1 Gentle Introduction to Programming Session 3: Recursion.

76
1 Gentle Introduction to Programming Session 3: Recursion
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    224
  • download

    0

Transcript of 1 Gentle Introduction to Programming Session 3: Recursion.

Page 1: 1 Gentle Introduction to Programming Session 3: Recursion.

1

Gentle Introduction to Programming

Session 3: Recursion

Page 2: 1 Gentle Introduction to Programming Session 3: Recursion.

2

Review• More Scala:

• var / val• Strings & API• Defining variables (type inference)• Variable scope• Importance of style

• Functions• Why do we need them• Types: methods, local (nested), literal, value• Closures• Higher order functions• The functions stack

• More on control structures• if / while / for result in a value

Page 3: 1 Gentle Introduction to Programming Session 3: Recursion.

3

Correctness Of Algorithm / Code

דיון

Page 4: 1 Gentle Introduction to Programming Session 3: Recursion.

4

Functions

((x : Int) => x * 2)(a)

((x : Int) => x * 2)(5)

((x : Int) => x * 2)5 5

10

Page 5: 1 Gentle Introduction to Programming Session 3: Recursion.

5

Higher Order Functions

100

1k

k

sum += ((x:Int) => x)(i)

i = ((x:Int) => x+1)(i)

Page 6: 1 Gentle Introduction to Programming Session 3: Recursion.

6

Integration as a Function

Integration under a curve f is approximated by

dx (f(a) + f(a + dx) + f(a + 2dx) + … + f(b))

a bdx

f

Page 7: 1 Gentle Introduction to Programming Session 3: Recursion.

7

Integration as a Function (Cont.)

a bdx

f

Page 8: 1 Gentle Introduction to Programming Session 3: Recursion.

8

arctan(a) = ∫(1/(1+y2))dy0

a

Integration.scala

Page 9: 1 Gentle Introduction to Programming Session 3: Recursion.

9

The Debugger

• Some programs may compile correctly, yet not produce the desirable results

• These programs are valid and correct Scala programs, yet not the programs we meant to write!

• The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program

Page 10: 1 Gentle Introduction to Programming Session 3: Recursion.

10

Debugger – Add Breakpoint

• Right click on the desired line

• “Toggle Breakpoint”

Page 11: 1 Gentle Introduction to Programming Session 3: Recursion.

11

Debugger – Start Debugging

breakpoint

debug

Page 12: 1 Gentle Introduction to Programming Session 3: Recursion.

12

Debugger – Debug Perspective

Page 13: 1 Gentle Introduction to Programming Session 3: Recursion.

13

Debugger – Debugging

Current state

Current location

Back to Scala perspective

Page 14: 1 Gentle Introduction to Programming Session 3: Recursion.

14

Today• Recursion• Guest lecture by Prof. Ran Canetti 11:10• Home work review• Home work• Arrays (if time allows)

Page 15: 1 Gentle Introduction to Programming Session 3: Recursion.

15

The Functions “Stack”

g()->h()

f()->g()

main-> f()

Page 16: 1 Gentle Introduction to Programming Session 3: Recursion.

16

Recursive Functions

• How to create a process of unbounded length?

• Needed to solve more complicated problems

• Tower of Hanoi

• Start with a simple example

Page 18: 1 Gentle Introduction to Programming Session 3: Recursion.

18

Tower of Hanoi

• How to solve for arbitrary number of disks n?• Let’s name the pegs: source, target, spare• All n disks are initially placed on source peg• Solution:

1. Move n-1 upper disks from source to spare

2. More lower (bigger) disk from source to target

3. Move n-1 disks from spare to target (smaller. Easier?)• Base condition: a single disk

Page 19: 1 Gentle Introduction to Programming Session 3: Recursion.

19

Factorial

• As we saw, n! = 1*2*3*… *(n-1)*n

• Thus, we can also define factorial the following way: • 0! = 1 • n! = n*(n-1)! for n>0

(n-1)! * n

RecursiveDefinition

Page 20: 1 Gentle Introduction to Programming Session 3: Recursion.

20

A Recursive Definition

• Functions can also call themselves!• However, usually not with the same parameters

• Some functions can be defined using smaller occurrences of themselves

• Every recursive function has a “termination condition”. The function stops calling itself when it is satisfied

Page 21: 1 Gentle Introduction to Programming Session 3: Recursion.

21

Example - Factorial

Termination Condition

Recursive Calll

Factorial.scala

Page 22: 1 Gentle Introduction to Programming Session 3: Recursion.

22

Example - factorial

factRec(1)

factRec(2)->2*factRec (1)

factRec(3)->3*factRec (2)

main-> factRec (3)

Page 23: 1 Gentle Introduction to Programming Session 3: Recursion.

23

Recursive factorial – step by step

FactRec(4)n

4

Returns…

Page 24: 1 Gentle Introduction to Programming Session 3: Recursion.

24

Recursive factorial – step by step

FactRec(4)n

4

Returns…4*…

Page 25: 1 Gentle Introduction to Programming Session 3: Recursion.

25

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

Page 26: 1 Gentle Introduction to Programming Session 3: Recursion.

26

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

Page 27: 1 Gentle Introduction to Programming Session 3: Recursion.

27

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…3*…

Page 28: 1 Gentle Introduction to Programming Session 3: Recursion.

28

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…

Page 29: 1 Gentle Introduction to Programming Session 3: Recursion.

29

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…

Page 30: 1 Gentle Introduction to Programming Session 3: Recursion.

30

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…2*…

Page 31: 1 Gentle Introduction to Programming Session 3: Recursion.

31

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…

FactRec(1)n

1

Returns…

Page 32: 1 Gentle Introduction to Programming Session 3: Recursion.

32

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…

FactRec(1)n

1

Returns…

Page 33: 1 Gentle Introduction to Programming Session 3: Recursion.

33

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…

FactRec(1)n

1

Returns… 1

Page 34: 1 Gentle Introduction to Programming Session 3: Recursion.

34

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…

FactRec(2)n

2

Returns…2*1

Page 35: 1 Gentle Introduction to Programming Session 3: Recursion.

35

Recursive factorial – step by step

FactRec(4)n

4

Returns…

FactRec(3)n

3

Returns…3*2

Page 36: 1 Gentle Introduction to Programming Session 3: Recursion.

36

Recursive factorial – step by step

FactRec(4)n

4

Returns…4*6

Page 37: 1 Gentle Introduction to Programming Session 3: Recursion.

37

General Form of Recursive Algorithms

• Base case: small (non-decomposable) problem• Recursive case: larger (decomposable) problem• At least one base case, and at least one recursive

case.

test + base case recursive case

Page 38: 1 Gentle Introduction to Programming Session 3: Recursion.

38

Short Summary

• Design a recursive algorithm by1. Solving big instances using the solution to smaller

instances

2. Solving directly the base cases

• Recursive algorithms have1. test

2. recursive case(s)

3. base case(s)

Page 39: 1 Gentle Introduction to Programming Session 3: Recursion.

39

More Examples

Page 40: 1 Gentle Introduction to Programming Session 3: Recursion.

40

Example - Modulo

• Given the following iterative version of modulo calculation

Find the recursive definition

Modulo.scala

Page 41: 1 Gentle Introduction to Programming Session 3: Recursion.

41

Solution

Page 42: 1 Gentle Introduction to Programming Session 3: Recursion.

42

Fibonacci

• “Naturally” recursive• Because the nth term is the sum of the (n-1)th and

(n-2)th terms• Therefore, the recursive definition is:

• fib(1) = 0 ; fib(2) = 1 /* base */• fib(n) = fib(n-1) + fib(n-2)

Page 43: 1 Gentle Introduction to Programming Session 3: Recursion.

43

Or, in Scala…Fibonacci.scala

Page 44: 1 Gentle Introduction to Programming Session 3: Recursion.

44

Recursion and Efficiency

• The recursive form, however elegant, may be much less efficient

• The number of redundant calls grow exponentially!

Fib(5)

Fib(4) Fib(3)

Fib(3) Fib(2) Fib(2) Fib(1)

Fib(2)

Fib(1)

Fib(6)

Fib(4)

Page 45: 1 Gentle Introduction to Programming Session 3: Recursion.

45

Efficient Recursive Fibonacci

• Pass the values that were already calculated to the recursive function

• This technique is called Memoization

• How would we keep the values that were already calculated?

Fib(5)

Fib(4) Fib(3)

Fib(3) Fib(2) Fib(2) Fib(1)

Fib(2)

Fib(1)

Fib(6)

Fib(4)

Page 46: 1 Gentle Introduction to Programming Session 3: Recursion.

48

Odd-Even

• Given a function ‘odd(n : Int) : Boolean’ • Return true on n that are odd, false on even n

• Write a function ‘even(n : Int) : Boolean’ that:• Return true on n that are even, false on odd n

• This is easy

Page 47: 1 Gentle Introduction to Programming Session 3: Recursion.

49

Odd-EvenEvenOdd.scala

Page 48: 1 Gentle Introduction to Programming Session 3: Recursion.

50

Decimal Binary

• We want to print the binary representation of a decimal number

• Examples:• 0 -> 0• 8 -> 1000• 12 -> 1100• 31 -> 11111

Page 49: 1 Gentle Introduction to Programming Session 3: Recursion.

51

Decimal Binary Recursively

• The conversion of a number d from decimal to binary:• If d is 0 or 1 – write d to the left and stop, else:• If d is even, write ‘0’ to the left• If d is odd, write ‘1’ to the left• Repeat recursively with floor(d/2)

Page 50: 1 Gentle Introduction to Programming Session 3: Recursion.

52

Example: d = 14

d Output at the end of stage Action at the end of stage

14 0 Insert 0 to left of output; divide d by 2

7 10 Insert 1 to left of output; divide d by 2 and round down

3 110 Insert 1 to left of output; divide d by 2 and round down

1 1110 Insert 1 to left of output; return.

Page 51: 1 Gentle Introduction to Programming Session 3: Recursion.

53

Solution Dec2Bin.scala

Page 52: 1 Gentle Introduction to Programming Session 3: Recursion.

54

Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)

Page 53: 1 Gentle Introduction to Programming Session 3: Recursion.

55

Approximating Square Root

• Given integer x > 0, how to find an approximation of x?

• Newton was the first to notice that for any positive n, and when x0=1, the following series converges to sqrt(n):

Page 54: 1 Gentle Introduction to Programming Session 3: Recursion.

56

Algorithm

x = 2 g = 1x/g = 2 g = ½ (1+ 2) = 1.5

x/g = 4/3 g = ½ (3/2 + 4/3) = 17/12 = 1.416666

x/g = 24/17 g = ½ (17/12 + 24/17) = 577/408 = 1.4142156

• Algorithm:• Make a guess g• Improve the guess by averaging g, x/g• Keep improving the guess until it is good enough

• Example: calculate the square root of 2

Page 55: 1 Gentle Introduction to Programming Session 3: Recursion.

57

Exercise 1

• Write a program that receives from the user:• An integer x > 0• A double representing the approximation’s accuracy

• Calculates an approximation of x within the required accuracy

Use the function Math.abs(x) which returns the absolute value of x

Page 56: 1 Gentle Introduction to Programming Session 3: Recursion.

58

Solution ApproxSQRT.scala

Page 57: 1 Gentle Introduction to Programming Session 3: Recursion.

59

Exercise 2

Write a function that uses the formula :2/6=1/1+1/4+1/9+1/16+…+1/n2 (where n goes to infinity)

in order to approximate . The function should accept an argument n which determines the number of terms in the formula. It should return the approximation of

Write a program that gets an integer n from the user, and approximate using n terms of the above formula• Use a nested function sum, with signature:

Page 58: 1 Gentle Introduction to Programming Session 3: Recursion.

60

Solution ApproxPI.scala

Page 59: 1 Gentle Introduction to Programming Session 3: Recursion.

61

Exercise 3

• Write a function deriv: • Input: a function f (Double=>Double), accuracy dx• Output: function df (Double=>Double), the derivative

of f. • df (x) = (f(x+dx) – f(x))/dx• Define a few simple functions (linear, square) and

calculate their derivative at various points received by command line arguments

Page 60: 1 Gentle Introduction to Programming Session 3: Recursion.

62

Usage Example

// the function you want to derive

def f(x : Double) : Double = x * x// resolution/accuracy/granularity of derivative

val dx = 0.001 /* this is the invokation of the function you

are supposed to implement*/

val df = deriv(f,dx) // print the derivative of f(x) at x = 10

println(df(10))

Page 61: 1 Gentle Introduction to Programming Session 3: Recursion.

63

SolutionDerivative.scala

Page 62: 1 Gentle Introduction to Programming Session 3: Recursion.

64

Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)

Page 63: 1 Gentle Introduction to Programming Session 3: Recursion.

65

Exercise 1

• Write a program that receives two non-negative integers and computes their product recursively

• Hint: Notice that the product a*b is actually a+a+…+a (b times). How does this help us define the problem recursively?

Page 64: 1 Gentle Introduction to Programming Session 3: Recursion.

66

Exercise 2

• Given the following iterative version of sum-of-digits calculation

Write the recursive definition

Page 65: 1 Gentle Introduction to Programming Session 3: Recursion.

67

Exercise 3

• Write a function that simulates print on positive integers

• The function should print one digit at time• Example:

• printRec(1234) 1234

Page 66: 1 Gentle Introduction to Programming Session 3: Recursion.

68

Today• Recursion• Guest lecture by Prof. Ran Canetti• Home work review• Home work• Arrays (if time allows)

Page 67: 1 Gentle Introduction to Programming Session 3: Recursion.

69

Arrays

• Array: sequential block of memory that holds variables of the same type

• Array can be declared for any type• Example: new Array[Int](3)

• Examples:• list of students’ marks• series of numbers entered by user• vectors• matrices

Page 68: 1 Gentle Introduction to Programming Session 3: Recursion.

70

Arrays in Memory

• Sequence of variables of specified type• The array variable itself holds the address in

memory of beginning of sequence• Example: val s = new Array[Double](10)

• The k-th element of array A is specified by A[k-1] (0 based)

0 1 2 3 4 5 6 7 8 9

s

……

Page 69: 1 Gentle Introduction to Programming Session 3: Recursion.

71

Example - Initialization

Page 70: 1 Gentle Introduction to Programming Session 3: Recursion.

72

Arrays in Memory

• Access array’s content

• Change array’s content

Page 71: 1 Gentle Introduction to Programming Session 3: Recursion.

73

Example

Array.scala

Page 72: 1 Gentle Introduction to Programming Session 3: Recursion.

74

foreach, filter

• Iterates over arrays (and other containers)

• foreach – for each element apply a given function

• filter – create a new container containing only elements that pass the given Boolean-function

Page 73: 1 Gentle Introduction to Programming Session 3: Recursion.

75

Example – Print Arrays PrintArray.scala

Page 74: 1 Gentle Introduction to Programming Session 3: Recursion.

76

Example – filter

Page 75: 1 Gentle Introduction to Programming Session 3: Recursion.

77

Example – Find MinimumFindMin.scala

Page 76: 1 Gentle Introduction to Programming Session 3: Recursion.

78

HW on Arrays: Exercise 4

Write a program that gets 10 numbers from the user.It then accepts another number and checks to see ifthat number was one of the previous ones.

Example 1:Please enter 10 numbers:1 2 3 4 5 6 7 8 9 10Please enter a number to search for: 8Found it!

Example 2:Please enter 10 numbers:1 2 3 4 5 6 7 8 9 10Please enter a number to search for: 30Sorry, it’s not there