为何while循环无法终止?生日匹配计数程序问题求助
问题原因
你用错了随机数生成函数:random.sample(range(1,365), k=2) 是无重复采样,它会从1到364里挑出两个完全不同的数,所以birthdays[0] == birthdays[1]这个条件永远不可能成立,循环自然停不下来。另外原代码里range(1,365)的范围是1到364,如果你想覆盖全年365天,应该写成range(1,366)。
修正方案
要生成可能重复的两个随机数,有两种常用方法:
- 用
random.randint()分别生成两个独立随机数 - 用
random.choices()做有放回采样
方法1:用randint实现
import random def numberToSharedBirthday(): count = 0 found = False while not found: # 分别生成1-365的随机整数(包含两端) b1 = random.randint(1, 365) b2 = random.randint(1, 365) count += 1 if b1 == b2: found = True return count
方法2:用choices实现
random.choices支持有放回采样,允许选中重复元素:
import random def numberToSharedBirthday(): count = 0 found = False while not found: # 有放回采样2个1-365的随机数 birthdays = random.choices(range(1, 366), k=2) count += 1 if birthdays[0] == birthdays[1]: found = True return count
内容的提问来源于stack exchange,提问作者taylynn
相关产品推荐
相关产品推荐

