具有用户输入的生日悖论循环程序

时间:2017-11-27 05:38:04

标签: python

我正在制作一个生日悖论计划,它已基本完成

import random

duplicateNumber=0

def has_duplicates(listToCheck):
    number_set = set(listToCheck)

    if len(number_set) is not len(listToCheck):
        return True
    else:
        return False 

for i in range(0,1000):
    birthdayList=[]

    for j in range(0,23):  
        birthday=random.randint(1,365)
        birthdayList.append(birthday)

    x = has_duplicates(birthdayList)

    if x==True:
        duplicateNumber+=1

print ("after 1000 simulations with 23 students there were", duplicateNumber,"simulations with at least one match")

我想通过要求用户继续重复代码直到他们希望终止代码来改进我的代码。例如,代码将给出输出,然后询问用户是否要再次运行它。例如,输入是"是"代码将再次运行然后再次输出,但这次它很可能会有不同的重复值。然后,该过程将一次又一次地重复,直到用户输入“不”为止。然后程序将结束

1 个答案:

答案 0 :(得分:0)

将部分代码更改为 -

import random

duplicateNumber=0

def has_duplicates(listToCheck):
    number_set = set(listToCheck)

    if len(number_set) is not len(listToCheck):
        return True
    else:
        return False 
i=0
while True:
    if i>0:
        prompt = raw_input('Do you wish to continue?')
        if prompt.lower() == 'no':
            break
    birthdayList=[]

    for j in range(0,23):  
        birthday=random.randint(1,365)
        birthdayList.append(birthday)

    x = has_duplicates(birthdayList)

    if x==True:
        duplicateNumber+=1
    i += 1

print ("after ", i," simulations with 23 students there were", duplicateNumber,"simulations with at least one match")

循环无限循环,不断询问用户是否希望继续。他说不的时刻,打破循环并打印统计数据