TORONTO KIDS COMPUTER CLUB | Friday 17:00 Python Practice 21.02.19.
19085
post-template-default,single,single-post,postid-19085,single-format-standard,ajax_fade,page_not_loaded,,qode-theme-ver-7.6.2,wpb-js-composer js-comp-ver-6.8.0,vc_responsive

Friday 17:00 Python Practice 21.02.19.

23 Feb Friday 17:00 Python Practice 21.02.19.

Question:

Use the recursion we have learn in the class, please try to create a function to recursively calculate the total of 1 + 2 + …. (n-2) + (n-1) + n

def total(n):
# please write you program below

total(int(input('Please enter a number:')))

Class Notes:

All recursive algorithms must obey three important laws:

  1. A recursive algorithm must have a base case.

  2. A recursive algorithm must change its state and move toward the base case.

  3. A recursive algorithm must call itself, recursively.

Sample program:

def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])

print(listsum([1,3,5,7,9]))

No Comments

Sorry, the comment form is closed at this time.