python random.uniform用于随机发红包

博客介绍了Python中random.uniform函数,可随机返回指定范围内的浮点数。还阐述了随机发红包流程,指出红包金额最大值应是总金额减去最小值乘以人数,要给后面的人预留金额,保证都能参与,并给出相关代码思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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()))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值