[Solved] Sum from random list in python


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

1

solved Sum from random list in python