关于网上python红包算法。

今天在python新手群(我是新手~)看见一个python红包算法,闲来无事,码下算法看看。如下:

#coding=gbk
import random
import sys
#print random.randint(0, 99)
#print "====", random.uniform(0, 0.99)
def calRandomValue(min, max, total, num):
    print min, max, total, num
    total = float(total)
    num = int(num)
    min = 0.01
    if(num < 1):
        return
    if num == 1:
        print "第%d个人拿到红包数为:%.2f" %(num, total)
        return
	
    i = 1
    total_money = total
    #rtotal = (total*100 - min*num*100)/100
    while( i < num ):
        max = total_money - min*(num- i)
        k = int((num-i)/2)
        if num -i<= 2:
            k = num -i
            max = max/k
            monney = random.randint(int(min*100), int(max*100))
            monney = float(monney)/100
            total_money = total_money - monney
            print "第%d个人拿到红包数为:%.2f, 余额为: %.2f" %(i, monney, total_money)
            i += 1
	
    print "第%d个人拿到红包数为:%.2f, 余额为: %.2f" %(i, total_money, 0.0)
if __name__ == "__main__":
    min = sys.argv[1]
    max = sys.argv[2]
    total = sys.argv[3]
    num = sys.argv[4]
    calRandomValue(min, max, total, num)

经多验证发现有不对的地方:

关于网上python红包算法。_第1张图片

num=4以上就不行了,经久思考,发现这里貌似出问题了:

if num-i <=2:
万一num=4,5,6...呢,所以这里得改下

if num-i >= 1:

这样就行了哈。贴图:

关于网上python红包算法。_第2张图片


ok!今天大年初二哈~~~~~~over

你可能感兴趣的:(Python学习笔记)