简体   繁体   English

如何获取输出中的总行数

[英]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.我制作了这段代码,它基本上计算了使用便士、镍币、15 美分和一美元硬币制作一美元的所有不同组合。 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.您只需要在代码末尾使用len(solution) ,如下所示。

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) :在这种情况下,您可以使用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:虽然,FWIW,如果您确实需要列出清单,那么理解有点多余,而且更清晰:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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