Python_程序实现发红包
发红包
200块钱 20个红包
将200块随机分成20份
基础版本:
1 import random 2 3 4 ret = random.sample(range(1, 200 * 100), 19) 5 ret = ret.sort() 6 ret.insert(0, 0) 7 ret.append(200 * 100) 8 l = [] 9 10 for i in range(10): 11 l.append((ret[i + 1] - ret[i]) / 100) 12 13 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)
进阶版:
1 import random 2 3 4 def red_packet(money, num): 5 ret = random.sample(range(1, money * 100), num - 1) 6 ret.extend([0, money * 100]) # 改进点 7 ret = ret.sort() 8 9 return [(ret[i + 1] - ret[i])/100 for i in range(num)] 10 11 ret = red_packet(100, 10)
12 print(ret)
生成器版
1 import random 2 3 4 def red_packet(money, num): 5 ret = random.sample(range(1, money * 100), num - 1) 6 ret.extend([0, money * 100]) 7 ret.sort() 8 9 for i in range(num): 10 yield (ret[i + 1] - ret[i]) / 100 11 12 red_packet(100, 10)