1 / 7

Recursion

Recursion. Barb Ericson ericson@cc.gatech.edu Georgia Tech. Recursion. When a function calls itself Used to break problems into smaller problems Used to solve recursion problems. def downUp(word ): print word if len(word )==1: return downUp(word [1:]) print word.

thomas-beck
Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Recursion Barb Ericson ericson@cc.gatech.edu Georgia Tech

  2. Recursion • When a function calls itself • Used to break problems into smaller problems • Used to solve recursion problems def downUp(word ): print word if len(word )==1: return downUp(word [1:]) print word >>> downUp("Hello")

  3. import os import java.io.File as File def printAllFiles(directory ): files = os.listdir(directory) for file in files: fullname = directory+"/"+file if isDirectory(fullname ): printAllFiles(fullname) else: print fullname def isDirectory(filename ): filestatus = File(filename) return filestatus.isDirectory () Print filenames in a directory tree

  4. Decrease Red Recursively def decreaseRedR(aList ): if aList == []: # empty return setRed(aList [0], getRed(aList [0])*0.8) decreaseRedR(aList [1:])

  5. def test(num): if num > 0: return test(num -1) + num else: return 0 Call Stack test(0) return 0 test(1) return test(0) + 1 test(2) return test(1) + 2 test(3) return test(2) + 3 What is the output?

  6. Stacks • Add and remove from the top of the stack • Last in first out type of structure • Like a stack of plates in a cafeteria • Or a Pez container • Or a childs toy

  7. Queue • Add to the end and remove from the front • First in and first out type of structure • Like a line at a store checkout • Or a printer queue

More Related