#!/usr/bin/env python3 from functools import reduce from pprint import pprint with open('input.txt', 'r') as f: instructions = [x.strip() for x in f.readlines()] instructions = [(x.split(' ')[1], x.split(' ')[7]) for x in instructions] steps = {y for x in instructions for y in x} # flatten finished = list() requirements = { step: [] for step in steps } for el in instructions: requirements[el[1]].append(el[0]) print(requirements) print(steps) while len(steps) != 0: possible = [ step for step in requirements if len(requirements[step]) == 0] possible.sort() step = possible[0] steps.remove(step) requirements.pop(step) for el in requirements: if step in requirements[el]: requirements[el].remove(step) finished.append(step) print(''.join(finished))