def read_file(): with open("input_sample.txt") as f: p1, p2 = f.read().split('\n\n') p1 = p1.split('\n')[1:] p2 = p2.split('\n')[1:] p1 = list(map(int, p1)) p2 = list(map(int, p2)) return p1, p2 def combat(p1,p2): while True: c1 = p1.pop(0) c2 = p2.pop(0) if c1 > c2: p1 += [c1, c2] else: p2 += [c2, c1] if len(p1) == 0: return p2 if len(p2) == 0: return p1 def part1(): p1, p2 = read_file() winner_deck = combat(p1, p2) score = 0 for i, card in enumerate(reversed(winner_deck)): score += (i+1)*card return score def recursive_combat(p1, p2): seen = set() while True: # does p1 auto-win? state = (tuple(p1), tuple(p2)) if state in seen: return 1, p1 seen.add(state) # does anyone win by normal rules? if len(p1) == 0: return 2, p2 break if len(p2) == 0: return 1, p1 # draw cards c1 = p1.pop(0) c2 = p2.pop(0) # should we recurse? if len(p1) >= c1 and len(p2) >= c2: # play recursive round winner, deck = recursive_combat(p1[:c1],p2[:c2]) # copy that many cards if winner == 1: p1 += [c1, c2] else: # winner == 2 p2 += [c2, c1] else: # play normal round if c1 > c2: p1 += [c1, c2] else: # c2 > c1 p2 += [c2, c1] def part2(): p1, p2 = read_file() winner, winner_deck = recursive_combat(p1, p2) score = 0 for i, card in enumerate(reversed(winner_deck)): score += (i+1)*card return score def main(): print(part1(),part2()) if __name__ == "__main__": main()