class Step: l = [] d = {} limit = 0 def __init__(self, num): self.limit = 5 * num self.l = [0] * self.limit self.l[0] = 1 def __getitem__(self, key): if self.limit > key: return self.l[key] else: return self.d.setdefault(key, 0) def __setitem__(self, key, value): if self.limit > key: self.l[key] = value else: self.d[key] = value def collatz_step(x, path): global steps if steps[x - 1]: foot = steps[x - 1] + 1 while path: steps[path.pop() - 1] = foot foot += 1 return else: path.append(x) if x % 2: collatz_step(3 * x + 1, path) else: collatz_step(x // 2, path) def collatz_max(num): global steps for x in range(1, num + 1): if steps[x - 1]: continue collatz_step(x, []) return steps.l.index(max(steps.l[:num])) + 1 limit = 1000000 steps = Step(limit) print(collatz_max(limit))