算法太慢;我选择相同的4个号码,中奖的几率更高吗?

时间:2018-10-14 19:33:24

标签: python python-3.x

这是问题陈述。

有一个彩票,每天选4个随机数字。 我想知道我是否有更好的中奖机会(比如说超过100万次试用)。

我添加了为解决该问题而编写的解决方案,但是运行起来非常慢。超过3000次试用都非常缓慢。

我已在代码中添加注释以显示我的推理

添加:我需要帮助才能找到瓶颈

ADD2:代码已完成,很抱歉,已重命名了几个变量

#lottery is 4 numbers
#lottery runs 365 days a year
#i pick the same number every day, what are my odds of winning/how many times will i win
#what are my odds of winning picking 4 random numbers
import random

my_pick = [4,4,4,7]
lotto_nums = list(range(0,9))
iterations = 3000

#function to pick 4 numbers at random
def rand_func ():
  rand_pick = [random.choice(lotto_nums) for _ in range(4)]
  return rand_pick

#pick 4 random numbers X amount of times
random_pick = [rand_func() for _ in range(iterations)]

#pick 4 random numbers for the lottery itself
def lotto ():
  lotto_pick = [random.choice(lotto_nums) for _ in range(4)]
  return lotto_pick

#check how many times I picked the correct lotto numbers v how many times i randomly generated numbers that would have won me the lottery
def lotto_picks ():
  lotto_yr =[]
  for _ in range(iterations):
    lotto_yr.append(lotto())
    my_count = 0
    random_count = 0
    for lotto_one in lotto_yr:
      if my_pick == lotto_one:
        my_count = my_count +1
      elif random_pick == lotto_one:
        random_count = random_count +1
  print('I have {} % chance of winning if pick the same numbers versus {} % if i picked random numbers. The lotto ran {} times'.format(((my_count/iterations)*100), ((random_count/iterations)*100), iterations))

lotto_picks()

2 个答案:

答案 0 :(得分:2)

代码之所以缓慢的原因是,在每次迭代中,您都在重新计算所有模拟。实际上,您需要检查每次模拟是否只赢了一次彩票。因此lotto_picks()应该看起来像这样:

def lotto_picks ():
  lotto_yr = []

  my_count = 0
  random_count = 0
  for _ in range(iterations):
    new_numbers = lotto()
    lotto_yr.append(new_numbers) # You can still save them for later analysis

    if my_pick == new_numbers:
      my_count = my_count +1

    if random_pick == new_numbers: # Changed from elif to if
      random_count = random_count +1

  print('I have {} % chance of winning if pick the same numbers versus {} % if i picked random numbers. The lotto ran {} times'.format(((my_count/iterations)*100), ((random_count/iterations)*100), iterations))

这将使您的程序在线性时间O(n)以及代码以quadratic time complexity O(n ^ 2)运行之前运行。

答案 1 :(得分:1)

您的问题是嵌套的for循环。 您的第一个for循环的初始运行时间约为O(n)(线性)。 对于每个初始迭代(假设 i ),您的嵌套循环都会运行 i 次。

for i in range(iterations):

    for lotto_one in i:

这意味着您的嵌套循环总共将运行4501500次(数字总和从1到3000)。将您的初始外循环迭代添加到其中(3000),您将获得4 504 500个“实际”迭代。这给了你O(n ^ 1.9)的运行时间,几乎是^ 2的运行时间。那是你的瓶颈。