Unit03 Algorithm 1
Unit03 Algorithm 1
range(n)
range(start, end)
range(start, end, step)
range(10, 1, -1) ?
range(10, 2, -4) ?
Iteration with for loops
def test3():
for i in range(1,6): This expression creates a string
print("Woof" * i) that concatenates i number
of “Woof”s.
>>> test3()
Woof
WoofWoof
WoofWoofWoof
WoofWoofWoofWoof
WoofWoofWoofWoofWoof
This Lecture
F(x) = y
9
Input
• Input specification
• Recipes: ingredients, cooking utensils, …
• Knitting: size of garment, length of yarn, needles …
• Tax Code: wages, interest, tax withheld, …
10
Computation
11
Output
• Output specification
• Recipes: number of servings, how to serve
• Knitting: final garment shape
• Tax Code: tax due or tax refund, where to pay
12
Is this a “good” algorithm?
Output?
13
What makes a “good” algorithm?
return total_sick
15
Variation on the Epidemic Example
17
while loop
Format:
while condition:
loop body false
condition
loop body
true
one or more instructions
to be repeated
loop body
After the loop condition becomes false
during the loop body, the loop body
still runs to completion (before its check
before the next turn) and exit the loop
and go on with the next step.
18
Recall the Epidemic Example
def days_left(population):
#computes the number of days until extinction
days = 1
newly_sick = 1
Loop condition
total_sick = 1
while total_sick < population: Should be
#each iteration represents one day changing so
newly_sick = newly_sick * 2 that loop will
total_sick = total_sick + newly_sick end at a point
days = days + 1
print(days, " days for the population to die off")
return days
19
While Loop Examples
20
While Loop Examples
i = 1
while i < 6: >>>
print(i, end=' ')
1 2 3 4 5
i = i + 1
print('\n', 'After :',i) After : 6
print('-------------'); -------------
i = 0 1 2 3 4 5
while i < 5:
After : 5
i = i + 1
print(i , end=' ') >>>
print('\n After :', i)
21
While vs. For Loops
i = 1 for i in range(1,11):
while i < 11: print(i)
print(i)
i = i + 1
22
When to use for or while loops
Algorithm:
1. If score >= 60 Exactly one of the steps 1 or 2
a. Set grade to “Pass” is executed, but step 3 and
b. Print “Pass” step 4 are always executed.
2. Otherwise,
a. Set grade to “Fail”
b. Print “Fail”
3. Print “See you in class”
4. Return grade
Coding the Grader in Python
def grader(score):
Algorithm:
if score >= 60:
1. If score >= 60
grade = "Pass"
a. Set grade to “Pass”
print("!!!Pass")
b. Print “ Pass”
else:
2. Otherwise,
grade = "Fail"
a. Set grade to “Fail”
print("!!!Fail")
b. Print “Fai”
print("See you in class")
3. Print “See you in class ”
return grade
4. Return grade
Control Flow
true false
score >= 60
26
FLOW CHART: if statement
Format:
if condition : false
statement_list condition
true
statements
27
FLOW CHART: if/else statement
true false
Format: condition
statement_list1 statement_list2
if condition :
statement_list1
else:
statement_list2
28
Grader for Letter Grades
true false
score >= 90
29
Nested if statements
def grader2(score):
if score >= 90:
grade = "A"
print("You got an A")
else: # score less than 90
if score >= 80:
grade = "B"
print("You got a B")
else: # score less than 80
if score >= 70:
grade = "C"
print("You got a C")
else: #score less than 70
grade = "D or lower"
print("Your grade is less than C")
return grade
30
Equivalently
def grader3(score):
if score >= 90:
grade = "A"
print("You got an A")
elif score >= 80:
grade = "B"
print("You got a B")
elif score >= 70:
grade = "C"
print("You got a C")
else:
grade = "D or lower"
print("Your grade is less than C")
return grade
31
Flow chart:
if/elif/else statement
true false
Format: condition1
if condition1:
statement_list1
statement_list1
elif condition2 : false
true
statement_list2 condition2
else:
statement_list3 statement_list2
statement_list3
32
Example: Finding the maximum
299
307
222
152
265
146
246
138
158
109
203
175
What’s the maximum?
33
This slide is added just for the lecture notes in PDF.
Same with the previous slide which animates the list of numbers
34
Example: Finding the maximum
35
Until Now
Notion of an algorithm:
Kinds of instructions needed to express algorithms
What makes an algorithm a good one
36
Representing Lists in Python
Slicing
Membership check
Concatenation
…
38
Some List Operations
39
Accessing List Elements
0 1 2 3
indices
>>> names[len(names)-1]
'Mark'
>>> names[4]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
names[4]
IndexError: list index out of range
Slicing Lists
names "Al" "Jane" "Jill" "Mark"
list elements
0 1 2 3 indices
End
Slicing Lists
names "Al" "Jane" "Jill" "Mark"
list elements
0 1 2 3 indices