6

小案例--python编写设置拼手气红包模块

 2 years ago
source link: https://blog.51cto.com/u_14124898/5329319
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

小案例--python编写设置拼手气红包模块

原创

**此案例主要锻炼python基础逻辑思维能力​

**小编个人一直以为,看懂理解不难,难的是自行想到全部逻辑

拼手气红包发放,需满足:

设定金额与数量

金额最大为运气王

随机分配金额

# 附有多个输出用来解释每行代码

import random

def giveredpackets(total, num):
print('红包共{}元,分{}份'.format(total, num))
each = []
already = 0
average = total / num # 平均金额
print('average--', average)
for i in range(1, num):
print('i---------------:', i)
# 为当前抢红包的随机分配,至少给剩下的人每人留平均金额
print('total-already钱剩余:', total - already)
print('剩下人一共分此以上---', (num - i) * average)
t1 = random.uniform(0, (total - already) - (num - i) * average)
t = round(t1, 2)
# round参数第一个是需要四舍五入的数,第二个是小数点后位数
print('这次红包-----', t)
each.append(t)
print('现在红包序列---', each)
already += t
print('现已分配的总金额---', already)
print('----------------------------------------------')
# 剩下所有钱发给最后一个人
each.append(round(total - already, 2)) # 剩下的钱四舍五入 加入队列
print('运气王:', max(each)) # 我自己写的用这个也许在想不到的地方会有风险
# 下面是标准的 将表排序从小到大,用列表下标的方式 获取最后一个数字为最大的金额
print('运气王:', sorted(each)[num - 1])
random.shuffle(each) # 将类表中的数据顺序打乱 随机排列
print('最终红包序列-------:', each)
return each


if __name__ == '__main__':
total, num = 10, 6
giveredpackets(total, num)


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK