Reputation: 11
i have a problem to create a list of all possible combinations of a given list of words. the result should be a combination per line for all possible words. the max lengh of combination is based on the amount of words given in the input file. this means, if the file contains 7 words, the combination is max 7 words long. the output should be formated like shown below:
germany germanygermany germanygeranygermany germanyspain germanygermanyspain germanygermanyspain
etc etc.
i've googled a bit and figured out, that itertools would be a possible solution for me.
the given words are located in a file called input.txt
i used this code from the Stack overflow entry here:
How to get all possible combinations of a list’s elements?
i just represent the main part as the file read part and file output is not part of the problem here.
so my given list of words is: germany spain albania netherlands
which works fine
from itertools import combinations
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
The output is not as expected.
as my list contains 3 words i changed the code:
germany spain albania
which works fine
from itertools import combinations
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
but, i believe the result is not as expected, it should be ALL possible combinations. some combinations are missing, for example:
germany
germany germany
germany germany spain
germany germany germany
or something.
(the output is limited to 3 as the given list contains 3 words in the original question).
How do i get the germany germany etc combinations to the output and why are they missing? i believe i should have the same issues when i use numbers as pins or something. it cant start at 0 to 9999 but there should be a 00 and 000 and 0000 also in the list.
best regards Fred
Upvotes: 1
Views: 875
Reputation: 2516
I believe you want to use the function combinations_with_replacement:
from itertools import combinations_with_replacement
features = ['germany', 'spain', 'albania']
tmp = []
for i in range(len(features)):
oc = combinations_with_replacement(features, i + 1)
for c in oc:
tmp.append(list(c))
print (tmp)
Upvotes: 2