简体   繁体   中英

How to get the total number of lines in an output

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, but 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]

solution = [s for s in alter(n, coins, [])]
for s in solution:
  print(s)

You just need to use len(solution) at the end of your code like the following.

solution = [s for s in alter(n, coins, [])]
for s in solution:
  print(s)

print(f'Total no of possibilities: {len(solution)}')

Output:

Total no of possibilities: 243

You might not actually need to make a list. In that case, you could use enumerate(start=1) :

possibilities = alter(n, coins, [])
i = 0  # Just in case there are no possibilities
for i, p in enumerate(possibilities, 1):
    print(p)
print('Total number of possibilities:', i)

Or of course, you could do it manually:

i = 0
for p in possibilities:
    print(p)
    i += 1
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:

solution = list(alter(n, coins, []))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM