0

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. これを克服し、互いに一致する要素を保存するにはどうすればよいですか?
4

2 に答える 2

4

return path.append((x))その場で編集pathし、を返しますNone。の新しい値を返したい場合はpath、2行に分割してください。

path.append((x)) 
return path
于 2012-11-19T13:56:23.293 に答える
2

これは、コードの最後の行が原因です。

list.append()を返しますNone

次のように変更します。

path.append(x)
return path

また

return path + [x]
于 2012-11-19T13:57:24.820 に答える