1. 题目🔍
使用random()
模拟10次发红包的情况。
1.1 输入样例
请输入红包总金额:100
请输入红包总数量:8
1.2 输出样例
[11, 34, 16, 14, 2, 16, 2, 5]
[65, 26, 2, 1, 1, 2, 1, 2]
[30, 61, 3, 2, 1, 1, 1, 1]
[70, 10, 12, 1, 3, 1, 1, 2]
[14, 43, 31, 2, 7, 1, 1, 1]
[64, 11, 18, 3, 1, 1, 1, 1]
[91, 3, 1, 1, 1, 1, 1, 1]
[27, 24, 14, 2, 21, 4, 2, 6]
[64, 11, 6, 2, 14, 1, 1, 1]
[36, 19, 15, 12, 1, 8, 2, 7]
2. 题解✨
2.1 代码
import random
a = int(input('请输入红包总金额:'))
b = int(input('请输入红包总数量:'))
def dis_lucky_money(total, num):
pack = [] # 以列表形式存储分配的红包金额
already = 0 # 已经分配的金额
# 前num-1次的分配情况
for j in range(1, num):
least_remain = num - j # 后几个红包中至少含有的总金额
money = random.randint(1, (total - already) - least_remain) # randint取值范围包含首尾 <区别于range()>
pack.append(money)
already += money
pack.append(total - already) # 将剩余的钱作为最后一个红包,添加至红包分配列表
print(pack)
# 随机生成10次
for i in range(10):
dis_lucky_money(a, b)
相关内容