Lecture 11: Coding as Pattern Matching - a Review Lecture¶
We are almost half way through the semester! Before going into spring break, let's review what we have learned and in this lecture we'll go over some practical way of approaching coding problems, or how to start writing some code from scratch.
By the end of this lecture, students should be able to:
- Recognize and name common code patterns
- Break a problem into parts before writing any code
- Have a toolbox of questions to ask to help scaffold creating functions
The Core Idea: Pattern Matching¶
Python is a programming language. Just like any language, you learn about its vocabulary and grammar before speaking and writing longer sentences and entire passages. Python is no difference, we learn about its vocabulary (e.g., print(), type(), string literals, numeric data) and grammar (arithmetic operators, expressions, conditionals, loops) before creating data structures with different data types and manipulating them and writing longer functions and snippets of code that achieve a certain functionality.
When faced with a problem, we do no start from scratch. Always try to look for what you have seen before, whether it's an example snippet in lecture notes, assignments, or the starter code, helper functions.
It takes practice to build this reflex of seeing a problem and just getting what you need to use to solve it, and today we are going to practice this as much as we can.
Name the Pattern¶
For the following code snippets, what is each of them doing? What pattern is it (or what Python constructs appear here)?
Snippet A:
def double(n):
"""Given n, create a list with numbers 0~(n-1) doubled."""
result = []
for item in range(n):
result.append(item * 2)
return result
Pattern...
function definition, docstring, for loop, range() to create sequence of numbers, accumulator pattern
Snippet B:
# assuming inside a function
if x > 0:
return "positive"
elif x == 0:
return "zero"
else:
return "negative"
Pattern...
if-elif-else, conditionals, branched execution
Snippet C:
# grid is a 2D array defined before
for i in range(len(grid)):
for j in range(len(grid[i])):
grid[i][j] = 0
Pattern...
nested loop iterating over 2D array, index based for loops with range(), resetting every cell to 0
Snippet D:
def sum_even(numbers):
"""Given a list numbers, return the sum of all the items that are even numbers."""
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total
Pattern...
accumulator pattern, value based for loop, modulo 2 if condition to check number parity
Snippet E:
# rows and cols are integers defined before
num = 0
grid = []
for i in range(rows):
row = []
for j in range(cols):
row.append(num)
num += 1
grid.append(row)
Pattern...
row-based 2D grid construction, index based iteration with range(), nested for loops, accumulator, filling in the array with increasing integer starting from 0
Read Other People's Code¶
Let's continue from where we left off last week. We will read knitout_helpers.py from HW2 and understand its structure and what each helper function does.
From Problem to Code¶
Programming is essentially converting your solution into something that computers can do for you. So before coding, we should be able to describe what we would do to solve the problem ourselves. Oftentimes, we can write something called pseudocode to indicate what we would do in the actual code but not in the exact syntax, and after that we can translate from pseudocode to actual code.
Let's now do some more practice together.
Variables and Expressions¶
Write a function celsius_to_fahrenheit(temp) that converts a temperature from Celsius to Fahrenheit. Formula: F = C * 9/5 + 32
Start by answering the questions in the checklist! Feel free to add cells to test with your own test cases.
[ ] What is the function name?
[ ] What are the parameters? (names + what they represent)
[ ] What is the function doing? (one sentence: given X, returns Y)
[ ] What is the return value? (type + meaning)
[ ] What pattern does the body need? (loop? conditional? both?)
[ ] What are the variables I'll need inside?
# TODO: your code here
def celsius_to_fahrenheit(temp):
"""
Converts from temperature in celsius to temperature in fahrenheit.
"""
return temp * 9/5 + 32
celsius_to_fahrenheit(23)
73.4
Conditionals, Loops, Strings¶
Write a function count_long_words(words, min_length) that takes a list of strings and a minimum length, and returns how many words are at least that long.
Example: count_long_words(["def", "function", "parenthesis", "parameter", "colon"], 6)
Expected output: 3
Start by answering the questions in the checklist! Feel free to add cells to test with your own test cases.
[ ] What is the function name?
[ ] What are the parameters? (names + what they represent)
[ ] What is the function doing? (one sentence: given X, returns Y)
[ ] What is the return value? (type + meaning)
[ ] What pattern does the body need? (loop? conditional? both?)
[ ] What are the variables I'll need inside?
def count_long_words(words, min_length):
"""
Takes in a list of words and the minimin length of a word
to be considered a long word and count the number of long
words.
"""
count = 0
for word in words:
if len(word) >= min_length:
count += 1
return count
count_long_words(["def", "function", "parenthesis", "parameter", "colon"], 6)
3
2D Arrays and Indexing¶
Write a function make_stripe_grid(rows, cols, colors) that returns a 2D list where each row alternates through the given colors. Row 0 uses colors[0], row 1 uses colors[1], and so on; the colors wrap around if there are more rows than colors.
Example: make_stripe_grid(4, 3, ["A", "B"])
Expected output: [["A","A","A"], ["B","B","B"], ["A","A","A"], ["B","B","B"]]
Start by answering the questions in the checklist! Feel free to add cells to test with your own test cases.
[ ] What is the function name?
[ ] What are the parameters? (names + what they represent)
[ ] What is the function doing? (one sentence: given X, returns Y)
[ ] What is the return value? (type + meaning)
[ ] What pattern does the body need? (loop? conditional? both?)
[ ] What are the variables I'll need inside?
# TODO: your code here
def make_stripe_grid(rows, cols, colors):
"""
Create a grid of stripes of alternating colors.
The grid size is rows x cols.
"""
grid = []
for i in range(rows):
row = []
color = colors[i % len(colors)]
# if i % 2 == 0:
# color = colors[0]
# else:
# color = colors[1]
for j in range(cols):
row.append(color)
grid.append(row)
return grid
make_stripe_grid(4, 3, ["A", "B"])
[['A', 'A', 'A'], ['B', 'B', 'B'], ['A', 'A', 'A'], ['B', 'B', 'B']]