Python Forum
Erratic Datetime result - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Erratic Datetime result (/thread-14959.html)



Erratic Datetime result - timsch - Dec-27-2018

To practise coding, I've been looking at Problem 14 of Project Euler, the longest Collatz sequence for numbers up to a million.
My code takes about 35 seconds to process a million numbers, and to get an estimate for the time to process 10 million numbers, I extracted the times for the powers of 10 (to practise coding, and a bit curious).

# Problem 14 Euler Project - Longest Collatz Sequence

from datetime import datetime


def iterate(n):
    numberIterations = 0
    while n > 1:
        if n % 2 == 0:
            n = n / 2
        else:
            n = 3 * n + 1
        numberIterations += 1
    return numberIterations


t1 = datetime.now()
term = []
timings = []
timeinterval = []
timings.append(t1)
no = 1
exponent = 1
maxsteps = 0
maxlimit = 1000 
for x in range(1, maxlimit+1):
    if x == 10**exponent:
        term.append(x)
        t2 = datetime.now() #This is the troublesome line 
        timings.append(t2)
        timeinterval.append(t2-t1)
        exponent += 1
        if iterate(x) > maxsteps:
            maxsteps = iterate(x)
            no = x
    else:
        if iterate(x) > maxsteps:
            maxsteps = iterate(x)
            no = x
print(maxsteps, no)
print(term)
print(timings)
print(timeinterval)
The line t2 = datetime.now() works erratically. This is the correct output.

Output:
178 871 [10, 100, 1000] [datetime.datetime(2018, 12, 27, 12, 52, 48, 557358), datetime.datetime(2018, 12, 27, 12, 52, 48, 557829), datetime.datetime(2018, 12, 27, 12, 52, 48, 558330), datetime.datetime(2018, 12, 27, 12, 52, 48, 575374)] [datetime.timedelta(microseconds=471), datetime.timedelta(microseconds=972), datetime.timedelta(microseconds=18016)]
This is the same code (hitting the Rerun button) with nothing changed:
Output:
178 871 [10, 100, 1000] [datetime.datetime(2018, 12, 27, 14, 26, 11, 347978), datetime.datetime(2018, 12, 27, 14, 26, 11, 347978), datetime.datetime(2018, 12, 27, 14, 26, 11, 349454), datetime.datetime(2018, 12, 27, 14, 26, 11, 367000)] [datetime.timedelta(0), datetime.timedelta(microseconds=1476), datetime.timedelta(microseconds=19022)]
The first instance of t2 in this second case is the same value as t1. There is no (to me) obvious pattern.

If a breakpoint is placed at t2 = datetime.now(), t2 is evaluated correctly at about 500 millionth of a second.

So my question is: "what am I doing wrong"?

I'm also wondering how to get rid of the datetime.datetime appearing each time in the output.

This is my first posting.

Thank you