哈哈,小脑筋转起来,想到一个简单优雅的实现
Here we go:
import random
def generate_red_packets(money_in_cents: int, number_of_red_packets: int) -> list[int]:
if number_of_red_packets money_in_cents:
raise ValueError("too many red packets")
flags = [0] * (money_in_cents - number_of_red_packets) + [1] * number_of_red_packets
temp = flags[:-1]
random.shuffle(temp)
flags[:-1] = temp
i = -1
red_packets = []
for j, x in enumerate(flags):
if x == 1:
# 找到红包
red_packet = j - i # 确认红包金额(分)
red_packets.append(red_packet)
i = j
return red_packets
money_in_cents = int(input("总金额(分): "))
number_of_red_packets = int(input("红包个数: "))
red_packets = generate_red_packets(money_in_cents, number_of_red_packets)
print("随机红包列表(分):", red_packets)