1

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

Fred
  • 11
  • 2

1 Answers1

2

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)
jprebys
  • 2,469
  • 1
  • 11
  • 16
  • Thanks for the possible solution. when using 1,2,3,4 as features, at least the 2,1 is missing. therefore, i still believe its not complete. [['1'], ['2'], ['3'], ['4'], ['1', '1'], ['1', '2'], ['1', '3'], ['1', '4'], ['2', '2'], ['2', '3'], ['2', '4'], ['3', '3'], ['3', '4'] – Fred Nov 28 '22 at 07:19
  • You said combinations, not permutations. My answer gives all combinations. In this case [2, 1] is the same as [1, 2]. If you want a different answer, you should update your question. – jprebys Nov 29 '22 at 14:44