1 of 43

AddisCoder: Week 2

Lecture 6A:

  • Intro
  • Dictionaries
  • Functions

2 of 43

Intro & Logistics

3 of 43

Who am I?

  • My name is Huy Nguyen.
  • Associate Professor at Northeastern University

Live in Massachusetts. I like to hike and play soccer.

4 of 43

Why Study Computer Science?

Modern daily life power by CS.

5 of 43

Why Study Computer Science?

Major driver of progress of our civilization.

6 of 43

Why Study Computer Science?

Not just by traditional Software Engineering...

7 of 43

Why Study Computer Science?

Many reasons beyond just wanting to make websites and apps!

It’s also just fun :)

8 of 43

Day Structure

  • Similar schedule as in the first week.
  • We will adjust as we go.

TIME

SCHEDULE

9:00-10:00

Lecture A

10:00-12:00

Lab A

12:00-1:00

Lunch

1:00-1:30

Break

1:30-2:30

Lecture B

2:30-5:00

Lab B

9 of 43

Week Overview

Learning Objectives for this week

  • be able to write functions and compose them together to solve real problems
  • dictionaries
  • be comfortable with nested loops, nested lists
  • understand recursion
    • structure of a recursive function
    • solving problems recursively or iteratively
  • apply above concepts to manipulate images
  • fundamentals of algorithms and time complexity

10 of 43

Week Overview

MON

TUES

WED

THURS

FRI

July 25, 2023

July 26, 2023

July 27, 2023

July 28, 2023

July 29, 2023

Lecture 6A�Intro, Week 1 Review, Functions

Lecture 7A

Libraries, Pixels and Images, Image Manipulation

Lecture 8A

Recursion

Lecture 9A

More Recursion

Lecture 10A

Review, Quiz

Lecture 6B

Nested Lists, Nested Loops, Slicing

Lecture 7B

More Images

Lecture 8B

More Recursion

Lecture 9B

Time Complexity

Lecture 10B

Maps, List Comprehensions

11 of 43

Lecture Structure

  • Mix of slides and Jupyter Notebook
  • Questions throughout
  • Interactive!

Let’s begin!

12 of 43

Dictionaries

13 of 43

Dictionaries

Like physical dictionary, Python dictionaries are used for look-up.

14 of 43

Dictionaries

Like physical dictionary, Python dictionaries are used for look-up.

Physical dictionary: look up definition for word.

Python dictionary: look up value using a key.

15 of 43

Dictionaries

Like physical dictionary, Python dictionaries are used for look-up.

Physical dictionary: look up definition for word.

Python dictionary: look up value using a key.

These are also sometimes called “maps”.

16 of 43

Dictionaries

A dictionary is an unordered collection of key:value pairs.

17 of 43

Dictionaries

A dictionary is an unordered collection of key:value pairs.

Dictionaries are good to use when you have a mapping of some sort, such as...

    • Name (Alex) -> Grade (95)
    • Class (AddisCoder) -> Location (Ethiopia)
    • Word (“the”) -> frequency (950)

18 of 43

Creating a Dictionary

We use curly braces to create a dictionary:

grades = {

"HW1": 95,

"Lab1": 100,

"Lab2": 90

}

19 of 43

Creating a Dictionary

We use curly braces to create a dictionary:

Key and value pairs are given with a colon in between, separated by commas.

grades = {

"HW1": 95,

"Lab1": 100,

"Lab2": 90

}

Key

Value

20 of 43

Indexing (Reading from the Dictionary)

Index into the dictionary using the key to get the associated value.

Notice, indexing here is just like for lists, except you put the key inside the brackets.

grades = {

"HW1": 95,

"Lab1": 100,

"Lab2": 90

}

score1 = grades["HW1"] # == 95

21 of 43

Dictionary KeyError

If you try to get the value associated with a key that doesn’t exist, you get a KeyError.

grades = {

"HW1": 95,

"Lab1": 100,

"Lab2": 90

}

score1 = grades["Exam1"]

22 of 43

Dictionaries

What types can be in a dictionary?

  • Keys must be immutable.
    • From the types we know so far, ints, floats, booleans, and strings are all ok to be keys.
    • A list or dictionary cannot be a key in a dictionary.
  • Values can be anything, mutable or immutable.

movie_info = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'actors': ['Ryunosuke Kamiki', 'Mone Kamishiraishi'],

'score': 96,

}

23 of 43

Dictionary Mutation

24 of 43

Mutation

It’s very common to want to update the values in a dictionary.

Let’s use this sample dictionary as an example.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

25 of 43

Mutation

Just like lists, dictionaries are Mutable using assignment.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

26 of 43

Mutation: Add an Item

Just like lists, dictionaries are Mutable using assignment.

�Insert new key:value pair by assigning to the new key.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

27 of 43

Mutation: Change an item

Just like lists, dictionaries are Mutable using assignment.

�Keys are unique, so assigning to an existing one replaces it.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

28 of 43

Mutation: Change an item

Just like lists, dictionaries are Mutable using assignment.

�Keys are unique, so assigning to an existing one replaces it.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

movie['title'] = 'Finding Nemo'

29 of 43

Mutation: Delete an Item

Delete key:value pairs by passing the key into the dictionary.pop() function.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

movie['title'] = 'Finding Nemo'

30 of 43

Mutation: Delete an Item

Delete key:value pairs by passing the key into the dictionary.pop() function.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

movie['title'] = 'Finding Nemo'

movie.pop('score')

31 of 43

Mutation: Delete an Item

Delete key:value pairs by passing the key into the dictionary.pop() function.

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

movie['title'] = 'Finding Nemo'

movie.pop('score')

32 of 43

Checking Dictionary Contents

To check whether a key exists, use `in` operator. `in` operator only checks keys of dictionary

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

contains_key = 'screenwriter' in movie # == False

33 of 43

Checking Dictionary Contents

To check whether a key exists, use `in` operator. `in` operator only checks keys of dictionary

movie = {

'title': 'Your Name',

'year': 2016,

'rating': 'PG',

'running_time': 112,

'score': 96,

}

movie['writer'] = 'Andrew'

contains_key = 'writer' in movie # == True

34 of 43

Dictionary Iteration

35 of 43

Iteration

Dictionaries are unordered. But we can still iterate over them with a forloop.

�This iterate over keys in the dictionaries. Keys are not guaranteed to be in the order you created them.

for key in dictionary:

print(key) # print current key

print(dictionary[key]) # print value at that key

36 of 43

Iteration: Example

Example of iterating over keys and values

��PythonTutor Link

abbreviations = {'Louisiana': 'LA', 'Utah': 'UT', 'Oregon': 'OR'}

for state in abbreviations:

print('State: ', state)

print('Postal abbreviation: ', abbreviations[state])

37 of 43

Coding Example:

Letter Count Accumulation

38 of 43

Coding Example:

Letter Count Accumulation

s = “abcabc”

frequency_dict = {}

for char in s:

if char in frequency_dict:

frequency_dict[char] += 1

else:

frequency_dict[char] = 1

print(frequency_dict)

39 of 43

Input

40 of 43

Input

We learned “output” for how to print stuff out to the terminal. Now, we will learn how to take things in from the terminal.

New function!

answer = input("Prompt")

41 of 43

Input

We learned “output” for how to print stuff out to the terminal. Now, we will learn how to take things in from the terminal.

New function!

��Prints “Prompt” to the screen, then waits for user to provide input.

answer = input("Prompt")

42 of 43

Input

We learned “output” for how to print stuff out to the terminal. Now, we will learn how to take things in from the terminal.

New function!

��Prints “Prompt” to the screen, then waits for user to provide input.

We assign the words that the user types in to the variable answer.

answer = input("Prompt")

43 of 43

Function Review

  1. Think of a function as a (sub)routine.
  2. Why use functions?
    1. Reuse the same code for different inputs
    2. Abstraction: to use a function, just need to know the inputs and the promised outputs, do not need to know how it works

Vocab:

  • Using a function is called calling or executing the function
    • Function calls are expressions that need to be evaluated
    • The input values given in the function call are called arguments
  • Creating a new function is called defining it
    • The input variables in the definition are called parameters
    • We can return a value for the function to evaluate to