A document from MCS 260 Fall 2021, instructor Emily Dumas. You can also get the notebook file.

MCS 260 Fall 2021 Worksheet 3 Solutions

  • Course instructor: Emily Dumas

Topics

The main topics on this worksheets are lists, while loops and for loops.

Instructions

  • Work on the exercises below during lab. Complete them afterward if you don't finish during the lab period.
  • This worksheet will prepare you for the upcoming homework assignment.
  • Most of the exercises ask you to write Python scripts to accomplish a certain task. We recommend making a folder (with a name like "worksheet3") to store the scripts you prepare today.
  • Seek assistance from your TA or from fellow students if you run into trouble.

Collaboration

Collaboration on worksheets is strongly encouraged.

Resources

The main course materials to refer to for this worksheet are:

(Lecture videos are not linked on worksheets, but are also useful to review while working on worksheets. Video links can be found in the course course Blackboard site.)

Reminder about the solutions

There are always many ways to solve a problem. Your solution doesn't need to match the one shown here to be correct. What's important is whether your program does what the question asked.

1. Arithmetic progression reporter

An arithmetic progression is a sequence of numbers in which the difference between any pair of neighboring terms is the same, e.g. $$ 1, 5, 9, 13, 167, 21, ... $$ where the difference is 4, or $$ -58, -42, -26, -10, 6, 22, ... $$ where the difference is 16.

An arithmetic progression is determined by its first element $a_0$ and the difference $\delta$ between neighboring terms. The term at index $i$ then has the formula $a_i = a_0 + \delta * i$.

Write a program that allows the user to specify an arithmetic progression and a desired number of terms, and which then prints the terms, one per line, as shown below:

First term: -100
Difference of neighboring terms: 7
Number of terms: 13

The first 13 terms of that arithmetic progression are:
-100
-93
-86
-79
-72
-65
-58
-51
-44
-37
-30
-23
-16

In this example, -100, 7, and 13 on the first three lines are numbers entered by the user. Note that means your program will have three input() statements to read these data.

Hints:

  • Use a for loop
  • No lists are needed or recommended for this program (but there are correct solutions that would use a list)
  • Do you recall how to iterate over the numbers from 0 to n-1 in a for loop?

Solution

Possible contents of a program arith.py that solves problem 1 are shown below. Below the code is a sample session obtained by running the program.

In [2]:
# MCS 260 Fall 2021
# Worksheet 3 problem 1
# Emily Dumas

# Input handling
first_term = int(input("First term: "))
delta = int(input("Difference of neighboring terms: "))
n = int(input("Number of terms: "))

# Print the arithmetic progression
print() # gives a blank line
print("The first",n,"terms of that arithmetic progression are:")
for i in range(n):
    print(first_term + delta*i)
First term: -23
Difference of neighboring terms: 5
Number of terms: 8

The first 8 terms of that arithmetic progression are:
-23
-18
-13
-8
-3
2
7
12

2. Word list report

Write a script that lets the user enter any number of words, one per line. The script should store all of the words the user enters in a list. When the user is finished, they simply press Enter instead of entering a word, and the script takes this as a signal to stop waiting for additional input. It then prints a report giving:

  • The number of words entered
  • The first and last words entered
  • The middle word in the list (using the earlier of the two middle entries if the length of the list is even)

Here's a sample session which shows what the prompt and output should look like:

Enter any number of words, one per line, or a blank line to stop:
we
are
closely
monitoring
the
situation
and
will
announce
something
shortly

Number of words: 11
First word: we
Last word: shortly
Middle word: situation
Total number of letters: 65

Hints:

  • Try to get everything except the total number of letters working first.
  • At the beginning of the program, you'll want to create a list that is initially empty, and which will store the words as they arrive.
  • You can use a while loop to repeatedly read words until a blank one is found (with input(...) in the body of the loop).
  • But watch out: Variables used in the while statement need to exist before the loop begins, and you won't have read the first word when the loop starts.
  • In lecture 5 we learned how to add an element to the end of a list.

Solution

Possible contents of a program wordlist.py that solves problem 2 are shown below. Below the code is a sample session obtained by running the program.

In [3]:
# MCS 260 Fall 2021
# Worksheet 3 problem 2
# Emily Dumas

# Show a prompt once, even though we might read more than one word
print("Enter any number of words, one per line, or a blank line to stop:")

L = []    # will store the words
total = 0 # running total of characters read so far

# Main loop that reads words
while True:   # we'll use `break` to exit the loop
    w = input()
    if w == "":
        # empty input means stop
        break
    # If we make it here, we have an actual word.
    # Update list and character count.
    L.append(w)
    total = total + len(w)

print("Number of words:",len(L))
print("First word:",L[0])
print("Last word:",L[-1])
print("Middle word:",L[len(L)//2])
print("Total number of letters:",total)
Enter any number of words, one per line, or a blank line to stop:
the
quick
brown
fox
jumped
over
the
lazy
dog

Number of words: 9
First word: the
Last word: dog
Middle word: jumped
Total number of letters: 36

3. Puzzle box

You are presented with a wooden box. Across the top, it has a row of five light bulbs. (To be able to refer to the lights individually, let's call them 0, 1, 2, 3, and 4.) Lights 1 and 2 are turned on when you first receive the box. Below the lights is a label that reads "Puzzle Box - Can you turn on all of the lights?" There are also two large circular buttons, labeled "a" and "b".

You discover that pressing button "a" makes the state of the lights shift one position to the right, with the rightmost light's state wrapping around to the left side. In other words, after pressing button "a", light $n$ will be in whatever state light $n-1$ was in before you pressed it.

You also discover that pressing button "b" makes lights 0, 2, and 4 switch state (from on to off or off to on, whichever is appropriate for the light).

Before trying out the physical puzzle, you decide it would be best to experiment on your computer.

Write a Python script that simulates the puzzle box, displaying the state of the lights using 0 and 1 to represent off and on, respectively. The script should keep showing the state of the lights and waiting for a button press until the user wins (i.e. until the state is 11111.) Here's what the interface should look like (and a sample of how you might win):

01100
Which button? a
00110
Which button? b
10011
Which button? b
00110
Which button? a
00011
Which button? b
10110
Which button? b
00011
Which button? a
10001
Which button? b
00100
Which button? a
00010
Which button? a
00001
Which button? b
10100
Which button? a
01010
Which button? b
11111 you win!

Hints:

  • Use a list of integers to represent the state of the lights. Assign it a value at the beginning to represent the two lights that are on at the start of the game.
  • You want to end the game when the lights are all on; what type of loop makes this easiest?
  • You'll need to read a button from the user using input(...) and then decide which of two things you need to do to modify the light state list. What Python construct is best for that?
  • If you want to print a digit and not skip to the next line, you can use print(x,end=""). For example, compare the two programs shown below.
In [23]:
for x in range(3):
    print(x)
0
1
2
In [24]:
for x in range(3):
    print(x,end="")
012

Solution

Possible contents of a program wordlist.py that solves problem 3 are shown below. Below the code is a sample session obtained by running the program.

In [4]:
# MCS 260 Fall 2021
# Worksheet 3 problem 3
# Emily Dumas

L = [0,1,1,0,0] # L stores current state of lights
while L != [1,1,1,1,1]: # loop until in win state
    # print the current light state
    for x in L:
        print(x,end="")
    print()
    # wait for input
    cmd = input("Which button? ")
    if cmd == "a":
        # Rotate lights one position right
        # In words, next code line says "make a list containing only the last
        # element of L, and another list containing all but the last element 
        # of L. Join them in that order and make it the new value of L.
        # Analogous to saying you can rotate ABCDE to the right by taking
        # E and joining it to ABCD.
        L = [L[-1]] + L[:-1]  # first term is in brackets to make a one-element list
    elif cmd == "b":
        # Flip lights 0, 2, and 4.
        # If x is 0 or 1, then 1-x is 1 or 0, respectively.
        # We use that formula to flip light values.
        L = [1-L[0],L[1],1-L[2],L[3],1-L[4]]

# If we get here, it means L is [1,1,1,1,1].  But we haven't yet printed
# that state because printing happens *before* the button press is handled
# in the while loop.  So we're now ready to print both the state and the
# win message.
print("11111 you win!")
01100
Which button? a
00110
Which button? b
10011
Which button? b
00110
Which button? a
00011
Which button? b
10110
Which button? b
00011
Which button? a
10001
Which button? b
00100
Which button? a
00010
Which button? a
00001
Which button? b
10100
Which button? a
01010
Which button? b
11111 you win!

Revision history

  • 2021-09-09 Initial release