我是
python的新手,并且以递归方式思考非常糟糕.这段代码给了我一个IndexError:字符串索引超出范围.我不知道如何纠正它.
def get_permutations(sequence):
def permutationhelp(sequence,chosen):
if sequence=="":
print(chosen)
else:
for i in range(len(sequence)):
c= sequence[i]
chosen +=c
sequence=sequence[i+1:]
permutationhelp(sequence,chosen)
sequence=c+sequence
chosen=chosen[:-1]
def permutation(sequence):
permutationhelp(sequence,"")
return permutation(sequence)
例:
get_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Traceback是这样的:
Traceback (most recent call last):
File "soRecursivePermutations.py", line 25, in
get_permutations('abc')
File "soRecursivePermutations.py", line 23, in get_permutations
return permutation(sequence)
File "soRecursivePermutations.py", line 20, in permutation
permutationhelp(sequence,"")
File "soRecursivePermutations.py", line 12, in permutationhelp
c= sequence[i]
IndexError: string index out of range