Strings as Sequences

Reminders

  1. HW1: Rivalry Project is due tonight at 11:59pm
  2. HW1: Presentation signups are due tonight at 11:59pm
    1. If you can't find an open slot that works for you, email me and Talie with some documentation of your full set of conflicts
    2. We're going to do a full presentation demo for you in class later so we'll take more questions about that then
  3. Office Hours continue—mine, Talie's, TAs'

Some Refreshers on Strings

Some Refreshers on ________

Uh oh! I left out some cheese last night and then a bunch of mice came and ate my slides! You're going to need to help me finish this review section.

Why is a String a Sequence?

Create a string by writing out a literal as a bunch of characters placed between a pair of the quotation marks of your choice:

vocabulary_word = "vermiculate"

Sequences are collections of .

Why is a String a Sequence?

A string is defined not just by the characters it contains!

a = "relatives"
b = "versatile"
print(a == b)

🖨️ ➡️

This is because sequences, and therefore strings, are collections of data.

Sequences in Python are , meaning that we can refer to their contents based on their positions.

"carrot"
 012345

This is a string with six characters, which we could verify in Python by printing out

Rules about indexing

  • the value in a sequence lives at index 0
"carrot"
 012345

Notice that "carrot" is a string with six characters: since we start counting at 0, the index of the last character is .

Indexing in Sequences

For a sequence of length n, the valid indices always range from 0 to n-1.

  • indices n lead to IndexError
"short"     # 5 characters long
 01234      # biggest index: 4

"lengthy"   # 7 characters long
 0123456    # biggest index: 6

Slicing: Generating Subsequences

We know how to refer to one position in a sequence at a time with a single index.

  • How about a group of positions—a subsequence?
  • If we want to obtain a subsequence of a string s including all characters starting at index i and stopping before index j, then we can do that by writing

This operation is called slicing.

print("trepidation"[2:5])

This one prints

print("audacity"[4:])

This one prints "city" because omitting the second number means that you go until

print("12" + "3")

🖨️ ➡️ 123

This happens because "addition" between two strings is really called , meaning that we put the contents of the second string after all the contents of the first string.

If we had really wanted 15...

s_one = "12"
s_two = "3"

print(int(s_one) + int(s_two))

This converts the values of "12" and "3" into respectively, before adding them together the "normal" way.

OK, the mice are gone. 👍
  • strings are indexable, meaning that you can ask for a character at a specific position
  • strings are sliceable, meaning that you can ask for a group of characters from a range of indices
  • valid indices range from 0 to len(s) for a string s
    • -1 gives you the last character, too, which is helpful to know
  • strings can be concatenated together with the + sign

What questions remain about strings?

A Game with Strings

Example: Guessing Game

Requirements:

  • Screen should start blank before any keys are pressed
  • Let the game run as long as the player has not pressed the secret key
  • Each frame, check if the player has made a guess
    • if the guess is wrong, show the player's guess and tell them they're wrong.
    • if the guess is right, stop the game and display a victory screen.
import penndraw as pd
letter = "s"
still_guessing = True
while still_guessing:
  if pd.has_next_key_typed():
    guess = pd.next_key_typed()
    if guess == letter:
      still_guessing = False
    else:
      pd.clear()
      pd.text(0.5, 0.5, f"Not {guess}, try again!")
  pd.advance()

pd.clear(pd.GREEN)
pd.text(0.5, 0.5, f"Hurray! {letter} is right.")
pd.run()

Practice Reasoning and Talking about Code

I'll put the code back up in a second. We'll start by reading it silently for two minutes.

C1 Working independently, describe what happens in the code that makes it so the program stops when the correct letter is typed. Your answer should include:

  • which conditional branch is triggered on the winning press,
  • which variable is changed as a result, and
  • what happens mechanically to make the program go to the victory screen.

Work on this on your own—asking for our help as needed—and then practice explaining this to a partner after you've tried to write down your own answer.

A Better Game

Modify guessing.py so that all previous guesses are saved. That way, we can count the number of guesses and show the history.

Big ideas:

  • Create a variable called history that will start as an empty string.
  • Whenever there's a wrong guess, concatenate it to the end of history
  • At the end, show the value of history and its length to show all the wrong guesses and the number required.

Toolkit: len() and +

L1: complete the TODOs so that history is tracked and then displayed at the end!

letter = "s"
still_guessing = True
history = ""          # ❗❗❗
while still_guessing:
  if pd.has_next_key_typed():
    guess = pd.next_key_typed()
    if guess == letter:
      still_guessing = False
    else:
      pd.clear()
      # TODO: Save the guess!
      pd.text(0.5, 0.5, f"Not {guess}, try again!")
  pd.advance()
pd.clear(pd.GREEN)
# TODO: Change next line to show all guesses taken and the total #
pd.text(0.5, 0.5, f"Hurray! {letter} is right.") 
pd.run()

Finally: A Demo Presentation

Presntation Structure

  • Brief Introduction (1 min)
  • Code Walkthrough (9 min)
  • PrairieLearn

Introduction

Say hello to each other!

Code Walkthrough

The purpose of this part is twofold:

  • to give you some immediate and actionable feedback on your assignment
  • to measure your understanding of the code that you submit

Immediate and Actionable Feedback

On this assignment, we'll talk about style

  • if you have any automatic style deductions, we'll show you what those mean and how to fix them in the future.
  • we'll talk about other measures of code style and quality
  • we will be telling you where you did a good job

Measuring Understanding

We'll select two questions from a pool at random. You think for a minute and then pick the one you want to answer!

  • when you're close, we'll prompt you to say more to finish an answer
  • you can see youno other resources or help is available during this time

Questions are meant to be not super challenging. Here's an example of one we shared on the assignment:

Imagine that I wanted to extend the Rivalry program to include a third contestant. What would I need to add and modify in that case?

Demo: Measuring Understanding

How would you modify the Guessing Game program so that you have a limited number of guesses?

PrairieLearn Problem

We'll pick one at random, print it, and have you solve it on the board.

  • You do have to briefly explain your reasoning, which you can either do while you solve it or once you're finished.
  • No resources or help on this part.
  • Always a variant of a question you've already seen.
  • Points are awarded both for correctness of solution and explanation.

Trying it out

We're going to demo the parts that are "yours":

Imagine that I wanted to extend the Rivalry program to include a third contestant. What would I need to add and modify in that case?

and

alt text