0% found this document useful (0 votes)
13 views36 pages

Lecture 5

The document is a lecture on algorithms and programming, focusing on lists, associative arrays (dictionaries), sets, and functions in Python. It includes examples of how to use these data structures and the importance of functions for code organization and reusability. The lecture emphasizes the benefits of functions in programming, such as improving readability and maintainability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views36 pages

Lecture 5

The document is a lecture on algorithms and programming, focusing on lists, associative arrays (dictionaries), sets, and functions in Python. It includes examples of how to use these data structures and the importance of functions for code organization and reusability. The lecture emphasizes the benefits of functions in programming, such as improving readability and maintainability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to Algorithms &

Programming
Steve James
Lecture 5
Homework
• Write a program that reads a series of names
into a list. Use your own name and your
friends’! Loop through each name in the list
and flip a coin. If heads, the person survives. If
tails, the person does not!
• Print out all the people that survived Thanos’
plan! Did you?
import random
names = list()
name = input()
while name != "":
names.append(name)
name = input()
for name in names:
if random.choice([True, False]):
print(name, "survived")
else:
print(name, "dead")
RECAP

LISTS
Lists
• A list is a built-in type that lets us store a
collection of values
values = [27, 39, False, "Batman > Superman"]

• Loop through:
for x in values:
print(x)

• Check if contains
if 28 in values:
Python

ASSOCIATIVE CONTAINERS
Associative arrays
• Collections of key-value pairs
• Also known as maps, dictionaries, symbol
tables
• Offer ability to:
– add a key-value pair to the collection
– remove a key-value pair
– modify an existing pair
– lookup a value given a particular key
• In Python, we use a dictionary (dict)
Example
• Students have names and marks
• Want to relate mark to each name
– i.e. given a name, what is the mark?

Vegeta: 99
Goku: 9001
Freeza: 80
dict
• Create an empty dict using:
my_dict = dict() # or my_dict = {}

• Create a dict of key-values with:


another_dict = {"Vegeta": 99, "Goku": 9001}

• Keys are unique


• Can use ints and strings as keys (others too)
Adding/Modifying

• Add with overwrite

marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
marks["Vegeta"] = 40 # overwrites
Removing
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
marks["Vegeta"] = 40
marks.pop("Vegeta")
Querying
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
is_goku_a_key = "Goku" in marks
goku_mark = marks["Goku"]
Iteration
marks = dict()
marks["Vegeta"] = 99
marks["Goku"] = 9001
for name, mark in marks.items():
print(name, ":", mark)
"""
Output:
Vegeta : 99
Goku : 9001
"""
set
• Stores keys only, not key-value pairs
• Keys are unique
• Keys are not ordered!
• KEYS CANNOT BE OVERWRITTEN ONCE INSERTED
• Create an empty set using:
my_set = set()

• Create a set of values with:


another_set = {"Vegeta", "Goku"}
Adding
names = set()
names.add("Vegeta")
names.add("Goku")
Removing
names = set()
names.add("Vegeta")
names.add("Goku")
names.remove("Vegeta")
Querying
names = set()
names.add("Vegeta")
names.add("Goku")
is_goku_a_key = "Goku" in names
Iteration
names = set()
names.add("Vegeta")
names.add("Goku")
for name in names:
print(name)
"""
Output:
Vegeta
Goku
"""
Early Abstraction

FUNCTIONS
Example
• Calculate the bill for a table at a restaurant
– Restaurant has multiple tables
– Consider
• Discount
• Tax
• Tip
Without function
# Table 1 Bill Calculation (in Rands) tip_table2 = subtotal_table2 * 0.15
items_table1 = [85.50, 65.00, 105.75] # Prices of items in final_total_table2 = subtotal_table2 + tax_table2 +
Rands tip_table2
total_table1 = sum(items_table1)
if total_table1 > 200: print("Table 2 Bill:")
discount_table1 = total_table1 * 0.10 # 10% discount print("Items:", items_table2)
if total > R200 print("Total: R", total_table2)
else: print("Discount: R", discount_table2)
discount_table1 = 0 print("Subtotal after discount: R", subtotal_table2)
subtotal_table1 = total_table1 - discount_table1 print("Tax (15%): R", tax_table2)
tax_table1 = subtotal_table1 * 0.15 # 15% VAT print("Tip (15%): R", tip_table2)
tip_table1 = subtotal_table1 * 0.15 # 15% tip print("Final Total: R", final_total_table2)
final_total_table1 = subtotal_table1 + tax_table1 + print()
tip_table1
# Table 3 Bill Calculation (in Rands)
print("Table 1 Bill:") items_table3 = [50.00, 50.00, 50.00, 50.00, 50.00]
print("Items:", items_table1) total_table3 = sum(items_table3)
print("Total: R", total_table1) if total_table3 > 200:
print("Discount: R", discount_table1) discount_table3 = total_table3 * 0.10
print("Subtotal after discount: R", subtotal_table1) else:
print("Tax (15%): R", tax_table1) discount_table3 = 0
print("Tip (15%): R", tip_table1) subtotal_table3 = total_table3 - discount_table3
print("Final Total: R", final_total_table1) tax_table3 = subtotal_table3 * 0.15
print() tip_table3 = subtotal_table3 * 0.15
final_total_table3 = subtotal_table3 + tax_table3 +
# Table 2 Bill Calculation (in Rands) tip_table3
items_table2 = [150.00, 120.00, 90.00, 60.00]
total_table2 = sum(items_table2) print("Table 3 Bill:")
if total_table2 > 200: print("Items:", items_table3)
discount_table2 = total_table2 * 0.10 print("Total: R", total_table3)
else: print("Discount: R", discount_table3)
discount_table2 = 0 print("Subtotal after discount: R", subtotal_table3)
subtotal_table2 = total_table2 - discount_table2 print("Tax (15%): R", tax_table3)
tax_table2 = subtotal_table2 * 0.15 print("Tip (15%): R", tip_table3)
What’s the problem?
• Monolithic code
– Hard to read
– Impossible to maintain

• No code reuse
– We write something that other users may be
interested in. Want to make that available

• More than one person working on the code?


With function
def print_bill(table_number, items):
total = sum(items)
if total > 200:
discount = total * 0.10
else:
discount = 0
subtotal = total - discount
tax = subtotal * 0.15
tip = subtotal * 0.15
final_total = subtotal + tax + tip

# Print a detailed breakdown of the bill


print(f"Table {table_number} Bill:")
print("Items:", items)
print("Total: R", total)
print("Discount: R", discount)
print("Subtotal after discount: R", subtotal)
print("Tax (15%): R", tax)
print("Tip (15%): R", tip)
print("Final Total: R", final_total)
print()

# Call the function for each table with different lists of item prices
print_bill(1, [85.50, 65.00, 105.75])
print_bill(2, [150.00, 120.00, 90.00, 60.00])
print_bill(3, [50.00, 50.00, 50.00, 50.00, 50.00])
What are functions?
• Also called methods, procedures, subroutines
• A function is a piece of code or a module that
– Has been “packaged” as a unit
– Usually serve a single purpose / task
– Performs a task and then returns control to the caller
• After the function has performed the task, the program will
continue execution from the point after the call
– Can be executed several times and called from
different places during a single execution of a program
What are functions?
• Consider mathematical functions:
Let 𝑓 𝑥 = 𝑥 2

• Function 𝑓 takes parameter 𝑥


– And does something with it

• We can call 𝑓 by giving providing an argument:


𝑓 2 → 4
What are functions?
𝑓 𝑥 = 𝑥2

• 𝑓 is the function’s name


𝑔 𝑥 = 𝑥2

• 𝑥 is the parameter
𝑓 𝑡 = 𝑡2
2 𝑓 𝑥 =
𝑓 𝑥 =𝑥
𝑥2

𝑠𝑞𝑢𝑎𝑟𝑒 𝑛𝑢𝑚 = 𝑠𝑞𝑢𝑎𝑟𝑒 𝑥 =


𝑛𝑢𝑚2 𝑥2

𝑠𝑞𝑢𝑎𝑟𝑒 𝑛𝑢𝑚 :
𝑛𝑢𝑚2

def 𝑠𝑞𝑢𝑎𝑟𝑒 𝑛𝑢𝑚 :


return 𝑛𝑢𝑚 ∗∗ 2
Functions as black boxes

Some function

0 or more things
0 or more inputs
returned

Function Some work Function output


parameters happens here
General Form
• In Python, functions take the form

def <function_name>(<parameter_list>):
<function_body>
Examples
How to call the functions:

def add(x, y):


x = 5
return x + y
y = add(2, x);

def greet():
print("Hello!") greet()

def greet2(name, num_times):


for i in range(num_times):
print("Hello", name) greet2("Bob", 10)
Why use functions?
– Chop a program into manageable pieces
• “divide and conquer”
– Match our understanding of the problem domain
• Name logical operations
• (A function should do one thing well)
– Functions make the program easier to read
– A function can be useful in many places in a program
(reusability)
– Ease testing, distribution of labour, and maintenance
– Abstraction (hide internal details)
Properties of functions
• Function definitions can be put into the same file (or
different files)
• Functions must be defined before they are used
• Once the function returns, the variables in the
parameter list and any other variables that it declares
are lost.
• Functions can call other functions.
• If function does not return anything, it is called a void
function
• If a function has no input parameters, leave brackets
empty e.g. def greet():
Function Declarations
def show_message(x, y):
m = int(input()) for i in range(x):
n = int(input()) for j in range(y):
show_message(m, n) print("*", end="")
print()
def show_message(x, y):
for i in range(x):
m = int(input())
for j in range(y): n = int(input())
print("*", end="") show_message(m, n)
print()

"""
Traceback (most recent call last):
File "main.py", line 5, in <module>
show_message(m, n)
NameError: name 'show_message' is not defined
"""
Function Return
• Functions can return in 3 ways
– Executing all the statements in the function body
(for void functions)
– Running into the statement return (for void
functions)
– Running into the statement return <exp>;
• non- void functions must return like this
Examples
# we run into the end of the function and exit
def f():
print("Hello, world!")
# returns here

# early return from void function


def g(x, y):

if y == 0:
print("y can't be 0")
return # returns here

print("Calculating...")
z = (x * x + y * y) / y;
print("The answer is", z)

# return from non-void


def h(firstName, surname){

if firstName == "" or surname == "":


return "Default Name" # returns here

return firstName + " " + surname # returns here


Function Return
• In Python, we can return as many values as we
want
– In other languages (like C++), we can only return one
value
def get_position_of_robot():
# get the xy position of a robot
# ... do calculations
x = ...
y = ...
return x, y

• Good practice:
– Functions should only return one logical thing

You might also like