Agenda Announcements Snarf code CompSci101Recursion 1/14/2013 - - PowerPoint PPT Presentation

agenda
SMART_READER_LITE
LIVE PREVIEW

Agenda Announcements Snarf code CompSci101Recursion 1/14/2013 - - PowerPoint PPT Presentation

Agenda Announcements Snarf code CompSci101Recursion 1/14/2013 CompSci101 Peter Lorensen 1 Recusion Recusion: Se recusion. 1/14/2013 CompSci101 Peter Lorensen 2 Recursion Functions can call other functions, but they


slide-1
SLIDE 1

Agenda

  • Announcements
  • Snarf code “CompSci101Recursion”

1/14/2013 CompSci101 Peter Lorensen 1

slide-2
SLIDE 2

Recusion

  • Recusion: Se recusion.

1/14/2013 CompSci101 Peter Lorensen 2

slide-3
SLIDE 3

Recursion

  • Functions can call other

functions, but they can also call themselves – that is reursion!

1/14/2013 CompSci101 Peter Lorensen 3

slide-4
SLIDE 4

Recursion

  • It is not a function or library
  • It is a new way of structuring your code to solve

problems.

  • Recursion is based on the divide an conquer way of

thinking:

1/14/2013 CompSci101 Peter Lorensen 4

  • Solve 1 small piece of the problem

and call your self with the rest of it.

slide-5
SLIDE 5

Recursion example # 1

  • A simple recursive function

that counts down to “Blastoff”

1/14/2013 CompSci101 Peter Lorensen 5

def countdown(n): if n == 0: print 'Blastoff!' else: print n countdown(n - 1) countdown(5)

slide-6
SLIDE 6

Try example

1/14/2013 CompSci101 Peter Lorensen 6

slide-7
SLIDE 7

Recursion example # 2

1/14/2013 CompSci101 Peter Lorensen 7

  • How to count files and folders?
slide-8
SLIDE 8

Recursion example # 2

  • Solve a big problem by

– Dividing it into a smaller problem that can be

  • solved. Identical in structure.

1/14/2013 CompSci101 Peter Lorensen 8

slide-9
SLIDE 9

Recursion on a structure

  • Do something (like counting) on the place were

you are…

  • …then call your self on a new element.

1/14/2013 CompSci101 Peter Lorensen 9

slide-10
SLIDE 10

Recursion on a collection

  • If else structure:

– If the problem is small enough to be solved, then do it, otherwise divide it up and call yourself.

  • Do something to a small part of the problem,

then divide and call your self on the rest

1/14/2013 CompSci101 Peter Lorensen 10

def countdown(n): if n == 0: print 'Blastoff!' else: print n countdown(n - 1) countdown(5)

slide-11
SLIDE 11

Question

  • What is printed?

A) 100.0 7.25 , 1000.0 72.5 , 10.0 0.725 , Done B) 100.0 72.5 , 1000.0 725.0 , 10.0 7.25 , Done C) Error

1/14/2013 CompSci101 Peter Lorensen 11

def vatCalculator( meatLst ): vat = 7.25 if len( meatLst ) == 0: print "Done" else: pay = meatLst[0] tax = (pay * vat) / 100.0 print pay, tax, “," vatCalculator(meatLst) lionFood = [10.0, 1000.0, 100.0 ] vatCalculator( lionFood )

slide-12
SLIDE 12

Recursion in sorting

  • Quicksort can be solved via recursion

1/14/2013 CompSci101 Peter Lorensen 12