그래서 여러 개의 입력 된 문자를 사용하여 가능한 모든 위치에 단어 생성기를 만들고 단어를 찾기 위해 문서와 일치시킵니다. 내가이 잘못에 접근하면 나에게 말해줘! 어떻게하면 안되지? 감사 편지여러 글자의 모든 가능한 순열의 목록을 생성하려면 어떻게해야합니까?
2
A
답변
7
주어진 문자 목록의 모든 순열을 생성하려면 itertools 모듈을 사용하십시오.
import itertools
for word in itertools.permutations(list_of_letters):
print ''.join(word)
2
역순으로 실행하는 것이 더 빠릅니다. 문서의 색인을 생성하고 각 단어에 대해 글자 목록의 하위 집합인지 확인하십시오.
2
당신은 당신의 자신의 기능 (작성할 수 있습니다.
def permutation(head, tail=''):
if len(head) == 0:
print tail
else:
for i in range(len(head)):
permutation(head[0:i] + head[i + 1:], tail + head[i])
0
def allpermutationsOfString(words):
if len(words) == 1:
return [words]
result = []
for index, letter in enumerate(words):
wordWithoutLetter = words[:index] + words[index+1:]
result = result + [letter + word for word in allpermutationsOfString(wordWithoutLetter)]
return result
print allpermutationsOfString("watup") #will print all permutations of watup
여기 알고리즘을 구현하는 또 다른 방법은의를 문자열을 '렌 것을
주 (들) == n'의 순열의 수는'n! '이고, 이것은 꽤 빠르다. (예를 들어, 내 사용자 이름의 3,628,800 순열이있다.) – jonrsharpe