一、random.uniform
help(random.uniform)
Help on method uniform in module random:
uniform(a, b) method of random.Random instance
Get a random number in the range [a, b) or [a, b] depending on rounding.
random.uniform用于随机返回指定范围内的浮点数,如下随机返回50-60范围内的浮点数:
random.uniform(50,60)
55.46093048529164
二、随机发红包流程
红包的金额cash,
人员persons,
一般0.01为最小值,为什么会来说还有最大值,你想假如一个10块的红包6个人抢第一个能抢了9.99,那么第二个人只有剩下0.01,后面的人没得强,这就有问题了。
所以最大值应该就是红包总金额减去最小值乘以人数(10-0.01x5),给后面的人每个人都预留0.01,才有得玩。
代码如下:
#!/usr/bin/env python
# encoding: utf-8
"""
@author: wanwei
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited.
@contact: wei_wan@sui.com
@software: pycharm
@file: random_hongbao.py
@time: 2019/5/7 19:01
@desc:
"""
#!/usr/bin/env python
# -*-coding:utf-8 -*-
import random
dic = {}
persons = ['KeLan', 'Monkey', 'Dexter', 'Superman', 'Iron Man', 'Robin']
def redpacket(cash, length, index):
if cash > 0 and length != 1:
n = round(random.uniform(0.01, cash - (0.01 * (length-1))), 2)
dic[persons[index]] = n
print(str(n).ljust(4, "0"))
length = length - 1
cash = cash - n
index = index + 1
redpacket(cash, length, index)
else:
dic[persons[index]] = round(cash, 2)
print(str(round(cash, 2)).ljust(4, "0"))
cash = 10.00
redpacket(cash, len(persons), 0)
print(dic)
print("手气最佳:", max(dic.items(), key=lambda x: x[1]))
print("总红包数之和:", sum(dic.values()))