- The problem:
def vowelCount(s):
# same as above...
if (s == ""): return 0
else:
thisCount = 1 if (s[0].upper() in "AEIOU") else 0
restCount = vowelCount(s[1:])
return thisCount + restCount
s = "This works!"
print(vowelCount(s)) # 2
L = list(s)
print(vowelCount(L)) # crash! IndexError: list index out of range
- The solution:
def vowelCount(s):
# notice the change...
if (len(s) == 0): return 0
else:
thisCount = 1 if (s[0].upper() in "AEIOU") else 0
restCount = vowelCount(s[1:])
return thisCount + restCount
s = "This works!"
print(vowelCount(s)) # 2
L = list(s)
print(vowelCount(L)) # 2 (now lists work, too!)
- The problem (once again):
def mySum(L):
# duplicating built-in sum function recursively, but with a problem...
if (L == [ ]): return 0
else: return L[0] + mySum(L[1:])
print(mySum([0,1,2,3])) # 6 (this works)
print(mySum(range(4))) # crash! IndexError: range object index out of range
- The solution:
def mySum(L):
# duplicating built-in sum function recursively, now fixed...
if (len(L) == 0): return 0
else: return L[0] + mySum(L[1:])
print(mySum([0,1,2,3])) # 6 (this works)
print(mySum(range(4))) # 6 (this works, too!)