下面是实际工作的代码。它返回任意长度的给定字符串(例如:: Permutations('ab') returns ['ab','ba] )的所有可能排列。
def permutations(string):
if len(string) == 1: return set(string)
first = string[0]
rest = permutations(string[1:]) #This is the line that i do not understand
result = set()
for i in range(0, len(string)):
for p in rest:
result.add(p[0:i] + first + p[i:])
return result我不知道rest = permutations(string[1:])正在做什么(上面的注释)。我试着像这样编写它,但是像这样写的时候它不能正常工作。
这两行代码有什么区别?
rest = permutations(string[1:]) 和
rest = string[1:]它似乎是在函数内部调用自己,但我不确定这会有什么不同。
发布于 2019-11-19 01:06:07
它正在做一个递归,这是编程中一个流行的概念。在每次迭代中,它都使用一个新字符串作为参数调用同一个函数,这是在切片 "string1:“之后获得的。
希望这能有所帮助。
https://stackoverflow.com/questions/58925198
复制相似问题