2

我正在用 Python 编写一个简单的算法来打印给定元素列表的所有排列,但遇到了一个我无法调试的错误:

def perm(prefix, rest):
    if len(rest) == 0:
        print prefix 
    print len(rest)
    for i in range(len(rest)):
        #The next 3 prints are for debugging purposes only
        print type(prefix)
        print "prefix=", prefix
        print "rest=", rest
        newprefix = prefix.append( rest[i])
        newrest = rest
        newrest.pop(i)
        perm(newprefix, newrest)


perm([], ['a','b','c'])

出于某种原因,在我的 for 循环的第一次迭代之后,我的变量“前缀”更改为 None 类型。这是我得到的输出:

3
<type 'list'>
prefix= []
rest= ['a', 'b', 'c']
2
<type 'NoneType'>
prefix= None
rest= ['b', 'c']
Traceback (most recent call last):
  File "self2.py", line 19, in <module>
    perm([], ['a','b','c'])
  File "self2.py", line 16, in perm
    perm(newprefix, newrest)
  File "self2.py", line 13, in perm
    newprefix = prefix.append( rest[i])
AttributeError: 'NoneType' object has no attribute 'append'
4

2 回答 2

4

list.append就地更改列表并返回None. 所以这一步newprefix实际上是经过None

newprefix = prefix.append( rest[i])
于 2013-04-29T01:53:32.287 回答
4

问题出在线路上

newprefix = prefix.append( rest[i])
perm(newprefix, newrest)

append返回None,然后传递Noneperm方法的下一个调用,因为newprefix已设置为None.

也许你想要

prefix.append(rest[i])
newprefix = prefix

但是,如果是这种情况,您可以将perm呼叫更改为perm(prefix, newrest)并且您根本不需要newprefix

于 2013-04-29T01:53:58.727 回答