退货声明有什么作用?

时间:2017-06-30 22:54:48

标签: 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的返回部分的方式确实存在一些问题,因为我看到它的方式应该返回res并将其用作下一行中的变量。

2 个答案:

答案 0 :(得分:0)

欢迎光临!

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

答案 1 :(得分:0)

有点重写:

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%)