12
下面的代碼生成的字符串的所有排列的所有排列:請解釋這種算法得到一個字符串
def permutations(word):
if len(word)<=1:
return [word]
#get all permutations of length N-1
perms=permutations(word[1:])
char=word[0]
result=[]
#iterate over all permutations of length N-1
for perm in perms:
#insert the character into every possible location
for i in range(len(perm)+1):
result.append(perm[:i] + char + perm[i:])
return result
你能解釋它是如何工作的?我不明白遞歸。
它看起來就像你在這裏有一個壓痕錯誤,另外,值得指出的是,這個代碼重新發明了車輪。標準庫中已經有'itertools.permutations' :-) - 雖然這並不能幫助你理解這段代碼。 – mgilson
「他」和「這個人」是什麼意思? –
@DavidRobinson我認爲這只是一種「可愛」的方式來詢問代碼中發生了什麼。我已經重寫了這個問題,直接要求解釋,我認爲這是提問者想要的(並已收到)。 – Blckknght