70 likes | 198 Views
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.
E N D
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 >>> downUp("Hello")
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
Decrease Red Recursively def decreaseRedR(aList ): if aList == []: # empty return setRed(aList [0], getRed(aList [0])*0.8) decreaseRedR(aList [1:])
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?
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
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