Python计算付款方式

img


只想到用for循环的嵌套,不知道这个思路对不对,还是不知道从哪开始写写,应该从哪里入手

稍等,帮你写一个

说白了,这就是鸡兔同笼问题,只不过2种动物你分别认为有20和10只脚而已。


total = 200  # 需要支付的总额
count = 0    # 统计方案总数

for i in range(21):  # 枚举20元数量
    for j in range(51):  # 枚举10元数量
        if i * 20 + j * 10 == total:  # 判断是否可以凑出总额
            print("20元:%d张,10元:%d张,总数:%d" % (i, j, i + j))
            count += 1

print("共有%d种支付方式。" % count)


count = 0 # 计数器
for i in range(21): # 20元面值可以有020for j in range(51): # 10元面值可以有050if i*20 + j*10 == 200: # 如果总金额为200count += 1 # 计数器加1
            print(f"第{count}种方式:{i}张20元,{j}张10元") # 输出这种方式对应的张数
print(f"共有{count}种方式") # 输出总共的方式数

def count_payment_methods(total_amount, bills):
    """
    :param total_amount: 需要支付的总金额
    :param bills: 可以使用的纸币面额列表
    :return: 方案数量和每种方案的详情
    """
    methods = []
    bill_count = len(bills)
    for i in range(0, bill_count+1):
        for j in range(0, bill_count+1-i):
            if i * bills[0] + j * bills[1] == total_amount:
                method = {bills[0]: i, bills[1]: j}
                methods.append(method)
    return len(methods), methods


# 测试
total_amount = 200
bills = [20, 10]
count, methods = count_payment_methods(total_amount, bills)
print('方案数量:', count)
for method in methods:
    print('-----------------')
    for key in method:
        print(key, '元的张数:', method[key])