diff --git a/python/p031.py b/python/p031.py index 6186899..0dad072 100644 --- a/python/p031.py +++ b/python/p031.py @@ -6,20 +6,30 @@ # https://github.com/nayuki/Project-Euler-solutions # - -# We use the standard dynamic programming algorithm to solve the subset sum problem over integers. -# The order of the coin values does not matter, but the values need to be unique. def compute(): - TOTAL = 200 - - # At the start of each loop iteration, ways[i] is the number of ways to use {any copies - # of the all the coin values seen before this iteration} to form an unordered sum of i - ways = [1] + [0] * TOTAL - for coin in [1, 2, 5, 10, 20, 50, 100, 200]: - for i in range(len(ways) - coin): - ways[i + coin] += ways[i] - return str(ways[-1]) + from itertools import combinations_with_replacement + + cvs = [1, 2, 5, 10, 20, 50, 100, 200] # Coins and their values + TOTAL = 10 # Use 10 coins (for example) + count = 0 # Solutions (combinations) counter + tracing = True # Not necessary but used just for tracing the combinations + if tracing: + sol = [] # List with solutions + lst = sorted(list(combinations_with_replacement(cvs, TOTAL))) + for i in range(len(lst)): + if sum(lst[i]) == 200: + count += 1 + if tracing: + sol.append(lst[i]) + print("Total combinations:", count) + if tracing: + print("Solutions:", sol) + ''' + Total solutions: 22 + Solutions: [(1, 1, 1, 1, 1, 5, 20, 20, 50, 100), (1, 1, 1, 2, 5, 10, 10, 20, 50, 100), (1, 1, 1, 2, 5, 20, 20, 50, 50, 50), (1, 1, 2, 2, 2, 2, 20, 20, 50, 100), ... + (10, 10, 10, 20, 20, 20, 20, 20, 20, 50), (20, 20, 20, 20, 20, 20, 20, 20, 20, 20)] + ''' if __name__ == "__main__": - print(compute()) + compute()