






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







def sumOfList(mylist): sumof = 0 # Add every number in the list. for i in range(mylist)): sumof = sumof + list[i] # Return the sum. return sumof print (sumOfList([ 5 , 7 , 3 , 8 , 10 ]))
So, which method is best? Well, obviously it depends on what you're trying to do - not all processes will provide an obvious recursive solution. Where they exist, recursive solutions tend to be more elegant, but can potentially be more difficult to understand (an important point to bear in mind if other people are going to be maintaining your code).
def sumOfList(mylist): if len(mylist) == 1 : return mylist[ 0 ] else : return mylist[ 0 ] + sumOfList(mylist[ 1 :]) print (sumOfList([ 5 , 7 , 3 , 8 , 10 ])) def sumOfList(mylist): sumof = 0 for i in range(mylist): sumof = sumof + list[i] return sumof print (sumOfList([ 5 , 7 , 3 , 8 , 10 ]))
Recursion / Recursive Programs
memory. So, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. You can change this with:
sys.setrecursionlimit( 5000 )
)
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …