Day 7: Strings! and midterm 1 exam practice

back · home · slides · CMSC 201 (Fall 2024) @ UMBC · strings, splits, joins, oh my!

CMSC 201: Strings! And some exam practice

Agenda:

  • HW3
  • "Fun": wargames
  • Who cares? (AKA: what will we make)
  • String manipulations :)
  • Practice exam questions!
  • Goal: Get very good at manipulating strings, maybe have fun :)

    My email is: sdonahue@umbc.edu (Shane Donahue), office hours Tu/Th ITE 373 2-3PM

    HW3

    HW3 questions? Still due Friday 2024-09-27 at 11:59:59 PM :)

    Midterm

    Midterm #1 is October 9th for M/W October 10th for Tu/Th! There is no make-up time! Please don't miss it :(! I have no power to give you make-up times. TAs will be in the room, administering the test.

    Reminder: If you have SDS accomodations (e.g., extra time or reduced distractions), please book that room and let them know you plan to take the test there! The room here will be very quiet though, so there won't be many auditory distractions.

    "Fun": wargames

    "Wargames" are online, long-running computer "competitions" (but really just some fun activities). They usually center around some specific technology (like Linux, or websites).

    Overthewire's bandit wargame has been running forever, and is focused on using Linux :)! Each level is based on learning some skill. Let's briefly check it out: Bandit OverTheWire wargame.

    Who cares (about string manipulations)?

    Let's do censorship! :) Taking a string input, remove all undesirable words and replace them with our own! We are employed by the banana empire, on a mission to destroy all apple-related messages and spread the good word of the banana. https://techpost.io/uploads/big-brother.jpg Picture of big brother poster inspired by the novel 1984

    Strings

    Strings in python are immutable! This means they are "passed by value". Or at least, they look like they're passed by value. You can not change them like lists (lists are mutable)!

    Strings! Methods that operate on strings:

  • strip: remove leading and trailing value, by default, whitespace
  • split: split string into list
  • join: reverse of split: put list into string
  • lower: make a string to lowercase
  • upper: make a string uppercase
  • There's also functions that can take strings as an input:

  • len: get string length
  • list: cast string to a list (each letter is a list element)
  • These all RETURN a modified string, they do not modify the string in place. Strings are immutable in Python.

    Challenge: Ask for a comma-delimited list of the places that make up the DMV. Keep asking until they get them all. When they do, print them all back.
    places_list = ["dc","virginia","maryland"]
    correct_list = []
    
    while len(places_list) > 0:
        user_input = input("Give place name: ").lower()
        user_list = user_input.split(",")
        for entry in user_list:
            if entry in places_list:
                print("Correct!", entry)
                places_list.remove(entry)
                correct_list.append(entry)
    
    print("Cool!", correct_list)

    You can iterate through characters of a string, just like elements of a list.

    place_name = "Maryland"
    for letter in place_name:
        print(letter)

    You can also do slices and indexing and all that good stuff.

    place_name = "Maryland"
    print(place_name[:4]) # "Mary"
    print(place_name[3]) # y
    print(place_name[2:5]) # "ryl"
    print(place_name[100]) # IndexError: string index out of range
    print(place_name[2:10000000000000]) # Why python?! Slices have no bounds limit, but indexing does
    

    But it's not a list! Strings are immutable in Python! (They are very mutable in C, C++, Go...)

    place_name = "Maryland"
    place_name[0] = "B" # Fails!
    # Outputs: TypeError: 'str' object does not support item assignment
    Challenge: Alternate capital and lower letters of a given string ("computer science --> cOmPuTeR ScIeNcE").
    user_sentence = input("Give me string: ")
    result_sentence = []
    
    # split into list
    index = 0
    for character in user_sentence:
        if index % 2 == 0:
            result_sentence.append(character.lower())
        else:
            result_sentence.append(character.upper())
        index += 1
    
    result_string = "".join(result_sentence)
    print(result_string)

    Let's do some string manipulations!

    Censorship... it's an awful thing, but money is money! And the banana empire is flush with cash.

    Challenge: Implement censorship from the banana regime-- take space delimited sentence, if any word is apple, replace it with banana. If it's banana, replace it with "government-sponsored BANANA(TM)".
    input_sentence = input("Give sentence: ")
    input_split = input_sentence.split()
    
    for word_index in range(len(input_split)):
        if "apple" in input_split[word_index].lower():
            input_split[word_index] = "banana"
        elif "banana" in input_split[word_index].lower():
            input_split[word_index] = "government-sponsored BANANA(TM)"
    
    print(" ".join(input_split))
    # fill this in with samples you, wrote and then finish functions discussion, then do study guide exam? or do it piece by piece

    OK let's do practice exam questions

    Spaced repetition is great, I plan to do some exam review for the next four sessions :)

    Two sections of the midterm: Multiple choice (~40%) and free response (~60%). Our main topics thus far are:

  • Booleans and variables
  • Lists and list manipulations
  • For and while loops
  • Types of free response questions include:

  • Writing code (lists, expressions, loops), mini-homework challenges
  • Debugging existing code
  • Fill in the blanks/describe what this does

  • Let's do exam prep!

    Fall 2023 Midterm 1

    Some extra multiple choice questions, just for fun...

    When declaring a variable, what names are legal (in python, don’t have to follow coding standards)?

  • A: this_is_a_variable
  • B: isVariableLegal
  • C: Money$
  • D: 2_many_variables
  • Answer: A, B


    What variable name follows the coding standard for this class, and PEP8?

  • A: thisVariableIsNice
  • B: is_this_ok
  • C: VariablesShouldBeFree
  • D: __strange_underscores
  • Answer: B


    Consider the following code:

    i = 0
    L = [1, 2, 1, 5]
    sum = 0
    for i in L:
       sum += i + 3
    print(sum)

    What will it print out?

  • A: 8
  • B: 21
  • C: 4
  • D: 17
  • Answer: B

    Consider the following code:

    Answer: C


    If you are given an integer (x), how can you write an if statement to test if it is even?

  • A: if 2 % x == 0:
  • B: if x is ‘even’:
  • C: if x % 2 != 0:
  • D: if x % 2 == 0:
  • Answer: D


    Let x = True, y = False and z = True, evaluate the statement:

    not (x or y) and z
  • A: True
  • B: False
  • C: ValueError
  • Answer: B


    Finally peace of mind 😌 Practice questions bring clarity to life...

    Future practice will focus on other sections (free response: programming, short answer, and debugging).

    I anticipate the programming free response to be the hardest. I'll have practice problems in future classes, but if you want to practice now, you can speedrun re-solve your homework, or check out the problems on codingbat (https://codingbat.com/python).