亲宝软件园·资讯

展开

python实现抽奖小程序

人气:0

设计一个抽奖服务 

背景:有x个奖品,要求在y天内发完;每天至少发放z个奖品;每天抽奖人数不定,事先会假设一个范围是m-n

举例:有100个奖品,要求5天内发完,每天至少发15个奖品;每天来抽奖的人估计是 2000-3000 人,希望奖品能够比较均匀,但随机的抽取出来。

接口要求:服务监听一个端口,测试程序不断连接,发送一个数字代表是第几天,比如第1-2000个请求发送1(模拟第一天来了2000人),第2001到5000请求发送2(模拟第二天来了3000人)... 服务返回 0 or 1 表示是否抽到奖品

client.py:设置初始化参数,模拟用户向server端发送数据

# -*- coding: utf-8 -*-
import socket
import random

address = ('127.0.0.1', 31500)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

x = int(input("奖品个数x:"))
y = int(input("发放天数y:"))
z = int(input("每天至少发放奖品个数:"))
m = int(input("最少人数m:"))
n = int(input("最多人数n:"))

data = '{"x":'+str(x)+',"y":+'+str(y)+',"z":'+str(z)+',"m":'+str(m)+',"n":'+str(n)+'}'
s.sendto(data.encode('utf-8'), address)

for day in range(y):
 num = random.randint(m, n)
 print("第",day+1,"天人数为",num)
 k=0
 for k in range(num):
 s.sendto(str(day+1).encode('utf-8'), address)
s.close()

server.py:服务端接收初始数据和每个用户发送的数据

# -*- coding: utf-8 -*-

import socket
import lottery

address = ('127.0.0.1', 31500)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(address)

list=[]

data, addr = s.recvfrom(2048)
data = data.decode('utf-8')
print ("received:", data, "from", addr)
dic=eval(data)
x=dic['x']
y=dic['y']
z=dic['z']
m=dic['m']
n=dic['n']

k=0
preday = 1
while True:
 k += 1
 day, addr = s.recvfrom(2048)
 if not day:
 print ("client has exist")
 break
 if preday != day:
 list.append(k-1)
 preday = day
 day = int(day.decode('utf-8'))
 x -= lottery.check(x,y,z,m,n,k,day,list)
s.close()

lottery.py:抽奖程序算法

#Filename:lottery.py

def check(x,y,z,m,n,k,day,list):

 #估计到来当天的人数和奖品的个数
 if day == 1 or day == y:
 e_x = z
 e_people = n
 elif day == y:
 e_x = x
 e_people = n
 else:
 e_x = x/(y+1-day)
 e_people = sum(list)/len(list)
 
 #中奖间隔
 length = int(e_people/e_x)

 lucky = 0
 if x>0 and k%length == 0 :
 #print(x,"第",k,"个中奖")
 lucky = 1

 print("第",k,"个--第",day,"天--是否中奖--",lucky)
 return lucky

源码下载:python实现抽奖小程序

想要学习更多关于抽奖功能的实现,请参考此专题:抽奖功能

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论