所以我知道这个话题已被涵盖。但是,我自己实施它会遇到麻烦。
def permutation(word, fixed = [], passed = ""):
if passed != "":
fixed.append(passed)
if len(word) == 1:
fixed.append(word[0])
print fixed
else:
for i in range(len(word)):
passed = word[i]
rem = word[:i] + word[i+1:]
permutation(rem, fixed, passed)
permutation(["a","b","c"])
raw_input()
我尝试不返回值,而是转到基座然后打印结果。虽然当我这样做时,我得到以下内容:
['a', 'b', 'c']
['a', 'b', 'c', 'c', 'b']
['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c']
['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a']
['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a', 'c', 'a', 'b']
['a', 'b', 'c', 'c', 'b', 'b', 'a', 'c', 'c', 'a', 'c', 'a', 'b', 'b', 'a']
这似乎很接近,但是,我可以说固定收集所有输出,我不完全理解为什么。
当使用递归时,每个变量集都是函数调用的本地变量?这是我的理解,但事实并非如此。
这不是家庭作业btw。
为感兴趣的人更新了代码:
def permutation(word, fixed = "", passed = ""):
if passed != "":
fixed += passed
if len(word) == 1:
fixed += word[0]
print fixed
else:
for i in range(len(word)):
passed = word[i]
rem = word[:i] + word[i+1:]
permutation(rem, fixed, passed)
permutation(["a","b","c"])
raw_input()
产生输出: ABC ACB BAC BCA 出租车 CBA