from collections import deque p1 = deque() p2 = deque() with open('input', 'r') as f: f.readline() # player 1 while (line := f.readline()) and line != '\n': p1.append(int(line)) f.readline() # player 2 while (line := f.readline()) and line != '\n': p2.append(int(line)) print('p1:', p1) print('p2:', p2) def game(p1, p2): rounds = set() while len(p1) and len(p2): # prevent infinite games round_hash = str(p1) + str(p2) if round_hash in rounds: return 1 rounds.add(round_hash) a = p1.popleft() b = p2.popleft() # check if each player has enough cards for recursion if len(p1) >= a and len(p2) >= b: new_p1 = p1.copy() new_p2 = p2.copy() while len(new_p1) > a: new_p1.pop() while len(new_p2) > b: new_p2.pop() winner = game(new_p1, new_p2) else: # normal round winner = 1 if a > b else 2 # append cards to winner winning_player = p1 if winner == 1 else p2 winning_player.append(a if winner == 1 else b) winning_player.append(b if winner == 1 else a) return 1 if len(p1) else 2 game(p1, p2) print('After game:') print('p1:', p1) print('p2:', p2) winner = p1 if len(p1) else p2 i = 1 score = 0 while len(winner): score += winner.pop() * i i += 1 print('Score:') print(score)