Search code examples
pythonlistrandomsumzero

Sum from random list in python


I have created a random list of 60 numbers, I don't know the numbers contained in the list. I'm asked to find any combination of three numbers from the list that sum to zero. What can I do? That's my code:

import random
import itertools
result = []

for x in range (-30, 30):
   num = random.randint(-30, 30)
   while num in result:
     num = random.randint(-30, 30)
     result.append(num)
        result = [seq for i in range(len(result), 0, -1) for seq in itertools.combinations(result, i) if sum(seq) == 0]
print result

Solution

  • There is a function combinations in itertools and it can be used to generate combinations.

    import random
    import itertools
    # Generate a random list of 30 numbers
    mylist = random.sample(range(-50,50), 30)
    
    combins = itertools.combinations(mylist, 3)
    interested = list(filter(lambda combin: sum(combin) == 0, combins))
    print(interested)
    

    Note that the results from filter() and itertools.combinations() are iterables and list() is needed to convert the iterable to a list.

    lambda expression lambda combin: sum(combin) == 0 is used to keep the combinations which the sum is zero from combins

    itertools.combinations(): https://docs.python.org/3.6/library/itertools.html#itertools.combinations

    filter(): https://docs.python.org/3.6/library/functions.html?highlight=filter#filter