taylynn
taylynn

Reputation: 1

Why won't my while loop repeat the calculations more than once?

I'm trying to program something that checks to see if two birthdays match, and counts how many birthdays have to be generated before we get a matching date. The actual date isn't important so I used the random.sample function to generate two numbers between 1 and 365. However when I try to compare these numbers in a while loop, I cannot get it to generate those numbers more than once.

import random
def numberToSharedBirthday():
    numberToSharedBirthday = 0
    sharedBirthday = False
    while sharedBirthday == False:
        birthdays = random.sample(range(1,365), k = 2)
        numberToSharedBirthday +=1 
#adds to the counter until the dates match
        if birthdays[0] == birthdays[1]:
            sharedBirthday = True
    return numberToSharedBirthday

When I run the code, the while loop doesn't end because it never satisfies the if statement. What am I doing wrong?

Upvotes: 0

Views: 52

Answers (2)

Arifa Chan
Arifa Chan

Reputation: 1017

Slight changes using choices and walrus operator:

from random import choices

def numberToSharedBirthday():
    numberToSharedBirthday = 0
    while birthdays := choices(range(1, 366), k=2):
        numberToSharedBirthday += 1
        if birthdays[0] == birthdays[1]:
            return numberToSharedBirthday

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 177665

The documentation for random.sample (emphasis mine):

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

You'll never pick the same two numbers.

Try random.choices instead:

Return a k sized list of elements chosen from the population with replacement.

Also note that range(1,365) return 1-364, not 1-365.

Upvotes: 2

Related Questions