How to find all possible combinations in a list (and their sum) with Python

Mini-learns with Python 3

image

While learning to code it’s easy to push through from exercise to exercise, chasing the feeling of accomplishment. I find that everything sinks in more, though, if I take a moment to flesh out my thought process from time to time.

I came across a problem on Hackerrank the other day that required me to find all possible sums of four out of five integers in a list. I’m making a note of what I did here, for future reference.

I used the combinations attribute from the itertools module.

To import this into our Python REPL or code

from itertools import combinations

The function

def find_combos(arr):
    combos = list(combinations(arr, 4))
    print(combos)

Breaking this down

  • arr — This will be the list we pass into the find_combos function. Ex: [1, 2, 3, 4, 5]
  • combos = list(combinations(arr, 4)) — Combinations takes two parameters. The first (arr) is what we are iterating over. The second (4), is how many of those things in arr (e.g — our list of numbers, strings, whatever) that we want to combine. All of the combinations are turned into a list using list, then set to a variable named combos.
  • combinations — This is what we imported from itertools that does the dirty work behind the scenes. The code for this can be found in the Python documentation: https://docs.python.org/3/library/itertools.html#itertools.combinations
  • list — This is a built-in function in Python. My layperson’s way of understanding this is that it turns all those combinations into a list that we can iterate over: https://docs.python.org/3/library/stdtypes.html#lists

The output

Using this as our list:

arr = [1, 2, 3, 4, 5]

Then passing it into our function:

find_combos(arr)

The result is:

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

Taking it further

The purpose of the exercise was to find the smallest and largest sum of these possible combinations. To do this, I fleshed out my code as follows:

def find_combos(arr):
    combos = list(combinations(arr, 4))
    combo_sums = []
    for combo in combos:
        combo_sums.append(sum(combo))
    print(min(combo_sums), max(combo_sums))
  • combo_sums = [] — This creates an empty list to dump all my sums into.
  • The for loop iterates through each combo (or combination of four numbers that we saw in the above result: [(1, 2, 3, 4), (1, 2, 3, 5)… etc.), takes their sum, and appends the sum to the combo_sums list. The end result of the combo_sums list is:
[10, 11, 12, 13, 14]
  • print(min(combo_sums), max(combo_sums)) — This prints the minimum number in combo_sums and the maximum number:
10 14

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics