Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program outputting different results, even though no random is used

I am trying to solve Project Euler Problem 19.

I am not here to ask for the answer to the 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)
like image 666
Luke Spademan Avatar asked Sep 04 '17 09:09

Luke Spademan


People also ask

How do you stop a Python code if not met?

To stop code execution in Python you first need to import the sys object. After this, you can then call the exit() method to stop the program from running.

Why am I not getting any output in Python?

One of the reasons of why your Python script does not show any output is because it buffers stdout and stderr steams instead of printing them. This also can happen if you execute the Python script from a CI/CD pipeline (e.g. using Jenkins, Gitlab-CI, TeamCity, etc.) or if you run it using a Dockerfile .


1 Answers

The problem is that the result of the computation depends on the order in which months is iterated. As of Python 3.3, string hashing is randomized by default, meaning that this order will not be deterministic (until Python 3.6). You can read about how to make this program run deterministically here, although I think that your intention is to iterate months in a predefined order always, in which case it should probably be a list or an OrderedDict.

like image 171
jdehesa Avatar answered Oct 19 '22 06:10

jdehesa