鉴于同事的疑惑
import random # import pylab def judge(discountPrice, energy, shell, fish): '''After User fired the shell, judge the result.''' if type(fish) == str: probabiliity = shell/eval(fish) capture = random.random() < probabiliity if capture: energy = energy + eval(fish) else: probabiliity = shell/fish capture = random.random() < probabiliity if capture: discountPrice = discountPrice - fish return discountPrice,energy def userBehavior(price, lowestDiscount, energy=0): '''Simulate teh User firing shells. ''' discountPrice = price energy = lowestDiscount if energy == 0 else energy shell = lowestDiscount/20 discountFishes = [i*discountPrice/10 for i in range(1, 10)] energyFishes = ['2*shell', '3*shell', '5*shell', '7*shell', '8*shell', '10*shell', '15*shell', '20*shell', '30*shell'] fishes = discountFishes + energyFishes fishNum = random.choice([1,1,1,1,2,2,3]) while energy >= shell and discountPrice > lowestDiscount: energy = energy - shell fish = random.choice(fishes) discountPrice, energy = judge(discountPrice, energy, shell, fish) return discountPrice def summary(price,lowestDiscount,frequency = 1000): '''repeat fishing 'frequency' times''' discountPrices = [] for k in range(frequency): discountPrice = (userBehavior(price, lowestDiscount)) discountPrices.append(discountPrice) print('平均折扣价 :', sum(discountPrices)/len(discountPrices), ' 平均获得折扣 :', round(sum(discountPrices)/len(discountPrices)/price, 2)) print('未获得折扣次数 :', discountPrices.count(price)) # pylab.plot(discountPrices) # pylab.title('discountPrice,%d time' % frequency) # pylab.xlabel('appear') # pylab.ylabel('discountPrice') summary(100, 10, frequency=1000)