Skip to content

Update p031.py #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions python/p031.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()