Search code examples
pythonpython-3.xlistdictionarysum

Python Find the sum of at least 2 numbers


If I have a list of numbers, for example [1, 2, 3, 4], how do I get a dictionary of two or more numbers and the sum of these numbers? The ideal dictionary that I am looking for looks like this:

num = [1, 2, 3]
ideal_dict = {[1,2]:3, [1, 3]:4, [1, 4]:5, [2, 3]:5, [2, 4]:6, [3, 4]:7, [1, 2, 3]:6, [2, 3, 4]:9, [1, 2, 3, 4]:10}

I would like your method to work with very large numbers which are not in sequence. "not in sequence" means not all the numbers are consequent. An example of a not in sequence list is [5, 3, 4, 8, 9].

Thank you for your time and consideration.


Solution

  • This could be solved using some of the logic of itertools recipes (powerset function).