gpt4 book ai didi

python - 从字符串 python 生成所有的字谜

转载 作者:太空狗 更新时间:2023-10-30 01:39:55 26 4
gpt4 key购买 nike

我今天在想这个问题,我来了以下伪代码(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

但是,我想知道一种执行此操作的 pythonic 方法: anagram = c + anagram( 字符串 - {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'

谢谢

最佳答案

为什么不直接使用 itertools

>>> import itertools
>>> ["".join(perm) for perm in itertools.permutations("abc")]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

documentation还包含如何完成排列的代码。


编辑:

Without itertools :

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))

没有 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

结果:

['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

关于python - 从字符串 python 生成所有的字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989502/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com