Which kettlebells to buy? Possible unique combination sums of int values in Python
It is prime day and you are wondering which kettlebells to buy? What are the possible weight combinations of all different weights including using between one and all of them with a dip belt? Yeah that’s really the motivation of how this started 🙂
What became of if was a method taking multiple int values, checking if they are valid for my use case and calculate all possible combinations, sorting it and removing duplicates.
- Fail fast, so the validity checks are done first. Adapt for your use case as negative values are obviously not considered in mine.
- The set is used to eliminate duplicates.
- itertools.combinations is used for the generate tuples of length 1 to count of int values given – so in this case 1 to 3. This method does not repeat the same value in a tuple if it is not included multiple times in the list of numbers. This was important to me as I will only have the same weight once. If the same value is given multiple times as parameter this is fine and the values are considered in the calculation. Check documentation of combinations and combinations_with_replacement to see the difference. For better understanding uncomment the print(combo) line I left in there to see what is does in each iteration.
- As sets are unsorted, the sorted method is called. This is done only to easily compare the outputs.
from itertools import combinations
def unique_combinations(*numbers: int) -> None:
if numbers is None or len(numbers) < 2 or any(n is None or type(n) is not int or n < 1 for n in numbers):
print(f'Invalid input list')
else:
result = set()
for r in range(1, len(numbers) + 1):
for combo in combinations(numbers, r):
# print(combo)
result.add(sum(combo))
print(sorted(result))
# invalid list checks
# unique_combinations()
# unique_combinations(1)
# unique_combinations(2, 4, -3)
# unique_combinations(2, 4, '12')
# unique_combinations(2, 4, None)
# valid list check
unique_combinations(4, 8, 16, 22)
[4, 8, 12, 16, 20, 22, 24, 26, 28, 30, 34, 38, 42, 46, 50]
-> Check out my code in a playground
I ended up buying 4, 8 and 16kg. The next one will probably be another 16 or a 22kg.
Hope this helps you, too! I learned something today: AI is great to generate pictures with hilarious errors, but sometimes points you in the right direction when asking it how to make your code better. But don’t trust it. The halucinations are ridiculous in my opinion. Don’t forget to test your code! Normalls this code would have returned a set or a list and I would have written automated tests for it, but for this little lesson I just checked the output of the invalid list checks.
Have a nice day and don’t forget to have fun!