递归生成器

列文

如标题所示,我正在尝试创建一个递归生成器,以查找给定列表的每个排列。这是我想出的功能,它不起作用:

def Permutations(l):
    if len(l) == 1:
        yield l
    else:
        for i in l:
            for j in Permutations(l[:i]+l[i+1:]):
                yield [i].extend(j)
            
l1 = [1,2,3]

for p in Permutations(l1):
    print(p)

我得到的错误是:

Traceback (most recent call last):
  File "idk.py", line 11, in <module>
    for p in Permutations(l1):
  File "idk.py", line 7, in Permutations
    yield [i].extend(j)
TypeError: 'NoneType' object is not iterable
MZ

您的代码有几个问题

def Permutations(l):
    if len(l) == 1:
        yield l
    else:
        for idx, i in enumerate(l):
            for j in Permutations(l[:idx]+l[idx+1:]):
                yield [i] + j
                """ or
                lst = [i]
                lst.extend(j)
                yield lst"""
  1. 您正在使用该值i作为列表的索引
  2. .extend不返回任何内容,因此您遇到了NoneType错误

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章