15.py 708 B

12345678910111213141516171819202122232425262728293031
  1. lines = []
  2. with open("15.input") as f:
  3. for line in f.readlines():
  4. lines.append(line.strip())
  5. numbers = [int(num) for num in lines[0].split(",")]
  6. def find_nth(numbers, end):
  7. numbers = list(numbers)
  8. last_spoken = {}
  9. for (i, num) in enumerate(numbers[:-1]):
  10. last_spoken[num] = i
  11. last = numbers[-1]
  12. numbers = numbers[0:-1]
  13. for i in range(len(numbers), end):
  14. if last in last_spoken:
  15. next = i - last_spoken[last]
  16. else:
  17. next = 0
  18. numbers.append(last)
  19. last_spoken[last] = i
  20. last = next
  21. return numbers[-1]
  22. print("Answer 1:", find_nth(numbers, 2020))
  23. print("Answer 2:", find_nth(numbers, 30000000))