所以我正在使用python,正在尝试编写一个给定字符串的方法,它将找到该字符串的每个组合并将其附加到列表中.我将给出字符串并显示所需的结果.
Hi so I'm working with python and I'm trying to write a method where given a string, it would find every combination of that string and append it to a list. I'll give the string and show the outcome that I want.
字符串: x ='上帝'
结果:
lst = ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']字母只能使用出现在给定字符串上的次数,因此,如果我们的字符串是'god','gg'或'goo'等不能附加.如果可以使用递归来做到这一点,那就太好了!
A letter can only be used by the number of times it appears on the string given, so if our string is 'god', 'gg' or 'goo' etc. cannot be appended. If this could be done using recursion that would be great!
推荐答案使用排列:
from itertools import permutations x = 'god' perms = [] for i in range(1, len(x)+1): for c in permutations(x, i): perms.append("".join(c)) print(perms) # ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']