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 thefind_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 inarr
(e.g — our list of numbers, strings, whatever) that we want to combine. All of the combinations are turned into a list usinglist
, then set to a variable namedcombos
.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.combinationslist
— 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 theirsum
, and appends the sum to thecombo_sums
list. The end result of thecombo_sums
list is:
[10, 11, 12, 13, 14]
print(min(combo_sums), max(combo_sums))
— This prints the minimum number incombo_sums
and the maximum number:
10 14