我很难理解Python中的这段代码
下面是实际工作的代码。它返回任意长度的给定字符串的所有可能排列 例如:我很难理解Python中的这段代码,python,permutation,Python,Permutation,下面是实际工作的代码。它返回任意长度的给定字符串的所有可能排列 例如:置换('ab')返回['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
置换('ab')返回['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:])
及
它似乎在函数内部调用自己,但我不确定这会有什么不同。它在做一个,编程中的一个流行概念。在每次迭代中,它都使用一个新字符串作为参数调用同一个函数,该参数是在“string[1:]”之后获得的
希望这有帮助。这是一个对切片字符串递归调用置换函数。字符串[1:]表示字符串的切片[start:end]。这是很好的切片阅读材料是的,这很有意义。我很感谢你的回复,这帮了我很大的忙!
rest = string[1:]