from collections import deque from time import time input = "137826495" #input = "389125467" cups = [int(i) for i in list(input)] max_cup = max(cups) def my_popleft(cups, following): current = cups.popleft() if current in following: cups.extendleft(following[current]) del following[current] return current def run_on_cups(cups, iterations): cup_count = len(cups) max_cup = max(cups) following = {} start = time() print("Start") for i in range(0, iterations): current_cup = my_popleft(cups, following) one = my_popleft(cups, following) two = my_popleft(cups, following) three = my_popleft(cups, following) three_cups = [three, two, one] dest = current_cup while True: dest -= 1 if dest == 0: dest = max_cup if dest not in three_cups: break following[dest] = three_cups cups.append(current_cup) print("Time:", time() - start) while len(following) > 0: current = my_popleft(cups, following) cups.append(current) return cups res1 = run_on_cups(deque(cups), 100) print("Answer 1:", ''.join([str(i) for i in res1])) res2 = run_on_cups(deque(cups + list(range(10, 1000001))), 10000000) res2.rotate(- res2.index(1)) assert res2.popleft() == 1 a = res2.popleft() b = res2.popleft() print("Answer 2:", a * b)