return语句做什么?

2024-06-14 17:24:44 发布

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

我试图创建一个程序来计算生日悖论:

import random

def random_birthdays():
    count = 0
    res = []
    for i in range(23):
        res.append(random.randint(0, 365))
    res.sort()
    return res

def final():
    count = 0
    i = 0
    random_birthdays()
    for day in res:
        if res[i] == res[i + 1]:
            count = count + 1
            i = i + 1
        else:
            i = i + 1
    return count

def percentage():
    happens = 0
    for i in range(100):
        final()
        happens = happens + count
    percentage = happens / 100

percentage()

但是我得到了这个错误:for day in res: res not defined。你知道吗

我认为我理解Python的return部分的方式确实有问题,因为在我看来,它应该返回res,并在下一行中用作变量。你知道吗


Tags: in程序forreturndefcountrangeres
2条回答

重写一下:

from collections import Counter
from math import factorial
from random import randrange

def duplicate_birthday(n):
    """
    Given n people with random birthdays,
      do any of them share a birthday?
    """
    c = Counter(randrange(365) for _ in range(n))
    return max(c.values()) > 1

def monte_carlo(n, tries = 1000):
    return sum(1 for _ in range(tries) if duplicate_birthday(n)) / tries

def calculated_odds(n):
    """
    Given n people with random birthdays,
    calculate the odds that at least two share a birthday
    """
    all_combos = 365 ** n
    unique_combos = factorial(365) / factorial(365 - n)
    return 1. - unique_combos / all_combos

def main():
    print("Odds of N people sharing a birthday:")
    for n in range(20, 26):
        sim_pct = 100. * monte_carlo(n)
        calc_pct = 100. * calculated_odds(n)
        print("{:>2d}: {:>4.1f}% ({:>4.1f}%)".format(n, sim_pct, calc_pct))

if __name__ == "__main__":
    main()

这给了

Odds of N people sharing a birthday:
20: 42.5% (41.1%)
21: 42.0% (44.4%)
22: 48.8% (47.6%)
23: 50.7% (50.7%)
24: 52.2% (53.8%)
25: 55.9% (56.9%)        

欢迎来到这里!你知道吗

return需要将返回值存储在object中。你知道吗

def final():
       count = 0
       i = 0
       res = random_birthdays()
       for day in res:
            if res[i] == res [i+1]:
                 count = count +1
                 i = i+1
            else:
                i = i+1
        return count

相关问题 更多 >