Python program produces different results, even if random

I am trying to solve Project Euler Problem 19 .

I am not here to ask for an answer to this problem, but I noticed that every time my program runs, its output is different.

Please can someone explain why for me

"""
    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)
+6
source share
2 answers

, , months. Python 3.3, , , ( Python 3.6). , , , , months , , , list OrderedDict.

+6

datetime

dict OrderedDict s, datetime, , :

>>> from datetime import date
>>> sum(1 for month in range(1,13) for year in range(1901, 2001) if date(year, month, 1).weekday() == 6)
171

, Python 3.6 Python2 + OrderedDict 172.

i % 7 == 0. , 1- (1- 1901 ), tuesday, i = 2.

unsorted dicts, :

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 = 2
    for year in range(1901, 2001):
        for month_name, days in months:
            if month_name == "feb":
              if year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0):
                  days = 29
              else:
                  days = 28
            if i % 7 == 0:
                ans += 1
            i += days
    return ans

if __name__ == "__main__":
    answer = calculate()
    print(answer)

171 Python.

0

All Articles