In [1]:
def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum
print(listsum([1,3,5,7,9]))
In [2]:
def listsum(numList):
if len(numList) == 1: # base case
return numList[0]
else:
return numList[0] + listsum(numList[1:]) # change its state and move toward base case with [1:]
print(listsum([1,3,5,7,9]))
In [3]:
# base case - n < base
# n / base (division by the base will move us toward base case)
# call recursion on n/base
def toStr(n,base):
convertString = "0123456789ABCDEF"
if n < base:
return convertString[n]
else:
return toStr(n // base, base) + convertString[n % base]
In [4]:
print(toStr(1453,16))
In [6]:
def reverseStr(s):
if len(s) == 1:
return s
else:
return reverseStr(s[1:]) + s[0]
In [7]:
reverseStr("hello")
Out[7]:
In [ ]: