问题
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.
string: x = 'god'
outcome:
lst = ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']
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!
回答1:
Use permutations:
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']
回答2:
Use itertools.permutations and list comprehensions
from itertools import permutations
[''.join(j) for i in range(1,len(x) + 1) for j in permutations(x, i)]
Output
['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']
回答3:
You want to use itertools
. From what you write, it sounds like you want to use itertools.permutation
.
>>> import itertools
>>> letters = 'god'
>>> combinations = []
>>> for i in range(len(letters)):
... combinations.extend(
... [''.join(x) for x in itertools.permutations(letters, i + 1)])
>>> print(combinations)
['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog']
回答4:
What you're trying to do here is to take the powerset of whatever string you pass in. What you'll want to do is convert that string into a list of characters, and then use the definition of powersets to use simple list extension to create what you are looking for.
def list_powerset(lst):
# the power set of the empty set has one element, the empty set
result = [[]]
for x in lst:
# for every additional element in our set
# the power set consists of the subsets that don't
# contain this element (just take the previous power set)
# plus the subsets that do contain the element (use list
# comprehension to add [x] onto everything in the
# previous power set)
result.extend([subset + [x] for subset in result])
return result
The above code was found at http://rosettacode.org/wiki/Power_set#Python
回答5:
import itertools
def _itersubs(x):
for i in range(1, len(x)+1):
yield from itertools.permutations(x, i)
# before 3.4, replace with:
# for y in itertools.permutations(x, i): yield y
def thefuncyouwant(x):
return list(_itersubs(x))
I'm not sure you actually want a list of 2 ** len(x)
items -- it will take a lot of memory for any x
not very short -- but, it's what you asked for, so here it is. The iterator yielding one item at a time is obviously more natural and probably preferable, but just wrapping it in a list
call will eat up just as much memory as you crave!-)
来源:https://stackoverflow.com/questions/28870709/python-every-possible-combination-of-a-string