Lecture 15 - Exercises

15A - List Basics

  1. Suppose that I’ve created a list as follows: starks = ["Ned", "Arya", "Bran", "Sansa"]

    For each of the following expressions, write what it evaluates to.

    1. "Ned" in starks
    2. "Sansa" in starks[1:3]
    3. len(starks[1:4]) == 3
    4. "Arya" in (starks + ["Jon"])[2:]
    5. len(starks[1:2]) * 4 == 8
    6. starks[4:] + starks[1:2]
    7. starks[3] + starks[1]

15B - List Methods and Mutability

  1. Write the contents of a (as it would be printed by Python) after each line of the following program.

  2. Execute the numbered lines below in order; if one causes an error, assume it is skipped before continuing on. List all the line numbers that do not cause errors.

  3. What does the following print? Be sure to check your answer on this one using Thonny.

Problems

  1. Implement and test the following function:

  2. Write a program that repeatedly prompts a user for words until they enter “exit” (with any capitalization). For each word entered, print a message saying whether or not it’s a duplicate of a word already entered. When determining duplicates, ignore case: “Banana” should be considered a duplicate if “banana” was entered previously.

  3. Implement and test the following function:

  4. Write a program to play a text-only version of the memory game Simon. For each round of the game, print a sequence of random colors chosen from “Red”, “Green”, “Blue”, and “Yellow”, and wait for the user to press enter. Then, print enough newline characters to clear the screen, and prompt the user to re-enter the sequence of colors from memory. Start the first round with a sequence length of one, increasing it by one in each subsequent round. If the player fails to enter the sequence correctly, they lose and the program terminates.

  5. Write a program that repeatedly prompts a user for positive numbers, stopping when they enter a negative number. Afterwards, print the numbers they entered in sorted (ascending) order. To keep things interesting, don’t use the sort or sorted functions.