Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
C
cs220-lecture-material
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Iterations
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package Registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Service Desk
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
CDIS
Computer Sciences
Courses
CS220
cs220-lecture-material
Commits
38182c44
Commit
38182c44
authored
1 year ago
by
Anna Meyer
Browse files
Options
Downloads
Patches
Plain Diff
list code template change
parent
3559f1e3
No related branches found
No related tags found
No related merge requests found
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
sum23/lecture_materials/08_Lists/lec_08_lists_template.ipynb
+29
-0
29 additions, 0 deletions
sum23/lecture_materials/08_Lists/lec_08_lists_template.ipynb
with
29 additions
and
0 deletions
sum23/lecture_materials/08_Lists/lec_08_lists_template.ipynb
+
29
−
0
View file @
38182c44
...
...
@@ -137,6 +137,14 @@
"print(grocery_list[len(grocery_list)])"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Write loops that process lists"
]
},
{
"cell_type": "code",
"execution_count": null,
...
...
@@ -194,6 +202,27 @@
"How does Python differentiate between two different usages of `[]`?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def longest_word(word_list):\n",
" '''Given a list of strings, return the string with the longest length.\n",
" If more than one, return the first one.'''\n",
"\n",
" max_length = 0\n",
" longest_word = None\n",
"\n",
" return longest_word\n",
"\n",
"print(grocery_list)\n",
"print(longest_word(grocery_list))\n",
"print(longest_word([\"aaaa\", \"xyz\", \"hello\"]))\n",
"print(longest_word([]))"
]
},
{
"attachments": {},
"cell_type": "markdown",
...
...
%% Cell type:markdown id: tags:
# Lists
%% Cell type:code id: tags:
```
python
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:
## Learning Objectives
%% Cell type:markdown id: tags:
-
Create a list and use sequence operations on a list.
-
Write loops that process lists
-
Explain key differences between strings and lists: type flexibility, mutability
-
Mutate a list using:
-
indexing
-
methods such as append, extend, sort, and pop
-
split() a string into a list
-
join() list elements into a string
%% Cell type:markdown id: tags:
### Motivation for lists:
-
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:
-
int
-
float
-
str
-
bool
-
other lists, etc.,
%% Cell type:code id: tags:
```
python
day
=
"
Monday
"
# first quotation indicates beginning of string sequence
# second quotation indicates end of string sequence
```
%% Cell type:code id: tags:
```
python
empty_list
=
None
some_nums
=
None
# [ indicates beginning of sequence
# ] indicates end of sequence
```
%% Cell type:code id: tags:
```
python
grocery_list
=
[
"
apples
"
,
"
milk
"
,
"
broccoli
"
,
"
spinach
"
,
"
oranges
"
]
# TODO: compute length of grocery_list
print
()
# TODO: use indexing to display broccoli
print
()
# TODO: use indexing to display last item
print
()
# TODO: use slicing to extract only the vegetables
print
()
```
%% Cell type:code id: tags:
```
python
# TODO: discuss why the following gives IndexError
print
(
grocery_list
[
len
(
grocery_list
)])
```
%% Cell type:markdown id: tags:
#### Write loops that process lists
%% Cell type:code id: tags:
```
python
# Iterate over every item in grocery_list to display:
# <Item> purchased!
for
item
in
???
:
print
()
```
%% Cell type:code id: tags:
```
python
# Compute sum of numbers in some_nums
# Let's do this example using PythonTutor
total
=
0
# TODO: for loop to iterate over each number in some_nums
print
(
total
)
```
%% Cell type:code id: tags:
```
python
# We can use a list instead of a variable for each operation
[
10
,
20
,
30
][
1
]
```
%% Cell type:code id: tags:
```
python
# We can use a list instead of a variable for each operation
[
10
,
20
,
30
][
1
:]
```
%% Cell type:markdown id: tags:
How does Python differentiate between two different usages of
`[]`
?
%% Cell type:code id: tags:
```
python
def
longest_word
(
word_list
):
'''
Given a list of strings, return the string with the longest length.
If more than one, return the first one.
'''
max_length
=
0
longest_word
=
None
return
longest_word
print
(
grocery_list
)
print
(
longest_word
(
grocery_list
))
print
(
longest_word
([
"
aaaa
"
,
"
xyz
"
,
"
hello
"
]))
print
(
longest_word
([]))
```
%% Cell type:markdown id: tags:
### Other sequence operations
-
concatentation using
`+`
-
`in`
-
multiply by an
`int`
%% Cell type:code id: tags:
```
python
msg
=
"
Happy
"
print
(
msg
+
"
Monday :)
"
)
some_nums
=
[
11
,
22
,
33
,
44
]
print
(
some_nums
+
[
1
,
2
,
3
])
# `+` concatenates two lists
```
%% Cell type:code id: tags:
```
python
msg
=
"
Happy
"
print
(
"
H
"
in
msg
)
print
(
"
h
"
in
msg
)
some_nums
=
[
11
,
22
,
33
,
44
]
print
(
33
in
some_nums
)
print
(
55
in
some_nums
)
```
%% Cell type:code id: tags:
```
python
msg
=
"
Happy :)
"
print
(
msg
*
3
)
print
([
"
Go
"
,
"
Badgers!
"
]
*
3
)
```
%% Cell type:markdown id: tags:
## Strings versus lists
<div>
<img
src=
"attachment:Mutation.png"
width=
"600"
/>
</div>
%% Cell type:markdown id: tags:
### Difference 1: lists are flexible
%% Cell type:code id: tags:
```
python
# String sequence can only contain characters as items
# List sequence can contain anything as an item
l
=
[
"
hello
"
,
14
,
True
,
5.678
,
None
,
[
"
list
"
,
"
inside
"
,
"
a
"
,
"
list
"
]]
# TODO: fix the bug in this loop
for
i
in
l
:
print
(
l
[
i
])
# TODO: use indexing to extract and print the inner list
print
()
# TODO: print type of last item in l
print
()
# TODO: use double indexing to extract "inside"
print
()
```
%% Cell type:code id: tags:
```
python
# List of lists usecase example
game_grid
=
[
[
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
S
"
],
[
"
.
"
,
"
S
"
,
"
S
"
,
"
S
"
,
"
.
"
,
"
S
"
],
[
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
S
"
],
[
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
],
[
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
S
"
,
"
.
"
],
[
"
.
"
,
"
.
"
,
"
.
"
,
"
.
"
,
"
S
"
,
"
.
"
]
]
for
row
in
game_grid
:
for
position
in
row
:
print
(
position
,
end
=
""
)
print
()
```
%% Cell type:markdown id: tags:
### Difference 2: lists are mutable
<div>
<img
src=
"attachment:Mutability.png"
width=
"600"
/>
</div>
-
Mutability has nothing to do with variable assignments / re-assignments
-
Mutability has to do with changing values inside a sequence
%% Cell type:code id: tags:
```
python
# Variables can always be re-assigned
s
=
"
AB
"
s
=
"
CD
"
s
+=
"
E
"
print
(
s
)
nums
=
[
1
,
2
]
nums
=
[
3
,
4
]
print
(
nums
)
```
%% Cell type:code id: tags:
```
python
name
=
"
Andrew
"
# 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
```
%% Cell type:code id: tags:
```
python
nums
=
[
2
,
2
,
9
]
# TODO: change 9 to 0
print
(
nums
)
# works because lists are mutable, that is you can change the value inside an existing list
```
%% Cell type:markdown id: tags:
### Mutating a list
-
update using index (works only for existing index)
-
`append`
method
-
`extend`
method
-
`pop`
method
-
`sort`
method
Unlike string methods, list methods mutate the original list. String methods produce a new string because strings are immutable.
%% Cell type:code id: tags:
```
python
grocery_list
=
[
"
apples
"
,
"
milk
"
,
"
broccoli
"
,
"
spinach
"
,
"
oranges
"
]
# TODO: try to add "blueberries" at index 5
grocery_list
[
???
]
=
"
blueberries
"
# doesn't work because grocery_list does not contain a previous item at index 5
```
%% Cell type:markdown id: tags:
So, how do we add a new item to a list?
%% Cell type:code id: tags:
```
python
grocery_list
.
append
(
"
blueberries
"
)
print
(
grocery_list
)
```
%% Cell type:markdown id: tags:
Can we add multiple items using
`append`
?
%% Cell type:code id: tags:
```
python
# Let's try to add "peanut butter", "jelly", "bread"
grocery_list
.
append
()
# doesn't work because append only accepts a single argument
```
%% Cell type:code id: tags:
```
python
grocery_list
.
append
()
# adds the list argument as such
print
(
grocery_list
)
```
%% Cell type:markdown id: tags:
`extend`
method will enable us to add every item in argument list to the original list as individual item.
%% Cell type:code id: tags:
```
python
grocery_list
.
extend
([
"
falafel
"
,
"
pita bread
"
,
"
hummus
"
])
print
(
grocery_list
)
```
%% Cell type:markdown id: tags:
`pop`
enables us to remove item from the list:
-
by default pop() removes the last item from the list
-
you can override that by passing an index as argument
-
pop remove the item from the original list and also returns it
%% Cell type:code id: tags:
```
python
grocery_list
.
pop
()
```
%% Cell type:code id: tags:
```
python
grocery_list
```
%% Cell type:code id: tags:
```
python
# TODO: remove "oranges" from grocery_list and store it into a variable
some_fruit
=
grocery_list
.
pop
(
???
)
print
(
some_fruit
)
print
(
grocery_list
)
```
%% Cell type:markdown id: tags:
`sort`
method enables us to sort the list using alphanumeric ordering.
TODO: Try sorting each of the following lists.
%% Cell type:code id: tags:
```
python
L
=
None
# TODO: initialize list with some unordered numbers
L
```
%% Cell type:code id: tags:
```
python
L
=
None
# TODO: initialize list with some unordered strings
L
```
%% Cell type:code id: tags:
```
python
L
=
[
False
,
True
,
False
,
True
,
True
]
L
```
%% Cell type:code id: tags:
```
python
L
=
[
"
str
"
,
1
,
2.0
,
False
]
L
.
sort
()
# Doesn't work as you cannot compare different types!
```
%% Cell type:markdown id: tags:
`split`
method splits a string into a list of strings, using a separator (argument)
-
Syntax: some_string.split(separator_string)
%% Cell type:code id: tags:
```
python
sentence
=
"
a,quick,brown,fox
"
words
=
sentence
.
split
(
"
,
"
)
words
```
%% Cell type:markdown id: tags:
`join`
method joins a list of strings into a single string using a separator (argument)
-
Syntax: separator_string.join(some_list)
%% Cell type:code id: tags:
```
python
characters
=
[
"
M
"
,
"
SS
"
,
"
SS
"
,
"
PP
"
,
""
]
place
=
"
I
"
.
join
(
characters
)
place
# TODO: remove the last item in characters list and see what place you get (re-run cell)
```
%% Cell type:markdown id: tags:
### List all Engineering majors (primary major) among current lecture (example: LEC001) students
%% Cell type:code id: tags:
```
python
for
idx
in
range
(
project
.
count
()):
lecture
=
project
.
get_lecture
(
idx
)
major
=
project
.
get_primary_major
(
idx
)
if
lecture
==
"
LEC001
"
:
print
(
lecture
,
major
)
```
%% Cell type:markdown id: tags:
### Profanity filtering
%% Cell type:code id: tags:
```
python
bad_words
=
[
"
omg
"
,
"
midterm
"
,
"
exam
"
]
def
censor
(
input_string
):
"""
replaces every bad word in input string with that word
'
s first
letter and then * for the remaining characters
"""
# 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: join the words back using the correct separator and return the joined string
censor
(
"
omg the midterm was so awesome!
"
)
```
%% Cell type:markdown id: tags:
### Wordle (self-study example)
%% Cell type:code id: tags:
```
python
def
get_wordle_results
(
guess
):
wordle_result
=
""
for
i
in
range
(
len
(
guess
)):
if
guess
[
i
]
==
word_of_the_day
[
i
]:
wordle_result
+=
"
O
"
elif
word_of_the_day
.
find
(
guess
[
i
])
!=
-
1
:
wordle_result
+=
"
_
"
else
:
wordle_result
+=
"
X
"
return
wordle_result
max_num_guesses
=
6
current_num_guesses
=
1
word_of_the_day
=
"
CRANE
"
print
(
"
Welcome to PyWordle!
"
)
print
(
"
You have 6 guesses to guess a 5 character word.
"
)
print
(
"
X
\t
The letter is not in the word.
"
)
print
(
"
_
\t
The letter is in the word, but in the wrong place.
"
)
print
(
"
O
\t
The letter is in the correct place!
"
)
while
current_num_guesses
<=
max_num_guesses
:
guess
=
input
(
"
Guess the word:
"
)
guess
=
guess
.
upper
()
wordle_results
=
get_wordle_results
(
guess
)
print
(
"
{}
\t
{}
"
.
format
(
guess
,
wordle_results
))
if
guess
==
word_of_the_day
:
break
current_num_guesses
+=
1
if
current_num_guesses
>
max_num_guesses
:
print
(
"
Better luck next time!
"
)
print
(
"
The word was: {}
"
.
format
(
word_of_the_day
))
else
:
print
(
"
You won in {} guesses!
"
.
format
(
current_num_guesses
))
```
%% Cell type:code id: tags:
```
python
```
...
...
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment