CS10: The Beauty and Joy of Computing - Su22
Lecture 13: Python II: Data Structures
Announcements
Midterm Scores (graded out of 140 points)
Midterm Scores
Object Oriented Programming
Code Translations (finishing up last time)
Concepts that don’t translate well between Snap! and Python:
Object Oriented Programming
Recall from the programming paradigms lecture the definition of object-oriented-programming:
In Snap! we may have had sprites representing objects interacting with each other
Object Oriented Programming- dot notation
The syntax for adding an item to a list is quite different from Snap!
some_list = [2, 4, 7, 11]
some_list.append("ketchup")
Object Oriented Programming
This is the Object Oriented Programming paradigm!
some_list = [2, 4, 7, 11]
some_list.append("ketchup")
ketchup
2 4 7 11
ketchup
The list itself does the work! (See 61A)
add __ to __
Types and Functions
Each type has its own special set of functions.
Examples:
https://docs.python.org/3/library/stdtypes.html#str
�
Example of a String Skill
numbers_text = input("Gimme: ")
numbers_list = numbers_text.split(" ")
print(numbers_list)
$ python3 split_user_numbers.py
Gimme: 1 2 3
[‘1’, ‘2’, ‘3’]
Many String Functions Don’t Exist in Snap!
print("cat".upper())
print("abracadabra".count("a"))
print("cool boot".replace("oo", "el"))
$ python3 string_examples.py
CAT
5
cell belt
Even More String Functions
Join is a particular interesting string ability.
', '.join(['apple', 'banana', 'cow'])
‘, ‘
['apple', 'banana', 'cow']
List Basics
List Basics
some_list = [0, 10, 20, 30, 40, 50]
some_list[0] → 0
some_list[4] → 40
some_list[len(some_list)-1] → 50
some_list[-1] → 50
len(some_list) → 6
List Basics
some_list = [0, 10, 20, 30, 40, 50]
middle_items = some_list[1:5]
print(middle_items)
some_list = [0, 10, 20, 30, 40, 50]
some_list[1:5] → [10, 20, 30, 40]
some_list[:3] → [0, 10, 20]
some_list[2:] → [20, 30, 40, 50]
some_list[:] → [0, 10, 20, 30, 40, 50]
some_list[3] = 35
print(some_list) → [0, 10, 20, 35, 40, 50]
List Basics
some_list = [0, 10, 20, 30, 40, 50]
middle_items = some_list[1:5]
print(middle_items)
some_list.pop()
some_list.append(4)
some_list.remove(3)
List Comprehensions
Defining Functions Review
Recall from yesterday’s lecture
def is_even(x):
if x % 2 == 0:
return True
else:
return False
In Snap!
As mentioned in the previous lecture, Python also has a map function:
This is the equivalent of the Snap! program below:
def reverse(s):
return s[::-1]
L = ["i", "am", "josh", "hug"]
map(reverse, L)
reverse is a function which reverses a string. The exact details of how it does this are not important.
In Snap!
As mentioned in the previous lecture, Python also has a map function:
One annoyance is that the map function in Python returns a “map object”, not a list. If we want our answer to be of type list, we have to convert it into a list as follows:
def reverse(s):
return s[::-1]
L = ["i", "am", "josh", "hug"]
map(reverse, L)
reverse is a function which reverses a string. The exact details of how it does this are not important.
def reverse(s):
return s[::-1]
L = ["i", "am", "josh", "hug"]
Lr = list(map(reverse, L))
List Comprehensions
Few people use “map” today. Instead, it is much more popular to use a list comprehension.
Lr = [reverse(x) for x in L]
Lr = list(map(reverse, L))
List Comprehension
Map Invocation
List Comprehensions
The syntax for a list comprehension (as we’ve seen it so far) has 3 components:
Lr = [reverse(x) for x in L]
Lr = list(map(reverse, L))
List Comprehension
Map Invocation
some_var
some_list
Map and Filter
Python also has a version of keep, called filter, which can of course be combined with map.
def reverse(s):
return s[::-1]
def longer_than_2(s):
return len(s) > 2
L = ["i", "am", "josh", "hug"]
map(reverse, filter(longer_than_2, L))
List Comprehensions That Also Filter
Can also create a list comprehension which filters out unwanted items (similar to keep).
Note: As before, the syntax inside a list comprehension is very special. The if here is NOT a normal conditional. Don’t try to read it like normal python code!
def reverse(s):
return s[::-1]
Lr = [reverse(x) for x in L if len(x) > 2]
List Comprehension Summary
map
[f(element) for element in iterable]
keep
[element for element in iterable if cond(element)]
map+keep
[f(element) for element in iterable if cond(element)]
[f(element) if cond(element) else other for element in iterable]
Idiomatic Python
While equivalent, most Python programmers use list comprehensions instead of explicit HoFs like map and filter.
When programming, you should strive to adopt the idioms of the language you’re using.
Python Sequences: Lists, Strings, Tuples, Ranges
(and more)
Strings in Python
Similar to a text in Snap!, Python allows us to create strings. Three ways to specify a String:
Can access characters using bracket notation, just like a list.
Strings are immutable- we cannot change/edit them
s1 = 'hello bob'
s2 = "hello alice"
s3 = """this
is a string
on many lines"""
print(s2[1:4])
s2[0] = 'y'
ell
TypeError:
'str' object does not support item assignment
String Functions
As mentioned before, there are many handy functions for working with strings.
"this is a sentence".split()
len('kaimuki')
"the biggest pig".title()
“The Biggest Pig”
Python Lists vs. Strings
Lists and Strings are both sequences.
��
See official Python documentation on sequences for more.
if "dog" in x[2:10]:
print("woof")
Works if x is any kind of sequence, e.g. string or list.
Ranges
We saw in lab that we can iterate over a range of numbers:
A range is just an object like any other.
total = 0
for x in range(0, 4):
total = total + x
print(total)
6
Converting Between Types
As we saw last time, Python is picky about types.
number = 5
text = “6”
print(number + text)
number = 5
text = “6”
print(number + int(text))
11
Converting a Range to a List
Can convert any sequence into a list using the list function:
x = range(0, 4)
x.append(4)
listX = list(x)
listX.append(4)
works fine
Tuples
Tuples are almost exactly like lists except:
Question: What good is a less powerful list?
�
some_tuple = (1, 5, 10, 4, 7, 16, 2)
some_list = [1, 5, 10, 4, 7, 16, 2]
Programming Language Design and Good Coding Style
Modern programming languages are designed to be beautiful, expressive, and simple.
Keeping things simple means restricting the space of things the programmer needs to think about. Examples:
Sets and Dictionaries
Sets
Sets are kind of like lists or tuples, except:
set_one = set([1, 3, 5])
set_two = set([3, 4, 5, 6, 7])
set_one = set_one.union(set_two)
print(set_one)
Counting Unique Items Using a Set
One trick you can do with a set is count unique items.
words = ["Can","you","can","a","can","as","a","canner","can","can","a","can?"]
unique_words = set(words)
print(unique_words)
print(len(unique_words))
Dictionaries
Can think of dictionaries as a more powerful kind of list.
phonebook = {}
phonebook["Josh"] = "713-474-2731"
phonebook["Board X-5"] = "713-474-3750"
phonebook["Tom Bates"] = "510-981-7100"
print(phonebook["Tom Bates"])
Dictionaries
phonebook = {}
phonebook["Alonzo"] = "713-474-2731"
phonebook["Oznola"] = "713-474-3750"
phonebook["Tom Bates"] = "510-981-7100"
print(phonebook["Tom Bates"])
Dictionaries
Some handy dictionary functions:
numerals = {'I': 1, 'V': 5, 'X': 10}
print(list(numerals.keys()))
print(list(numerals.values()))
Dictionary Syntax Summary
> D1[1]
“One”
dict.get(key, value=None)
> D1.get(2, 0) # 2 not a key in D1, returns given value
0
> D1.get(2) # returns nothing or errors
D1[“hello”] = “Alonzo”
Iterating through a Dictionary
for k in my_dictionary.keys():
for k in my_dictionary:
for v in my_dictionary.values():
for k,v in my_dictionary.items():
k in my_dictionary.keys()
k in my_dictionary
v in my_dictionary.values()
Summary
Today we saw a lot of things: