0% found this document useful (0 votes)
1 views

Unit03 Algorithm 1

lecture for algorithm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Unit03 Algorithm 1

lecture for algorithm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Algorithmic Thinking:

Loops and Conditionals


Last Time

 A control flow structure: for loop

 range(n)
range(start, end)
range(start, end, step)

 Assignments that modify variables:


x = x + y
Iteration with for loops
def test1(): What determines how many
for i in range(1,6): times “Woof” is printed is the
print("Woof") number of elements in the
range.
>>> test1()
Woof Any expression that gives 5
Woof elements in the range would
Woof give the same output.
Woof
Woof For example,
range(5), range(0,5), …
Iteration with for loops

def test2(): range(5) ?


for i in range(1,6): range(0, 5) ?
print(i, end='-') range(1, 6) ?

>>> test2() range(1, 10, 2) ?


1-2-3-4-5- range(2, 10, 2) ?

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

 The notion of an algorithm

 Moving from algorithm to code

 Python control structures:


 While loops, conditionals
Algorithms

• An algorithm is “a precise rule (or set of rules)


specifying how to solve some problem.”
(thefreedictionary.com)

• The study of algorithms is one of the


foundations of computer science.
image: AL-KHWARIZMI
historyoflinearalgebra.weebly.com

 New concept: algorithm

 New control structures


 While loops
 Conditionals
Mohammed al-Khowarizmi (äl-khōwärēz´mē)
Persian mathematician of the court of Mamun in Baghdad…
the word algorithm is said to have been derived from his name.
Much of the mathematical knowledge of medieval Europe was
derived from Latin translations of his works. (encyclopedia.com)
15110 Principles of Computing, Carnegie
Mellon University 8
An algorithm is like a function

F(x) = y

INPUT ALGORITHM OUTPUT

9
Input

• Input specification
• Recipes: ingredients, cooking utensils, …
• Knitting: size of garment, length of yarn, needles …
• Tax Code: wages, interest, tax withheld, …

• Input specification for computational algorithms:


• What kind of data is required?
• In what form will this data be received by the
algorithm?

10
Computation

• An algorithm requires clear and precisely stated


steps that express how to perform the
operations to yield the desired results.

• Algorithms assume a basic set of primitive


operations that are assumed to be understood
by the executor of the algorithm.
• Recipes: beat, stir, blend, bake, …
• Knitting: casting on, slip loop, draw yarn through, ...
• Tax code: deduct, look up, check box, …
• Computational: add, set, modulo, output, …

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

• Output specification for computational algorithms:


• What results are required?
• How should these results be reported?
• What happens if no results can be computed due to
an error in the input? What do we output to indicate
this?

12
Is this a “good” algorithm?

Input: slices of bread, jar of peanut butter, jar of jelly

1. Pick up some bread.


2. Put peanut butter on the bread.
3. Pick up some more bread.
4. Open the jar of jelly.
5. Spread the jelly on the bread.
6. Put the bread together to make your sandwich.

Output?

13
What makes a “good” algorithm?

• A good algorithm should produce the


correct outputs for any set of legal inputs.

• A good algorithm should execute efficiently


with the fewest number of steps as possible.

• A good algorithm should be designed in


such a way that others will be able to
understand it and modify it to specify
solutions to additional problems.
14
An epidemic (covered last week)
def compute_sick(numOfDays):
#computes total sick after n days
newly_sick = 1 #initially 1 sick person
total_sick = 1

for day in range(2, numOfDays + 1):


#each iteration represents one day
newly_sick = newly_sick * 2
total_sick = total_sick + newly_sick

return total_sick

Each newly infected person infects 2 people the next day.


The function returns the number of sick people after n days.

15
Variation on the Epidemic Example

Let us write a function that


 Inputs the size of the population
 Outputs the number of days left before all the population
dies out

How can we do that using iteration (loops)?

Keep track of the number of sick people.

But do we know how many times we should loop?


Recall the Epidemic Example
def days_left(population):
#computes the number of days until extinction
days = 1
newly_sick = 1
total_sick = 1
while total_sick < population:
#each iteration represents one day
newly_sick = newly_sick * 2
total_sick = total_sick + newly_sick
days = days + 1
print(days, " days for the population to die off")
return days

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

What is the output? How about this?


i = 1 i = 0
while i < 6: while i < 5:
print(i, end=' ') i = i + 1
i = i + 1 print(i , end=' ')
print('\n After :', i) print('\n After :', i)

‘\n’ means new line

What is the value of i when we exit the loop?

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

# Prints first 10 positive integers # Prints first 10 positive integers

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

 If you know in advance how many times you want to run


a loop use a for loop.

 When you don’t know the number of repetition needed,


use a while loop.
A Simple Algorithm
Input numerical score between 0 and 100 and
Output “Pass” or “Fail”

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

set grade to “Pass” set grade to “Fail”


print “Pass” print “ Fail”

print(“See you in class”)


return grade

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

true score >= 80


set grade to “A” false
print “you got an A”
true false
score >= 70
set grade to “B”
print “you got a B”

set grade to “C” set grade to “D or lower”


print “you got a C” print “your grade is less than C”

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

How do we find the maximum in a sequence of integers


shown to us one at a time?

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

Example: Finding the maximum

How do we find the maximum in a sequence of integers


shown to us one at a time?

175 203 109 158 138 246

146 265 152 222 307 299

What’s the maximum?

34
Example: Finding the maximum

Input: a non-empty list of integers.

1. Set max_so_far to the first number in list.


2. For each number n in list:
a. If n is greater than max_so_far, Loop
then set max_so_far to n.

Output: max_so_far as the maximum of the list.

35
Until Now

 Notion of an algorithm:
 Kinds of instructions needed to express algorithms
 What makes an algorithm a good one

 Instructions for specifying control flow (for loop, while


loop, if/then/else)
 Flow charts to express control flow in a language-
independent way
 Coding these control flow structures in Python

36
Representing Lists in Python

We will use a list to represent a collection of


data values.
scores = [78, 93, 80, 68, 100, 94, 85]
colors = [‘red’, ‘green’, ‘blue’]
mixed = [‘purple’, 100, 90.5]

A list is an ordered sequence of values and


may contain values of any data type.

In Python lists may be heterogeneous


(may contain items of different data types).
37
Some List Operations

 Indexing (think of subscripts in a sequence)

 Length (number of items contained in the list)

 Slicing

 Membership check

 Concatenation

 …

38
Some List Operations

>>> names = [ "Al", "Jane", "Jill", "Mark" ]


>>> len(names)
4
>>> Al in names
Error ... name 'Al' is not defined
>>> "Al" in names
True
>>> names + names
['Al', 'Jane', 'Jill', 'Mark', 'Al', 'Jane', 'Jill', 'Mark']

39
Accessing List Elements

names "Al" "Jane" "Jill" "Mark" list elements

0 1 2 3
indices

>>> names[0] >>> names[3]


'Al‘ 'Mark‘

>>> 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

>>> names[1:3] slice


['Jane', 'Jill']
Start

>>> names[0:4:2] incremental slice


[‘Al', 'Jill']
Step

End
Slicing Lists
names "Al" "Jane" "Jill" "Mark"
list elements

0 1 2 3 indices

names, names[0:4], names[0,4,1]


They all refer to ['Al', 'Jane', 'Jill‘, ‘Mark']

>>> names[1:3] ['Jane', 'Jill']


>>> names[1:4] ['Jane', 'Jill‘, ‘Mark']

>>> names[0:4:2] [‘Al', 'Jill']


>>> names[:3] ['Al', 'Jane', 'Jill‘]

>>> names[:2] ['Al', 'Jane']


>>> names[2:] ['Jill', 'Mark']
source: docs.python.org
43
Modifying Lists
>>> names = ['Al', 'Jane', 'Jill', 'Mark']
>>> names[1] = "Kate"
>>> names >>> a = [1, 2, 3]
['Al', 'Kate', 'Jill', 'Mark'] >>> a[0:0] = [-2, -1, 0]
>>> a
[-2, -1, 0, 1, 2, 3]

>>> names[1:3] = [ "Me", "You" ] >>> a = [1, 2, 3]


>>> names >>> a[0:1] = [-2, -1, 0]
['Al', 'Me', 'You', 'Mark'] >>> a
[-2, -1, 0, 2, 3]

>>> names[1:3] = [ "AA", "BB", "CC", "DD" ]


['Al', 'AA', 'BB', 'CC', 'DD', 'Mark']

The list grew in length, we could make it shrink as well.


44
source: docs.python.org
45
Tomorrow

 We will continue Lists and algorithms

You might also like