我正在编写一个模拟器,该模拟器可以检查每个盒子需要容纳多少个球,或者每个盒子至少需要有2个球(生日悖论)。我用python编写了脚本,它是如此之慢。我的朋友用C ++编写了一个程序,脚本速度更快。对于箱数= 1000,在我的python脚本中,它需要几分钟才能达到“永恒”。
有我的代码:
import numpy as np
import matplotlib.pyplot as plt
def check_every_box_is_occupied(boxes):
for box in boxes:
if box == 0:
return False
return True
def check_birthday_paradox(boxes):
for box in boxes:
if box >= 2:
return True
return False
def main():
number_of_tests = 100
birthday_paradox_graph = [[], []]
every_box_is_occupied_graph = [[], []]
boxes_max_num = 1000
for number_of_boxes in range(10, boxes_max_num + 1, 1):
print(number_of_boxes)
average_frequency_birthday_paradox = 0
average_frequency_every_box_is_occupied = 0
for index in range(number_of_tests):
for number_of_balls in range(1, number_of_boxes ** 2, 1):
boxes = np.array([0] * number_of_boxes)
for i in range(number_of_balls):
boxes[np.random.randint(number_of_boxes)] += 1
if check_birthday_paradox(boxes):
average_frequency_birthday_paradox += number_of_balls
break
for number_of_balls in range(number_of_boxes, number_of_boxes ** 2, 1):
boxes = np.array([0] * number_of_boxes)
for i in range(number_of_balls):
boxes[np.random.randint(number_of_boxes)] += 1
if check_every_box_is_occupied(boxes):
average_frequency_every_box_is_occupied += number_of_balls
break
plt.rcParams.update({'font.size': 15})
birthday_paradox_graph[0].append(number_of_boxes)
birthday_paradox_graph[1].append(average_frequency_birthday_paradox / number_of_tests)
every_box_is_occupied_graph[0].append(number_of_boxes)
every_box_is_occupied_graph[1].append(average_frequency_every_box_is_occupied / number_of_tests)
plt.figure(1)
plt.plot(birthday_paradox_graph[0], birthday_paradox_graph[1], 'ko')
plt.figure(2)
plt.plot(every_box_is_occupied_graph[0], every_box_is_occupied_graph[1], 'ko')
plt.show()
if __name__ == '__main__':
main()
您能帮我改进代码以使其更快吗?可以在原始python中使用吗?