INFO1110 Lecture Notes - Lecture 2: Order Of Merit, Call Stack

22 views1 pages

Document Summary

Each function call requires python to construct a stack frame: some problems are easier to solve with an iterative solution. When writing a recursive method, you need: a base case, a recursive case. Note: every time the method is called, a new function is loaded into the memory with it"s own copies of local variables and arguments. So if you have called the same function 5 times, python has stored the data in each of those function invocations. Exercise: write a recursive function that returns the cumulative sum from 0 up until a speci ed number. If the speci ed number is negative, return 0. # using recursion def cumulative_sum(n): if n <= 0: return 0 else: return n + cumulative_sum(n-1) print(cumulative_sum(0)) print(cumulative_sum(3)) print(cumulative_sum(10)) # using iteration def cumulative_sum(n): if n <= 0: return 0 total = 0 num = 1 while num <= n: total += num.

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents