如何在Python的递归函数中使用迭代器?
我想转换我的代码,这样我就不必使用额外的变量(即下面示例中的 s )。我知道有一种方法可以使用迭代器,但我不知道如何使用。有人可以帮忙吗?非常感谢。
from numbers import Number
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
def trav(root,s):
if isinstance(root,Number):
print(str(root) + " -> " + s)
else:
s = s + "0"
trav(root[0],s)
s = s[:-1]
s = s + "1"
trav(root[1],s)
s = s[:-1]
s = ""
trav(a,s)
I want to convert my code such that I don't have to use an extra variable (i.e, s in the example below). I know that there is a way to use iterator but I don't know how. Can somebody help? Thanks a bunch.
from numbers import Number
a = [[[1,2],[3,4]],[[5,6],[7,8]]]
def trav(root,s):
if isinstance(root,Number):
print(str(root) + " -> " + s)
else:
s = s + "0"
trav(root[0],s)
s = s[:-1]
s = s + "1"
trav(root[1],s)
s = s[:-1]
s = ""
trav(a,s)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不只是...
然后您可以省略
s = ""
行并将其称为trav(a)
?另外,如果您愿意内联一两个东西,您可以减少切片:请注意,这些都与迭代器无关;我不确定你在想什么。此处的
s
充当累加器参数;也许这就是您想到的术语?Why not just...
and then you can omit your
s = ""
line and call it astrav(a)
? Also if you were willing to just inline a thing or two, you could do less slicing:Note that none of this has anything to do with iterators; I'm not sure what you were thinking of there.
s
here acts as an accumulator argument; perhaps that's the term you were thinking of?