我今天正在考虑这个问题,我带来了以下伪代码(Python 3.2):
def anagrams( string ):
for c in string:
anagram = c + anagram( string - {c} ) # remove the char from its position in the string
print(anagram)
return
def main():
word = "abcd"
anagrams( word )
return
Run Code Online (Sandbox Code Playgroud)
但是,我想知道这种操作的pythonic方法:anagram = c + anagram(string - {c})
我怎么能从字符串中删除该字符?例如:
"abc" -> 'a' + "bc" -> 'a' + 'b' + "c" -> 'a' + 'b' + 'c' = 'abc'
+ "cb" -> 'a' + 'c' + "b" -> 'a' + 'c' + 'b' = 'acb'
-> 'b' + "ac" -> 'b' + 'a' + "c" -> 'b' + 'a' + 'c' = 'bac'
+ "ca" -> 'b' + 'c' + "a" -> 'b' + 'c' + 'a' = 'bca'
-> 'c' + "ba" -> 'c' + 'b' + "a" -> 'c' + 'b' + 'a' = 'cba'
+ "ab" -> 'c' + 'a' + "b" -> 'c' + 'a' + 'b' = 'cab'
Run Code Online (Sandbox Code Playgroud)
谢谢
slo*_*oth 21
为什么不使用itertools?
>>> import itertools
>>> ["".join(perm) for perm in itertools.permutations("abc")]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Run Code Online (Sandbox Code Playgroud)
该文档还包含代码如何完成排列.
编辑:
def all_perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
yield perm[:i] + elements[0:1] + perm[i:]
word = "abc"
print list(all_perms(word))
Run Code Online (Sandbox Code Playgroud)
没有itertools
和没有generators
:
def all_perms(elements):
if len(elements) <=1:
return elements
else:
tmp = []
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
tmp.append(perm[:i] + elements[0:1] + perm[i:])
return tmp
Run Code Online (Sandbox Code Playgroud)
结果:
['abc','bac','bca','acb','cab','cba']
使用itertools
模块。
import itertools
perms = [''.join(perm) for perm in itertools.permutations('abc')]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18647 次 |
最近记录: |