Search code examples
pythonpython-3.xcombinationspython-itertoolscombinatorics

How can is solve Python 3.6 itertools error?


So, I have this very-very basic code:

t = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,90]
c = list(itertools.combinations(t, 5))
print(c)

When I run this it takes approximately 15 seconds and then it gives the following error:

Traceback (most recent call last):
  File "H:/<path>/main.py", line 13, in <module>
    print(c)
OSError: [Errno 22] Invalid argument

But, when I run this code:

t = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 7, 8, 9, 10]
c = list(itertools.combinations(t, 5))
print(c)

It gives me no error instead my desired output which is:

[(1, 2, 3, 4, 5), (1, 2, 3, 4, 6), (1, 2, 3, 4, 7), ... (10, 7, 8, 9, 10), (6, 7, 8, 9, 10)]

Why doesn't it works with more numbers in list t?

I don't insist on itertools so you can show me another example of doing this. It just has to give every combination without repetition.


Solution

  • Try this instead:

    t = range(1, 91)
    c = itertools.combinations(t, 5)
    
    for i in c:
        print(i)
    

    It ran in my computer about 10 minutes and finiseshes correctly with the last combination (86, 87, 88, 89, 90).

    The difference is that I didn't create a list, so c is a generator, i. e. it generates only 1 combination at a time, which I immediately printed.