I have a relatively simple question. I made this code that basically calculates all the different combinations to make a dollar using pennies, nickels, quarters and dollar coins. The code works fine,its just that I need it to also tell me the total number of possibilities it printed, at the end of the code. I would appreciate some help :)
def alter(s, coins_free, coins_in_use):
if sum(coins_in_use) == s:
yield coins_in_use
elif sum(coins_in_use) > s:
pass
elif coins_free == []:
pass
else:
for c in alter(n, coins_free[:], coins_in_use [coins_free[0]]):
yield c
for c in alter(n, coins_free [1:], coins_in_use):
yield c
n = 100
coins = [1, 5, 10, 25, 100]
soloution = [s for s in alter(n, coins, [])]
for s in soloution:
print(s)
CodePudding user response:
You just to add print(f'Total no of possibilities: {len(soloution)}')
line at the end of your code like following.
Printing Code:
soloution = [s for s in alter(n, coins, [])]
for s in soloution:
print(s)
print(f'Total no of possibilities: {len(soloution)}')
Output:
Total no of possibilities: 243
CodePudding user response:
You might not actually need to make a list. In that case, you could use enumerate(start=1)
:
possibilities = alter(n, coins, [])
for i, p in enumerate(possibilities, 1):
print(p)
print('Total number of possibilities:', i)
Although, FWIW, if you do need to make a list, the comprehension is kind of redundant and this is cleaner:
soloution = list(alter(n, coins, []))