Python程序输出不同的结果,即使没有使用随机

Luk*_*man 6 python python-3.x

我正在努力解决Project Euler Problem 19.

我不是在这里要求问题的答案,但我注意到每次我的程序运行时,它的输出都是不同的.

请有人为我解释原因

"""
    Author: Luke Spademan
    Calculates answer to project euler problem id19
    https://projecteuler.net/problem=19
"""


def calculate():
    ans = 0
    months = {
        "jan": 31,
        "feb": 28,
        "mar": 31,
        "apr": 30,
        "may": 31,
        "jun": 30,
        "jul": 31,
        "aug": 31,
        "sep": 30,
        "oct": 31,
        "nov": 30,
        "dec": 31,
    }
    i = 1
    for year in range(1901, 2001):
        for month in months:
            months["feb"] = 28
            if year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0):
                months["feb"] = 29
            if i % 7 == 0:
                ans += 1
            i += months[month]
    return ans

if __name__ == "__main__":
    answer = calculate()
    print(answer)
Run Code Online (Sandbox Code Playgroud)

jde*_*esa 6

问题是计算的结果取决于months迭代的顺序.从Python 3.3开始,字符串哈希默认是随机的,这意味着这个顺序不是确定性的(直到Python 3.6).您可以在这里阅读有关如何确定性地运行此程序的内容,尽管我认为您的目的是months始终以预定义的顺序迭代,在这种情况下它应该是a list或a OrderedDict.