refactor to use generators and itertools instead of loops