Skip to content
Snippets Groups Projects
Commit 3559f1e3 authored by Anna Meyer's avatar Anna Meyer
Browse files

lec 10 changes

parent 3b2fe508
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Lists # Lists
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import project import project
``` ```
%% Cell type:code id: tags:
``` python
# Warmup: string review
# Predict the output of the following statments
name = "Andrew"
print(name[3])
print(name[-1])
print(name[:2])
print(name[:-1])
# Try this: change only the last letter of the name to "a" so that name = "Andrea"
# Takeaway:
# you cannot _______________
# because strings are ___________-
# But what about....
name = "Fred" # this is called reassignment and is allowed
print(name)
```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Learning Objectives ## Learning Objectives
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- Create a list and use sequence operations on a list. - Create a list and use sequence operations on a list.
- Write loops that process lists - Write loops that process lists
- Explain key differences between strings and lists: type flexibility, mutability - Explain key differences between strings and lists: type flexibility, mutability
- Mutate a list using: - Mutate a list using:
- indexing - indexing
- methods such as append, extend, sort, and pop - methods such as append, extend, sort, and pop
- split() a string into a list - split() a string into a list
- join() list elements into a string - join() list elements into a string
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Motivation for lists: ### Motivation for lists:
- what if we want to store a sequence of numbers or a sequence of numbers and strings? - what if we want to store a sequence of numbers or a sequence of numbers and strings?
- lists enable us to create flexible sequences: we can store anything inside a list as item, including: - lists enable us to create flexible sequences: we can store anything inside a list as item, including:
- int - int
- float - float
- str - str
- bool - bool
- other lists, etc., - other lists, etc.,
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
day = "Monday" day = "Monday"
# first quotation indicates beginning of string sequence # first quotation indicates beginning of string sequence
# second quotation indicates end of string sequence # second quotation indicates end of string sequence
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
empty_list = None empty_list = None
some_nums = None some_nums = None
# [ indicates beginning of sequence # [ indicates beginning of sequence
# ] indicates end of sequence # ] indicates end of sequence
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"] grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"]
# TODO: compute length of grocery_list # TODO: compute length of grocery_list
print() print()
# TODO: use indexing to display broccoli # TODO: use indexing to display broccoli
print() print()
# TODO: use indexing to display last item # TODO: use indexing to display last item
print() print()
# TODO: use slicing to extract only the vegetables # TODO: use slicing to extract only the vegetables
print() print()
```
%% Cell type:code id: tags:
``` python
# TODO: discuss why the following gives IndexError # TODO: discuss why the following gives IndexError
print(grocery_list[len(grocery_list)]) print(grocery_list[len(grocery_list)])
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Iterate over every item in grocery_list to display: # Iterate over every item in grocery_list to display:
# <Item> purchased! # <Item> purchased!
for item in ???: for item in ???:
print() print()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Compute sum of numbers in some_nums # Compute sum of numbers in some_nums
# Let's do this example using PythonTutor # Let's do this example using PythonTutor
total = 0 total = 0
# TODO: for loop to iterate over each number in some_nums # TODO: for loop to iterate over each number in some_nums
print(total) print(total)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# We can use a list instead of a variable for each operation # We can use a list instead of a variable for each operation
[10, 20, 30][1] [10, 20, 30][1]
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# We can use a list instead of a variable for each operation # We can use a list instead of a variable for each operation
[10, 20, 30][1:] [10, 20, 30][1:]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
How does Python differentiate between two different usages of `[]`? How does Python differentiate between two different usages of `[]`?
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Other sequence operations ### Other sequence operations
- concatentation using `+` - concatentation using `+`
- `in` - `in`
- multiply by an `int` - multiply by an `int`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
msg = "Happy " msg = "Happy "
print(msg + "Monday :)") print(msg + "Monday :)")
some_nums = [11, 22, 33, 44] some_nums = [11, 22, 33, 44]
print(some_nums + [1, 2, 3]) # `+` concatenates two lists print(some_nums + [1, 2, 3]) # `+` concatenates two lists
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
msg = "Happy" msg = "Happy"
print("H" in msg) print("H" in msg)
print("h" in msg) print("h" in msg)
some_nums = [11, 22, 33, 44] some_nums = [11, 22, 33, 44]
print(33 in some_nums) print(33 in some_nums)
print(55 in some_nums) print(55 in some_nums)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
msg = "Happy :)" msg = "Happy :)"
print(msg * 3) print(msg * 3)
print(["Go", "Badgers!"] * 3) print(["Go", "Badgers!"] * 3)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Strings versus lists ## Strings versus lists
<div> <div>
<img src="attachment:Mutation.png" width="600"/> <img src="attachment:Mutation.png" width="600"/>
</div> </div>
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Difference 1: lists are flexible ### Difference 1: lists are flexible
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# String sequence can only contain characters as items # String sequence can only contain characters as items
# List sequence can contain anything as an item # List sequence can contain anything as an item
l = ["hello", 14, True, 5.678, None, ["list", "inside", "a", "list"]] l = ["hello", 14, True, 5.678, None, ["list", "inside", "a", "list"]]
# TODO: fix the bug in this loop # TODO: fix the bug in this loop
for i in l: for i in l:
print(l[i]) print(l[i])
# TODO: use indexing to extract and print the inner list # TODO: use indexing to extract and print the inner list
print() print()
# TODO: print type of last item in l # TODO: print type of last item in l
print() print()
# TODO: use double indexing to extract "inside" # TODO: use double indexing to extract "inside"
print() print()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# List of lists usecase example # List of lists usecase example
game_grid = [ game_grid = [
[".", ".", ".", ".", ".", "S"], [".", ".", ".", ".", ".", "S"],
[".", "S", "S", "S", ".", "S"], [".", "S", "S", "S", ".", "S"],
[".", ".", ".", ".", ".", "S"], [".", ".", ".", ".", ".", "S"],
[".", ".", ".", ".", ".", "."], [".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", "S", "."], [".", ".", ".", ".", "S", "."],
[".", ".", ".", ".", "S", "."] [".", ".", ".", ".", "S", "."]
] ]
for row in game_grid: for row in game_grid:
for position in row: for position in row:
print(position, end = "") print(position, end = "")
print() print()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Difference 2: lists are mutable ### Difference 2: lists are mutable
<div> <div>
<img src="attachment:Mutability.png" width="600"/> <img src="attachment:Mutability.png" width="600"/>
</div> </div>
- Mutability has nothing to do with variable assignments / re-assignments - Mutability has nothing to do with variable assignments / re-assignments
- Mutability has to do with changing values inside a sequence - Mutability has to do with changing values inside a sequence
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Variables can always be re-assigned # Variables can always be re-assigned
s = "AB" s = "AB"
s = "CD" s = "CD"
s += "E" s += "E"
print(s) print(s)
nums = [1, 2] nums = [1, 2]
nums = [3, 4] nums = [3, 4]
print(nums) print(nums)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
name = "Andrew" name = "Andrew"
# TODO: let's try to change "Andrew" to "Andrea" # TODO: let's try to change "Andrew" to "Andrea"
# doesn't work because strings are immutable, that is you cannot change the value inside an existing string # doesn't work because strings are immutable, that is you cannot change the value inside an existing string
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
nums = [2, 2, 9] nums = [2, 2, 9]
# TODO: change 9 to 0 # TODO: change 9 to 0
print(nums) print(nums)
# works because lists are mutable, that is you can change the value inside an existing list # works because lists are mutable, that is you can change the value inside an existing list
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Mutating a list ### Mutating a list
- update using index (works only for existing index) - update using index (works only for existing index)
- `append` method - `append` method
- `extend` method - `extend` method
- `pop` method - `pop` method
- `sort` method - `sort` method
Unlike string methods, list methods mutate the original list. String methods produce a new string because strings are immutable. Unlike string methods, list methods mutate the original list. String methods produce a new string because strings are immutable.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"] grocery_list = ["apples", "milk", "broccoli", "spinach", "oranges"]
# TODO: try to add "blueberries" at index 5 # TODO: try to add "blueberries" at index 5
grocery_list[???] = "blueberries" grocery_list[???] = "blueberries"
# doesn't work because grocery_list does not contain a previous item at index 5 # doesn't work because grocery_list does not contain a previous item at index 5
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
So, how do we add a new item to a list? So, how do we add a new item to a list?
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list.append("blueberries") grocery_list.append("blueberries")
print(grocery_list) print(grocery_list)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Can we add multiple items using `append`? Can we add multiple items using `append`?
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Let's try to add "peanut butter", "jelly", "bread" # Let's try to add "peanut butter", "jelly", "bread"
grocery_list.append()# doesn't work because append only accepts a single argument grocery_list.append()# doesn't work because append only accepts a single argument
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list.append()# adds the list argument as such grocery_list.append()# adds the list argument as such
print(grocery_list) print(grocery_list)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`extend` method will enable us to add every item in argument list to the original list as individual item. `extend` method will enable us to add every item in argument list to the original list as individual item.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list.extend(["falafel", "pita bread", "hummus"]) grocery_list.extend(["falafel", "pita bread", "hummus"])
print(grocery_list) print(grocery_list)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`pop` enables us to remove item from the list: `pop` enables us to remove item from the list:
- by default pop() removes the last item from the list - by default pop() removes the last item from the list
- you can override that by passing an index as argument - you can override that by passing an index as argument
- pop remove the item from the original list and also returns it - pop remove the item from the original list and also returns it
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list.pop() grocery_list.pop()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grocery_list grocery_list
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# TODO: remove "oranges" from grocery_list and store it into a variable # TODO: remove "oranges" from grocery_list and store it into a variable
some_fruit = grocery_list.pop(???) some_fruit = grocery_list.pop(???)
print(some_fruit) print(some_fruit)
print(grocery_list) print(grocery_list)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`sort` method enables us to sort the list using alphanumeric ordering. `sort` method enables us to sort the list using alphanumeric ordering.
TODO: Try sorting each of the following lists. TODO: Try sorting each of the following lists.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
L = None # TODO: initialize list with some unordered numbers L = None # TODO: initialize list with some unordered numbers
L L
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
L = None # TODO: initialize list with some unordered strings L = None # TODO: initialize list with some unordered strings
L L
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
L = [False, True, False, True, True] L = [False, True, False, True, True]
L L
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
L = ["str", 1, 2.0, False] L = ["str", 1, 2.0, False]
L.sort() # Doesn't work as you cannot compare different types! L.sort() # Doesn't work as you cannot compare different types!
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`split` method splits a string into a list of strings, using a separator (argument) `split` method splits a string into a list of strings, using a separator (argument)
- Syntax: some_string.split(separator_string) - Syntax: some_string.split(separator_string)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
sentence = "a,quick,brown,fox" sentence = "a,quick,brown,fox"
words = sentence.split(",") words = sentence.split(",")
words words
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
`join` method joins a list of strings into a single string using a separator (argument) `join` method joins a list of strings into a single string using a separator (argument)
- Syntax: separator_string.join(some_list) - Syntax: separator_string.join(some_list)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
characters = ["M", "SS", "SS", "PP", ""] characters = ["M", "SS", "SS", "PP", ""]
place = "I".join(characters) place = "I".join(characters)
place place
# TODO: remove the last item in characters list and see what place you get (re-run cell) # TODO: remove the last item in characters list and see what place you get (re-run cell)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### List all Engineering majors (primary major) among current lecture (example: LEC001) students ### List all Engineering majors (primary major) among current lecture (example: LEC001) students
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for idx in range(project.count()): for idx in range(project.count()):
lecture = project.get_lecture(idx) lecture = project.get_lecture(idx)
major = project.get_primary_major(idx) major = project.get_primary_major(idx)
if lecture == "LEC001": if lecture == "LEC001":
print(lecture, major) print(lecture, major)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Profanity filtering ### Profanity filtering
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
bad_words = ["omg", "midterm", "exam"] bad_words = ["omg", "midterm", "exam"]
def censor(input_string): def censor(input_string):
""" """
replaces every bad word in input string with that word's first replaces every bad word in input string with that word's first
letter and then * for the remaining characters letter and then * for the remaining characters
""" """
# TODO: use split to extract every word # TODO: use split to extract every word
# TODO: Iterate over every word: 1. check if word is in bad_words 2. compute replacement 3. replace word # TODO: Iterate over every word: 1. check if word is in bad_words 2. compute replacement 3. replace word
# TODO: join the words back using the correct separator and return the joined string # TODO: join the words back using the correct separator and return the joined string
censor("omg the midterm was so awesome!") censor("omg the midterm was so awesome!")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Wordle (self-study example) ### Wordle (self-study example)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def get_wordle_results(guess): def get_wordle_results(guess):
wordle_result = "" wordle_result = ""
for i in range(len(guess)): for i in range(len(guess)):
if guess[i] == word_of_the_day[i]: if guess[i] == word_of_the_day[i]:
wordle_result += "O" wordle_result += "O"
elif word_of_the_day.find(guess[i]) != -1: elif word_of_the_day.find(guess[i]) != -1:
wordle_result += "_" wordle_result += "_"
else: else:
wordle_result += "X" wordle_result += "X"
return wordle_result return wordle_result
max_num_guesses = 6 max_num_guesses = 6
current_num_guesses = 1 current_num_guesses = 1
word_of_the_day = "CRANE" word_of_the_day = "CRANE"
print("Welcome to PyWordle!") print("Welcome to PyWordle!")
print("You have 6 guesses to guess a 5 character word.") print("You have 6 guesses to guess a 5 character word.")
print("X\tThe letter is not in the word.") print("X\tThe letter is not in the word.")
print("_\tThe letter is in the word, but in the wrong place.") print("_\tThe letter is in the word, but in the wrong place.")
print("O\tThe letter is in the correct place!") print("O\tThe letter is in the correct place!")
while current_num_guesses <= max_num_guesses: while current_num_guesses <= max_num_guesses:
guess = input("Guess the word: ") guess = input("Guess the word: ")
guess = guess.upper() guess = guess.upper()
wordle_results = get_wordle_results(guess) wordle_results = get_wordle_results(guess)
print("{}\t{}".format(guess, wordle_results)) print("{}\t{}".format(guess, wordle_results))
if guess == word_of_the_day: if guess == word_of_the_day:
break break
current_num_guesses += 1 current_num_guesses += 1
if current_num_guesses > max_num_guesses: if current_num_guesses > max_num_guesses:
print("Better luck next time!") print("Better luck next time!")
print("The word was: {}".format(word_of_the_day)) print("The word was: {}".format(word_of_the_day))
else: else:
print("You won in {} guesses!".format(current_num_guesses)) print("You won in {} guesses!".format(current_num_guesses))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment