在递归期间,数组变为无

时间:2012-11-19 13:54:01

标签: python arrays recursion

我试图将matches[0]的每个元素与matches[1]的每个元素相匹配,并最终得到哪个元素与哪个元素匹配。但在递归期间,变量path变为None

功能

def improve(ncipher,x): #probably do not have any problem
    for i in x:
        try:
            if x[i]!=ncipher[i]:
                return 0
        except:
            ncipher[i]=x[i]
    return ncipher
def find_indexes(matches,cipher,path):  #the function causing problems
    print 'matches=',matches,'cipher=',cipher,'path=',path,'\n'
    if len(matches)==0:
        return [(0)]
    for x in matches[0]:
        print 'x=',x,'path=',path
        cipher=improve(cipher,x[1])
        if cipher==0:
            return [(0)]
        path=find_indexes(matches[1:],cipher,path)
        if path==[(0)]:
            return [(0)]
        else:
            print 'path=',path
            return path.append((x)) 

输出

matches= [[['season', {'1': 's', '3': 'a', '2': 'e', '5': 'n', '4': 'o'}]], [['month', {'8': 'h', '5': 'n', '4': 'o', '7': 't', '6': 'm'}]]] cipher= {} path= [0] 

x= ['season', {'1': 's', '3': 'a', '2': 'e', '5': 'n', '4': 'o'}] path= [0]
matches= [[['month', {'8': 'h', '5': 'n', '4': 'o', '7': 't', '6': 'm'}]]] cipher= {'1': 's', '3': 'a', '2': 'e', '5': 'n', '4': 'o'} path= [0] 

x= ['month', {'8': 'h', '5': 'n', '4': 'o', '7': 't', '6': 'm'}] path= [0]
matches= [] cipher= {'1': 's', '3': 'a', '2': 'e', '5': 'n', '4': 'o', '7': 't', '6': 'm', '8': 'h'} path= [0] 

path= [0]
path= None

Traceback (most recent call last):
  File "E:\timepass\py\interviewstreet\fb_cipher.py", line 115, in <module>
    find_match(message,words)
  File "E:\timepass\py\interviewstreet\fb_cipher.py", line 67, in find_match
    sol_indexes=find_indexes(matches,{},[0])
  File "E:\timepass\py\interviewstreet\fb_cipher.py", line 24, in find_indexes
    return path.append((x))
AttributeError: 'NoneType' object has no attribute 'append'

问题

  1. 为什么path在递归过程中变为None
  2. 如何克服这一点并存储彼此匹配的元素?

2 个答案:

答案 0 :(得分:4)

return path.append((x))编辑了path并返回None。如果要返回path的新值,请将其拆分为两行。

path.append((x)) 
return path

答案 1 :(得分:2)

这是因为代码中的最后一行。

list.append()返回None

将其更改为:

path.append(x)
return path

return path + [x]