0

In python, I have tested combinations with a fixed length, with and without repetition by using multiple for loops. For example if I wanted to test every combination of numbers up to 5 with a length of 2 and repetition allowed, I would do this:

list1=[1,2,3,4,5]
for a in list1:
    for b in list1:
        print(str(a)+','+str(b) )

This seems simple enough for a fixed length but it does not work so well with testing all different lengths. When the length is varying, using this strategy I would have to make 5 different sets of 1, 2, 3, 4 and 5 loops. This is already very verbose and ugly but as the list size gets larger, it gets exponentially worse. I am looking for a more eloquent and easy way to test all of these combinations in python.

tupui
  • 4,812
  • 2
  • 29
  • 45
Bigbadboybob
  • 688
  • 2
  • 8
  • 17

1 Answers1

1

You may call itertools.combinations in a loop:

import itertools
list1 = [1, 2, 3, 4, 5]

for i in range(1, len(list1)):
     print(list(itertools.combinations(list1, i)))

[(1,), (2,), (3,), (4,), (5,)]
[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

If your list1 has duplicates, you might consider dropping them by converting to a set and repeating the process.

cs95
  • 330,695
  • 80
  • 606
  • 657