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. This is the same code (hitting the Rerun button) with nothing changed: 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 |