Teacher's Guide

Chapter 3 / Level 1: List Comprehensions

Teaching Objective:

  • Students learn how to make lists from other lists
  • Understand how List Comprehensions can be useful
  • Learn techniques to optimize code

Guide

In this exercise we’re going to be working with List Comprehensions, which is the process of creating a list from another list in a similar fashion as Lambda functions where everything is done in a single readable line.

This level entails taking potatoes , onions and garlic from sacks, removing any "Bad" , "Spoiled" or "Rotten" items from the sack and placing them in lists so they can be put in storage.

First walk to the three (3) light X marks, face the sacks, and use the speak() function to identify the contents of the sacks. There are three (3) list constants that correspond to the sacks and are named by their location: left_sack , middle_sack , right_sack .

player.speak(left_sack)

.........

player.speak(middle_sack)

.........

player.speak(right_sack)

Once the contents of a sack have been identified find out of the list contains "Bad" , "Spoiled" or "Rotten" items. Use List Comprehensions to create a new list with the name of the unusable items so they can be removed. The names for the newly created lists shall be: potatoes , onions and garlic .

potatoes = [x for x in left_sack if not "Spoiled" in x]

onions = [x for x in middle_sack if not "Bad" in x]

garlic = [x for x in right_sack if not "Rotten" in x]

Walk to the dark X marks and place() the newly created lists in their respective crates, according to the signs posted.

player.place(garlic)

...........

player.place(potatoes)

...........

player.place(onions)

Map overview and path

Map overview and path

Code Solution

import player

player.turn_left()
player.move_forward(4)
player.turn_right()
player.move_forward()
player.speak(left_sack)
player.turn_left()
player.move_forward(2)
player.turn_right()
player.speak(middle_sack)
player.turn_left()
player.move_forward(2)
player.turn_right()
player.speak(right_sack)
potatoes = [x for x in left_sack if not "Spoiled" in x]
onions = [x for x in middle_sack if not "Bad" in x]
garlic = [x for x in right_sack if not "Rotten" in x]
player.turn_left()
player.turn_left()
player.move_forward(2)
player.turn_left()
player.move_forward()
player.turn_right()
player.place(garlic)
player.turn_left()
player.move_forward(2)
player.turn_right()
player.place(potatoes)
player.turn_left()
player.move_forward(2)
player.turn_right()
player.place(onions)
Chapter 3 / Level 1: List Comprehensions | Teacher's Guide