python 最小硬币数_最小硬币数量的动态规划

我需要创建一个程序,要求最低数额的硬币输入随机数额给定。我遇到了一个问题,在不破坏程序的情况下,实际需要最低金额。我还有这条线的程序:print (x, "cents requires", val[0], "coins:", val[1])

只显示99美分的结果。我不知道我需要改变什么来修复它。我觉得问题在于:

^{pr2}$

我试过用if total == amount and amount == #(I've tried multiple different variables here.)# imports

import random

# program welcome

print("The purpose of this exercise is to enter the least number of coin values")

print("that add up to a displayed target value. \n")

print("Enter coins values as 1-penny, 5-nickel, 10-dime, and 25- quarter.")

print("Hit return after the last entered coin value.")

print("-------------------")

# init

terminate = False

empty_str = ""

# start game

while not terminate:

amount = random.randint(1,99)

print("Enter coins that add up to", amount, "cents, one per line.\n")

game_over = False

total = 0

while not game_over:

valid_entry = False

coins = [1, 5, 10, 25]

d = {}

# finds the minimum # of coins needed to

def m(cents):

if cents in d.keys():

return d[cents]

elif cents > 0:

choices = [(m(cents - x)[0] + 1, m(cents - x)[1] + [x]) for x in coins if cents >= x]

d[cents] = min(choices)

return d[cents]

else:

d[0] = (0, [])

return d[0]

for x in range(1, 100):

val = m(x)

while not valid_entry:

if total == 0:

entry = input("Enter first coin: ")

else:

entry = input("Enter next coin: ")

if entry in (empty_str, "1", "5", "10", "25"):

valid_entry = True

else:

print ("Invalid entry")

if entry == empty_str:

if total == amount:

print("Correct!")

game_over = True

if game_over:

entry = input("\nWould you like to play again (y/n)?: ")

if entry == "n":

terminate = True

else:

print("Sorry - you only entered", total, "cents")

print (x, "cents requires", val[0], "coins:", val[1])

game_over = True

else:

total = total + int(entry)

if total > amount:

print("Sorry - total amount exceeds", amount, "cents.")

game_over = True

if game_over:

entry = input("\nTry again (y/n)?: ")

if entry == "n":

terminate = True

print("Thanks for playing! Goodbye!")`

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值