Day 21 of 100 - Itertools Day 3 of 3

itertools Day 3 of 3

Day 21 of 100

What a great 3 day challenge! itertools is yet another module that I had never used and never heard of, but I can see many uses for. The first challenge was to make a stop light application that simulates the automatic changing of a stop light. For an extra challenge, I also added a random timer for the stop and go to simulate different light lengths in response to traffic.

First, I created an itertools.cycle() object for the light color rotation. This will create an object that I can endlessly iterate over, instead of a stopiterate error that usually comes when the end of an iterable is reached. Then created a variable to hold the cycle object value and a list of various amounts of seconds for a random timer between 5 and 10 seconds for the stop and go light length.

For the function, I print out the current light cycle and then set the display time length based on the return of the random choice of one of the values in the list of possible times. The program is designed to display in a terminal window, which is why sys.stdout.write() is used, rather than print():

import sys
import itertools
import time
import random

light_cycle = itertools.cycle(['Green', 'Yellow', 'Red'])
next_light = next(light_cycle)
light_length = list(range(5, 10))


while True:
    sys.stdout.write('\r' + next_light)
    next_light = next(light_cycle)
    sys.stdout.flush()
    if next_light == 'Yellow' or next_light == 'Green':
        time.sleep(random.choice(light_length))
    else:
        time.sleep(2)

The other challenges were three PyBites challenges and I was able to complete 2 of them in the time given. Both were great bites that I was able to use itertools to solve a coding challenge with one or two lines where I would have previously thought to write numerous for loops, while loops, and conditionals.

The first PyBite challenge was to return all possible combinations of teams given a list of possible team members, the size of the team, and if the order of the team members mattered. This was a great opportunity to use both the combinations and permutations methods that I just learned. So slick!

from itertools import permutations, combinations


def friends_teams(friend_list, team_size, order_does_matter):
    if order_does_matter:
        return list(permutations(friend_list, team_size))
    else:
        return list(combinations(friend_list, team_size))

The second bite I completed was to fix an "error" in how a list was reported using the zip function. I was not familiar with the zip function but learned it is a handy tool in the itertools library to combine lists. The problem was in the sample data, the lists were of unequal length, meaning that zip would stop when it reached the end of the shortest list, truncating data. It took some research and investigation, but I uncovered a zip_longest method that would continue to iterate until it reached the end of the longest list, and let me choose the placeholder character for empty values:

import itertools

names = 'Tim Bob Julian Carmen Sofia Mike Kim Andre'.split()
locations = 'DE ES AUS NL BR US'.split()
confirmed = [False, True, True, False, True]


def get_attendees():
    for participant in itertools.zip_longest(names, locations, confirmed, fillvalue='-'):
        print(participant)


if __name__ == '__main__':
    get_attendees()

Another great 3 day section of python code. I have already increased my skills immeasurably!