1. 程式人生 > >關於網上python紅包演算法。

關於網上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)

經多驗證發現有不對的地方:


num=4以上就不行了,經久思考,發現這裡貌似出問題了:

if num-i <=2:
萬一num=4,5,6...呢,所以這裡得改下
if num-i >= 1:

這樣就行了哈。貼圖:

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