Download presentation

Presentation is loading. Please wait.

Published byBarry Dooling Modified about 1 year ago

1
Queensland University of Technology CRICOS No J ITB001 Problem Solving and Programming Lecture 4 Faculty of Information Technology Queensland University of Technology

2
CRICOS No J a university for the world real R 2 Aims of this lecture Last week we saw how parameterised procedures allow us to reuse solutions We look now at how to break a large problem down so that it can be solved by repeated application of small steps

3
CRICOS No J a university for the world real R 3 References Concrete Abstractions: An Introduction to Computer Science Using Scheme, Sections 2.1–2.3 Structure and Interpretation of Computer Programs, Sections 1.1.7–1.1.8, and 1.2

4
CRICOS No J a university for the world real R 4 An illustration How can we make a paper chain with n links? 1.Line up at least n people 2.Ask the person on the end for a chain of length n 3.For each person who is asked for a chain of length i, where i exceeds 1: a.Ask the next person for a chain of length i 1 b.When the chain is returned, add one link to it and give it to the person who asked 4.If asked for a chain of length 1, create a single link

5
CRICOS No J a university for the world real R 5 What happened? Each person had to join one link only Each person did exactly the same thing (except the person who created the single link) When asked to make a chain, each person first got someone else to do most of the work (except the person who created the single link) We took a problem of size n and broke it into n problems of size 1

6
CRICOS No J a university for the world real R 6 The recursion strategy This is an example of a powerful problem-solving strategy: Do nearly all the work first, then do the little bit that’s left over

7
CRICOS No J a university for the world real R 7 A simple example of problem solving using the recursion strategy In last week’s exercises you wrote a small procedure called gst to calculate the Goods and Services Tax paid on a given price –Example: (gst 110) returns 10 Now imagine that you have been asked to write a procedure called total-gst to calculate the total tax paid on a list of prices –Example: (total-gst (list )) should return 20

8
CRICOS No J a university for the world real R 8 Total GST: Analysing the problem Before attempting to solve the problem, we should summarise what we know: –We know that the desired result is the sum of the taxes paid on each item in the given list –We know how to extract the first item in a list (using first) and get the remaining items (using rest) –We already have a procedure, gst, capable of calculating the tax for a single item We should also consider some ‘extreme’ examples, such as what result to return if given an empty list

9
CRICOS No J a university for the world real R 9 Total GST: Designing a solution One way to solve this problem (but not the only one) is to calculate the tax paid for each item in the list and sum the results –To express this solution recursively, consider that the desired result is the tax paid on the first item in the list plus the total tax paid for all the remaining items –In other words, if we already know the total tax paid for all items in the list except the first, then all we need to do is calculate the tax for the first item and add it

10
CRICOS No J a university for the world real R 10 Total GST: Designing a solution Action refinement: 1. Return the sum of the tax paid for a list of items 1.1 If the list is empty return zero (Base Case) 1.2 Otherwise return the tax paid for the first item in the list added to the tax paid for the rest of the items (Recursive Case)

11
CRICOS No J a university for the world real R 11 Total GST: Implementation The following Scheme procedure calculates taxes using this recursive strategy: ; Sums the tax paid for a list of items (define [total-gst prices] ; If the list is empty return zero (if (empty? prices) 0 ; Add the tax paid for the first item to ; the tax paid for the rest of the items (+ (gst (first prices)) (total-gst (rest prices))))) Example: –(total-gst (list )) returns 3

12
CRICOS No J a university for the world real R 12 The process for calculating taxes The main steps in calculating the total tax paid on two items costing $22 and $55 are as follows: 1.(total-gst (list 22 55)) 2.(+ 2 (total-gst (list 55))) 3.(+ 2 (+ 5 (total-gst (list)))) 4.(+ 2 (+ 5 0)) 5.(+ 2 5) 6.7

13
CRICOS No J a university for the world real R 13 Calculating factorials As another example of the recursive problem-solving strategy, consider calculating factorials, written ‘n!’ The number of ways that n objects can be arranged is: n! n (n 1) 1 By definition 0! 1 because zero objects can be arranged in one way only

14
CRICOS No J a university for the world real R 14 Calculating factorials For example, 3 objects can be arranged in 3 2 1 6 ways But notice that 4 objects can be arranged in 4 3 2 1 24 ways, which is equal to 4 3! In general, therefore, if asked to calculate n! we can solve the problem by getting someone else to calculate (n 1)! and by then multiplying this by n If asked to calculate 0! we just return 1

15
CRICOS No J a university for the world real R 15 Calculating factorials The following Scheme procedure calculates factorials using this recursive strategy: (define [factorial n] (if (zero? n) 1 (* n (factorial (- n 1))))) Example: –(factorial 3) returns 6

16
CRICOS No J a university for the world real R 16 The process for calculating factorials The main steps in calculating 3! are as follows: 1.(factorial 3) 2.(* 3 (factorial 2)) 3.(* 3 (* 2 (factorial 1))) 4.(* 3 (* 2 (* 1 (factorial 0)))) 5.(* 3 (* 2 (* 1 1))) 6.(* 3 (* 2 1)) 7.(* 3 2) 8.6

17
CRICOS No J a university for the world real R 17 Procedures and the processes they generate The form of a recursive procedure influences the efficiency of the corresponding computational process –When making paper chains, we had to wait until our neighbours had produced their part before we could add a link –When calculating taxes we had to wait until the subtotal for all other items was calculated before adding the tax on the first item –In the factorial process each multiplication is deferred until the recursive procedure application returns

18
CRICOS No J a university for the world real R 18 Base cases Observations: –When making paper chains, the person who created a single link behaved differently than everyone else –When calculating taxes we just returned zero if given an empty list of prices –In the factorial procedure, no multiplication was needed to calculate 0! (which equals 1 by convention) These are called the base cases of our solution

19
CRICOS No J a university for the world real R 19 Recursive cases Observations: –When making paper chains, everyone except the ‘base case’ person added a link to an existing chain –When calculating taxes, we applied the gst procedure to each price in the list –When calculating factorials, every number except for the base case was multiplied by another number These are called the recursive cases of our solution

20
CRICOS No J a university for the world real R 20 Designing recursive solutions Each recursive case should ‘break off’ a piece of the given problem, to create a subproblem that has the same form as the original problem –This ensures that the recursive procedure can make use of itself –When asked to make a paper chain, each person (except the last) asked their neighbour to also make a (shorter) chain –When calculating the total tax, we made use of a subtotal

21
CRICOS No J a university for the world real R 21 Designing recursive solutions Each recursive case should create a subproblem that is closer to the base case than the given problem –This ensures that the recursive procedure eventually terminates –When calculating the tax for a list, we first found the subtotal for a shorter list, stopping when the list was empty –When calculating n!, the factorial procedure’s recursive case decremented n, taking it closer to the base case of zero

22
CRICOS No J a university for the world real R 22 Exercise 4-1: Multiplication by repeated addition Define a procedure called mult which accepts two non- negative numbers m and n and returns the value m n Challenge: You may use the pre-defined addition procedure ‘+’ but not the multiplication procedure ‘*’ Hints: –Consider changing parameter n in each recursive step –What is the base case value of n? –What do you need to do in each recursive step?

23
CRICOS No J a university for the world real R 23 Recursive definitions in mathematics Recursively-defined procedures express computations in the same way as in mathematics The following mathematical definition of factorials has a base case and a recursive case, just like our procedure 1, if n 0 n (n 1)!, otherwise n!

24
CRICOS No J a university for the world real R 24 “Like a circle in a spiral, Like a wheel within a wheel” But isn’t this definition circular? No, it spirals towards the base case –Each recursive step ‘breaks off’ a piece of the problem until only the base case is left Truly circular definitions don’t help us find solutions n! = n!

25
CRICOS No J a university for the world real R 25 Multiple base and recursive cases To solve more complicated problems, we may need more than just one base case and one recursive case Multiple base cases allow the computation to terminate in different ways Multiple recursive cases allow us to do different things at each step

26
CRICOS No J a university for the world real R 26 Exercise 4-2: Number of occurrences of an item in a list Write a recursive procedure called how-often with two parameters, a list items and a particular item x, which returns the number of occurrences of x in items Hint: You may need more than one recursive case Example: –(how-often (list ) 2) returns 3

27
CRICOS No J a university for the world real R 27 “My head’s spinning” Trying to think about how a recursive procedure is evaluated is confusing Instead, consider just one layer of evaluation For other layers use ‘wishful thinking’ and assume they work as required –Since every layer is the same, this is sufficient to show that your solution is correct –(This is the basis of inductive proofs in mathematics)

28
CRICOS No J a university for the world real R 28 Wishful thinking For instance, to understand the factorial procedure, just assume that the recursive application ‘(factorial (- n 1))’ returns the desired value (n 1)! (define [factorial n] (if (zero? n) 1 (* n (n 1)!))) Now we can easily see that this procedure returns 1 if parameter n is zero and otherwise returns n (n 1)! which is n!, as desired This is not a legal Scheme expression

29
CRICOS No J a university for the world real R 29 Deciding how big a step to take So far it has been obvious what constitutes a ‘step’ required to solve a problem –For constructing paper chains it was sensible to make ‘add one link’ a single step –For calculating total GST it was easiest to calculate the tax on one price at a time –For calculating factorials it seemed reasonable to decrease the number by one at each step But for some problems the hard part is deciding how to take a step

30
CRICOS No J a university for the world real R 30 Exercise 4-3: Number of digits Define a procedure called num-digits which, given a non- negative number n, returns the number of digits in n Hint: You will need to use the pre-defined integer division procedure quotient to make progress towards the base case, e.g., (quotient ) returns 48 Examples: –(num-digits 487) returns 3 –(num-digits 6549) returns 4

31
CRICOS No J a university for the world real R 31 Exercise 4-3: Number of digits Extra challenge: Make your procedure work for negative numbers too

32
CRICOS No J a university for the world real R 32 Advanced topic: Tree recursion So far, all of our solutions have required only one recursive step at a time However, some problems require more than one recursive procedure application at each step This is known as tree recursion, due to the shape of the process it generates –Such processes are typically very inefficient

33
CRICOS No J a university for the world real R 33 Fibonacci numbers Fibonacci numbers model population growth in societies where deaths are rare (e.g., in bacterial colonies) They consist of the following sequence in which each number is the sum of its two predecessors 0, 1, 1, 2, 3, 5, 8, 13, 21, … The n th Fibonacci number can be expressed by: 0, if n 0 1, if n 1 F n - 1 F n - 2, otherwise Fn Fn

34
CRICOS No J a university for the world real R 34 Exercise 4-4: Fibonacci numbers Fill in the blanks to create a procedure for calculating the n th (counting from zero) Fibonacci number: (define [fib n] (cond [(…) 0] [(…) 1] [else (+ (…) (…))])) Examples: – (fib 7) returns 13 – (fib 8) returns 21 – Try some bigger arguments—what happens?

35
CRICOS No J a university for the world real R 35 Further Exercises

36
CRICOS No J a university for the world real R 36 Exercise 4-5: The Twelve Days of Christmas On the first day of Christmas, My true love gave to me, A partridge in a pear tree. On the second day of Christmas, My true love gave to me, Two turtle doves, And a partridge in a pear tree. On the third day of Christmas, My true love gave to me, Three French hens, Two turtle doves, And a partridge in a pear tree. Etcetera, ad nauseam!

37
CRICOS No J a university for the world real R 37 Exercise 4-5: The Twelve Days of Christmas 1.Define a procedure presents-on-day which, given a number n, returns the number of presents my true love gave me on the n th day of Christmas 2.Use your procedure presents-on-day to define a procedure presents-upto-day which returns the total number of presents my true love gave me up until a given day 3.Use your procedure presents-upto-day to find out how many presents I got over Christmas

38
CRICOS No J a university for the world real R 38 Exercise 4-6: Permutations The number of ways m objects can be arranged in n spaces is m! (m n)! –For example, given 52 playing cards we can deal 52! 47! 311,875,200 different 5-card hands, assuming the order of cards in the hand is significant Although we could calculate m! (m n)! by applying our factorial procedure twice and then dividing, this would not be very efficient because we would calculate term (m n)! twice

39
CRICOS No J a university for the world real R 39 Exercise 4-6: Permutations Define a recursive procedure permutations which, given two numbers m and n, where m n, calculates m! (m n)! efficiently Hint: In the playing card example, notice that the result is equal to 52 51 50 49 48 Examples: –(permutations 6 6) returns 720 –(permutations 6 1) returns 6 –(permutations 6 3) returns 120 –(permutations 4 2) returns 12

40
CRICOS No J a university for the world real R 40 Exercise 4-7: Length of longest word Write a procedure called longest-word-length which accepts a list of strings representing words and returns the length of the longest word in the list (or the special value 1 if the list is empty) Hint: The pre-defined procedure string-length returns the length of a string Example: –(longest-word-length (list "See" "Spot" "run")) returns 4

41
CRICOS No J a university for the world real R 41 Exercise 4-8: Summing digits Write a procedure sum-digits that computes the sum of the digits in a given number Hint: The pre-defined procedure remainder returns the remainder after integer division, e.g., (remainder ) returns 2 Example: –(sum-digits 472) returns 13

42
CRICOS No J a university for the world real R 42 Exercise 4-9: Counting letters Write a procedure count-letters which, when given a string comprising letters and space characters only, returns the number of letters Hint: Count-letters should convert the string into a list and use another procedure to do the counting –The pre-defined procedure string->list turns a string into a list of characters –The space character is written #\space Example: –(count-letters "My name is Fred") returns 12

43
CRICOS No J a university for the world real R 43 Exercise 4-10: Quotient by repeated subtraction Write a procedure quot which, given a non-negative numerator n and a positive denominator d, computes the integral part of n d by repeatedly subtracting d from n Hint: n d 0 when n d Example: –(quot 7 2) returns 3

44
CRICOS No J a university for the world real R 44 Exercise 4-11: Generalised quotient Extend your quot procedure to allow for the possibility that either, or both, of n and d are negative Hint: n d (n d) when d is negative n d ( n d) when n is negative Example: (quot 7 -2) returns -3 (This is an interesting example where the various recursive cases do quite different things)

45
CRICOS No J a university for the world real R 45 Exercise 4-12: Square roots by Newton’s method For further study, look at the example of calculating square roots by Newton’s method in Structure and Interpretation of Computer Programs, Section This is a good example of a large problem involving recursion and several procedures

46
CRICOS No J a university for the world real R 46 Exercise 4-13: Extracting alphabetic characters from text Define a procedure extract-alphas which takes a string of text and returns a string containing the alphabetic characters only Hint: You will need to convert the string into a list and back again using procedures string->list and list->string Hint: Pre-defined predicate char-alphabetic? can be used to test if a character is alphabetic or not

47
CRICOS No J a university for the world real R 47 Exercise 4-13: Extracting alphabetic characters from text Example: –(extract-alphas "Hello, World!") returns "HelloWorld"

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google