如何在Python的递归函数中使用迭代器?

发布于 2024-12-04 01:19:56 字数 417 浏览 2 评论 0原文

我想转换我的代码,这样我就不必使用额外的变量(即下面示例中的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放赐 2024-12-11 01:19:56

为什么不只是...

def trav(root, s=""):

然后您可以省略 s = "" 行并将其称为 trav(a) ?另外,如果您愿意内联一两个东西,您可以减少切片:

from numbers import Number

a = [[[1,2],[3,4]],[[5,6],[7,8]]]


def trav(root, s=""):
    if isinstance(root, Number):
        print("%s -> %s" % (root, s))
    else:
        trav(root[0], s + "0")
        trav(root[1], s + "1")

trav(a)

请注意,这些都与迭代器无关;我不确定你在想什么。此处的 s 充当累加器参数;也许这就是您想到的术语?

Why not just...

def trav(root, s=""):

and then you can omit your s = "" line and call it as trav(a)? Also if you were willing to just inline a thing or two, you could do less slicing:

from numbers import Number

a = [[[1,2],[3,4]],[[5,6],[7,8]]]


def trav(root, s=""):
    if isinstance(root, Number):
        print("%s -> %s" % (root, s))
    else:
        trav(root[0], s + "0")
        trav(root[1], s + "1")

trav(a)

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文