def read_file(): with open("input.txt","r") as f: return [int(x) for x in f.read().split(',')] def numbers_spoken(seed, limit): """Stores all numbers spoken.""" numbers = seed i = len(seed) number = seed[-1] while len(numbers) != limit: past = numbers[:-1] if number not in past: numbers.append(0) number = 0 else: last_spoken = len(past) + 1 most_recently_spoken = (len(past) - past[::-1].index(number)) turns_ago = last_spoken - most_recently_spoken numbers.append(turns_ago) number = turns_ago return numbers[-1] def part1(seed): return numbers_spoken(seed,2020) def number_spoken_on_turn(seed, turn): """Only cares about specific turn.""" last_spoken = {last: i+1 for i, last in enumerate(seed)} number = seed[-1] for i in range(len(seed),turn): if number not in last_spoken: last_spoken[number] = i number = 0 else: last = last_spoken[number] last_spoken[number] = i number = last_spoken[number] - last return(number) def part2(seed): return number_spoken_on_turn(seed,30000000) def main(): seed = read_file() print(part1(seed), part2(seed)) if __name__ == "__main__": main()