将while循环更改为for循环以查找两个生日相同的人

2024-10-01 22:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

import random

def findSameBDay():
    birthdays = []
    birthday = random.randint(1, 365)
    count = 1
    while birthday not in birthdays:
        count += 1
        birthdays.append(birthday)
        birthday = random.randint(1, 365)
    return count

我想把while循环改成for循环,我试着把它转换成for循环,但是我没有任何线索


Tags: inimportforreturndefcountnotrandom
2条回答

您可以使用迭代器

import random

class BirthdayMgt:
    def __init__(self):
        self.birthdays = []
        self.count = 0

    def __iter__(self):
        return self

    def __next__(self):
        new_birthday = random.randint(1, 365)
        self.count += 1
        if new_birthday in self.birthdays:
            raise StopIteration
        self.birthdays.append(new_birthday)
        return new_birthday

birthday_mgt = BirthdayMgt()
for birthday in birthday_mgt:
    pass
print(birthday_mgt.count)

但是很恶心

您可以使用以下方法:

  1. 构建一个生成器函数,以便在for循环中每次调用它时都获得一个新的随机生日
def get_birthdays():
  birthday = random.randint(1, 365)
  yield birthday
  1. 之后,您可以使用递归方法重新编写findSameBDay()。对于get_birthdays(生成器)生成的每个数字,您将把它保存在birthdays函数参数中。当局部变量birthday位于生成器填充的列表中时,将出现停止条件
def findSameBDay(birthdays=[]):
    birthday = random.randint(1, 365)
    for generator_birthday in get_birthdays():
      birthdays.append(generator_birthday)
      if birthday in birthdays:
        break
      else:
        findSameBDay(birthdays)
    return len(birthdays)

# We call the function
findSameBDay()

相关问题 更多 >

    热门问题