QUIZ on Ch.6: Write the pseudocode for adding two … the pseudocode for adding two numbers...

69
QUIZ on Ch.6: Write the pseudocode for adding two numbers together; our target language is PEP/8 assembly. 1

Transcript of QUIZ on Ch.6: Write the pseudocode for adding two … the pseudocode for adding two numbers...

QUIZ on Ch.6:

Write the pseudocode for adding two numbers together; our target language is PEP/8 assembly.

1

2

•Input the first number - into memory location "A"

•Input the second number - into memory location "B"

•Load A from memory into Accumulator reg.

•Add B from memory; result goes into Accumulator reg.

•Store the AC into memory location "C"

•Output the value in memory location "C"

Solution

For more practice: Write the assembly code!

QUIZ on Ch.6:

Write a PEP assembly program that reads in a character, and then outputs ‘A’ if the character was A, nothing otherwise.

3

What is the hex ASCII code for A?

Use this code as template:

Problem Solving

How to Solve It: A New Aspect of Mathematical Method by George Polya, 1945

The book is written within the context of solving mathematical problems, but the methods described are applicable to problem solving in general.

5

We can use the methods described

by Polya to solve any computer-

related problem!

1. Understand the problem

– What are the hypotheses? Data? Unknowns?

2. Devise a plan

– Can we find a related problem? A sub-problem?

– Can we strengthen or relax the hypotheses to obtain an easier problem?

3. Carry out the plan

— Prove that each step is correct!

4. Look back

– Check result

– Find shortcuts and alternate solutions

– Generalize to related problems6

Strategies

Don’t reinvent the wheel!

Similar problems come up again and again in different guises.

A good programmer recognizes a task or subtask that has been solved before and reuses the solution.

Can you think of two similar problems we solved in Python?

7

StrategiesDivide and Conquer!

Break up a large problem into smaller sub-problems and solve each separately

– Applies the concept of abstraction

– The divide-and-conquer approach can be applied over and over again until each subtask is manageable

8

Polya’s 4 steps can be applied to Computer Problem Solving

9

Analysis and Specification Phase

Ask questions to understand all the requirements

Explain in detail what needs to be achieved

Algorithm Development Phase

Develop algorithm

Test algorithm

Implementation Phase

Code algorithm

Test the code in various ways

Maintenance Phase

Use the code, find bugs

Fix bugs

Code new features, as requested by users

QUIZ: Match the steps in Polya’s method to the ones in the computer method for

problem solving

10

Analysis and Specification

Implementation

Algorithm Development

Maintenance

Devise a plan

Look back

Understand

Carry out the plan

Phase Interactions

11

Algorithms

Algorithm = A set of unambiguous instructions for solving a problem in a finite amount of time, using a finite amount of resources

12

Algorithm = A set of unambiguous instructions for solving a problem in a finite amount of time, using a finite amount of data

13Image source: http://my-online-log.com/tech/archives/1214

Algorithm = A set of unambiguous instructions for solving a problem in a finite amount of time, using a finite amount of data

Abstract Step

An algorithmic step containing unspecified details

Concrete Step

An algorithm step in which all details are specified

14

Whether the step is abstract or concrete depends on the

programming language we’re using!

7.2 Algorithms with simple variables

Variable = a means of storing intermediate results from one task to the next.

At the hardware level, a simple variable is just one or several adjacent Bytes in the computer memory.

Q: How many Bytes does a simple variable have in PEP/8?

15

QUIZ

We have two variables a and b.

Create an algorithm to swap their values!

16

What is wrong with this

algorithm?

a = b

b = a

17

save = a

a = b

b = save

Solution

Source: AP CS Principles – Course and Exam Descriptions

Similar problem (Don’t reinvent the wheel!)

Algorithms with Selection Statements (a.k.a. decision or if)

19

Flowchart of if statement

Figure is not in text

20

Algorithm with Selection

Problem: Write the appropriate dress for a given

temperature.

Write "Enter temperature"

Read temperature

Determine Dress

Which statements are concrete?

Which statements are abstract?

Algorithm Determine Dress v.1

Computer language is Python from now on!

21

Write “Enter temperature”

Read temperature

IF (temperature > 90)

Write “Texas weather: wear shorts”

ELSE IF (temperature > 70)

Write “Ideal weather: short sleeves are fine”

ELSE IF (temperature > 50)

Write “A little chilly: wear a light jacket”

ELSE IF (temperature > 32)

Write “Philadelphia weather: wear a heavy coat”

ELSE

Write “Stay inside”

Algorithm Determine Dress v.2

Is this concrete enough for implementation in Python?

Algorithms with Loops (a.k.a. repetition)

22

Flow of control of while statement

Figure is not in text

QUIZ: There are loops that can execute 0 times and loops that must execute at least 1 time.Which type is this?

23

Answer: It depends on whether the decision (diamond) is at the beginning or at the end of the loop!

24

Figure is not in text

Loops in Python

25

Not in text

Extra-credit question:

26

Event-controlled Loops, a.k.a. WHILE loops

27

They’re the most general type of loops!

Set sum to 0

Set allPositive to true

WHILE (allPositive)

Read number

IF (number > 0)

Set sum to sum + number

ELSE

Set allPositive to false

Write "Sum is " + sum

Counter-controlled Loops

28

They are a particular case of event-controlled

loops: the event is that a counter variable has

reached a predetermined limit

Set sum to 0

Set limit to 42

Set count to 1

While (count <= limit)

Read number

Set sum to sum + number

Increment count

Write "Sum is " + sum

Counter-controlled Loops

29

They are a particular case of event-controlled

loops: the event is that a counter variable has

reached a predetermined limit

Set sum to 0

Set limit to 42

Set count to 1

While (count <= limit)

Read number

Set sum to sum + number

Increment count

Write "Sum is " + sum

For loops are counter-

controlled!

EOL1

30

Important application of looping: Successive approximation

algorithms

Read in square

Calculate the square root

Write out square and the square root

Algorithm Calculate Square Root v.1

Which steps are abstract and which concrete?

31

Set epsilon to 1

WHILE (epsilon > 0.001)

Calculate new guess

Set epsilon to abs(square - guess * guess)

Which steps are abstract and which concrete?

Algorithm Calculate Square Root v.2

In Python usemath.fabs(…)

A more appropriate name for guess would be approximation

32

Set newGuess to

(guess + (square/guess)) / 2.0

Set guess to square/4

Set epsilon to 1

What’s the mathematical formula for the new approximation?

How do we get the loop started?

Algorithm Calculate Square Root - Refinements in v.2

33

Read in square

Set guess to square/4

Set epsilon to 1

WHILE (epsilon > 0.001)

Set guess to (guess + (square/guess)) / 2.0

Set epsilon to abs(square - guess * guess)

Write out square and guess

Which steps are abstract and which concrete?

Algorithm Calculate Square Root v.3

34

Set newGuess to

(guess + (square/guess)) / 2.0

QUIZ: Square root approximation alg.

We want to calculate = 2.236…

Set your initial guess x0 = 1 and show the

next 3 approximations x1, x2, x3

5

35

Solution

We want to calculate = 2.236…5

36

Set newGuess to

(guess + (square/guess)) / 2.0

To do in notebook:

We want to calculate = 2.236…

Set your initial guess x0 = 42 and show the

next 3 approximations x1, x2, x3

5

37

QUIZ: Square root algorithm

We want to calculate = 2.6457…

Set your initial guess to x0 = 7/4 = 1.75

and show the next 3 approximations x1, x2, x3

7

38

QUIZ: Square root algorithm

We want to calculate = 2.645751…7

39

Remember: The

algorithm converges

irrespective of the

initial guess x0!

= 2.645751…7

40

QUIZ:

Re-write this program

using a for loop!

QUIZ:

Re-write this program

using a for loop!

Individual work for

next time:

Re-write this program

using a while loop!

QUIZ True/False

• Count-controlled loops repeat a specific number of times.

• Event-controlled loops repeat a specific number of times

• Count-controlled loops are controlled by a counter

• Count-controlled loops are more general than event-controlled loops

43

44

Set newGuess to

(guess + (square/guess)) / 2.0

QUIZ: Square root algorithms

(approximations)

We want to calculate = 3.162…

Set your initial guess x0 = 10/4 and show

the next 3 approximations x1, x2, x3

10

Set newGuess to

(guess + (square/guess)) / 2.0

QUIZ: Square root algorithms

(approximations)

We want to calculate = 3.16227…

Set your initial guess x0 = 10/4 and show

the next 3 approximations x1, x2, x3

10

x0 = 2.5 x1 = 3.25 x2 = 3.16346… x3 = 3.16227…

7.3 Composite Data Types

They can be classified according to many criteria:

• homogeneous vs. heterogeneous

• accessed by index vs. accessed by name

• mutable vs. immutable

• linear vs. non-linear

• etc.

46

Composite Data Types

Records

A named heterogeneous collection of items in which individual items are accessed by name. For example, we could bundle name, age and hourly wage items into a record named Employee

Arrays

A named homogeneous collection of items in which an individual item is accessed by its position (index) within the collection

47

Are these the lists from Python? Why not?

Python strings are arrays of charactersCan implement in Python w/lists …

Composite Data Types

Lists (will be covered in next chapter)

A named heterogeneous collection of items in which individual items are accessed by position (index).

We have them in Python, e.g.

>>> myList = [“dog”, 42, 51.375, [1,2]]

>>> myList[1]

42

48

Composite Data Types - Records

Employee

name

age

hourly/Wage

Algorithm to store values into the fields of record:

Employee employee // Declare an Employee variableSet employee.name to “Frank Jones”Set employee.age to 32Set employee.hourlyWage to 27.50

49

Composite Data Types - Arrays

50

numbers[0]

numbers[4]

numbers

Some items in an array may be unused at a given time

51

first

last

numbers

??

??

??

??

Useful Algorithms on Arrays

• Initializing all items

• Printing all items

• Searching for an item

• Sorting the array

52

53

Initializing arrays

integer data[20]

Write “How many values?”

Read length

Set index to 0

WHILE (index < length)

Read data[index]

Set index to index + 1

Fill an array numbers with length values

that are being input from the keyboard

54

QUIZ

integer data[20]

Write “How many values?”

Read length

Set index to 0

WHILE (index < length)

Read data[index]

Set index to index + 1

Modify this pseudocode to print the values

after initializing them.

An Unsorted Array

55

data

A Sorted Array

56

data

Sorted Arrays

• The values stored in an array have unique keysof a type for which the relational operators are defined.

• Sorting rearranges the elements into either ascending or descending order within the array.

57

Reality check: In a real-life problem it’s very common

to encounter repeated keys!

7.4 Search algorithms

58

Sequential Search inUnsorted Array

A sequential search examines each item in turn and compares it to the one we are searching.

If it matches, we have found the item. If not, we look at the next item in the array.

We stop either when we have found the item or when we have looked at all the items and not found a match.

Thus, we have a loop with two ending conditions.

59

Set position to 0

Set found to FALSE

WHILE (position < length AND NOT found )

IF (numbers[position] equals searchItem)

Set found to TRUE

ELSE

Set position to position + 1

60

The array’s name is numbersThe value we’re searching for is stored in searchItem

Set position to 0

Set found to FALSE

WHILE (position < length AND NOT found )

IF (numbers[position] equals searchItem)

Set found to TRUE

ELSE

Set position to position + 1

61

QUIZ: When the loop exits, what do we need to do?

Set index to 0

Set found to FALSE

WHILE (index < length AND NOT found )

IF (data[index] equals searchItem)

Set found to TRUE

ELSE

Set index to index + 1

62

QUIZ: Desk-check this algorithm for the array

The item searched is:

• 35

• 43

42

100

35

1

Sequential Search in Sorted Array

Idea:

If items in an array are sorted, we can stop looking when we pass the place where the item would be if it were present in the array

63

Is this better?

64

Sequential Search in Sorted Array

Set index to 0

Set found to FALSE

WHILE (index < length AND NOT found)

IF (data[index] equals searchItem)

Set found to TRUE

ELSE IF (data[index] > searchItem)

Set index to length

ELSE

Set index to index + 1

This is the new part!

(Compare with previous alg. for unsorted array)

This alg. is called sequential search with early termination

QUIZ:End-of-chapter question 66 a

65

SearchItem = 4

SearchItem = 49

SearchItem = 50

Binary Search in Sorted Array

Search begins at the middle and finds the item or eliminates half of the unexamined items; the process is then repeated on the half where the item might be

66

24 30 31 42 44 90 92 94 99

Example: searchItem = 42

Binary Search Algorithm

67

Set first to 0

Set last to length-1

Set found to FALSE

WHILE (first <= last AND NOT found)

Set middle to (first + last)/ 2

IF (item equals data[middle]))

Set found to TRUE

ELSE

IF (item < data[middle])

Set last to middle – 1

ELSE

Set first to middle + 1

RETURN found

IntegerDivision!

Binary Search example

68Figure 7.10 Trace of the binary search

rat

QUIZ Binary Search

69

Search for deer

EOL 3