发红包
200块钱 20个红包
将200块随机分成20份
基础版本:
import random ret = random.sample(range(1, 200 * 100), 19)
ret = ret.sort()
ret.insert(0, 0)
ret.append(200 * 100)
l = [] for i in range(10):
l.append((ret[i + 1] - ret[i]) / 100) print(l)
函数版本:
import random def red_packet(money, num):
ret = random.sample(range(1, money * 100), num - 1)
ret = ret.sort()
ret.insert(0, 0)
ret.append(money * 100) for i in range(num):
l.append((ret[i + 1] - ret[i]) / 100) return l ret = red_packet(100, 10)
print(ret)
列表推导式版本:
import random def red_packet(money, num):
ret = random.sample(range(1, money * 100), num - 1)
ret = ret.sort()
ret.insert(0, 0)
ret.append(money * 100) return [(ret[i + 1] - ret[i]) / 100 for i in range(num)] ret = red_packet(100, 10)
print(ret)
进阶版:
import random def red_packet(money, num):
ret = random.sample(range(1, money * 100), num - 1)
ret.extend([0, money * 100]) # 改进点
ret = ret.sort() return [(ret[i + 1] - ret[i])/100 for i in range(num)] ret = red_packet(100, 10)
12 print(ret)
生成器版
import random def red_packet(money, num):
ret = random.sample(range(1, money * 100), num - 1)
ret.extend([0, money * 100])
ret.sort() for i in range(num):
yield (ret[i + 1] - ret[i]) / 100 red_packet(100, 10)