Solution Review: Sum of Digits in a String
This review provides a detailed analysis of the solution to find the sum of digits in a string
We'll cover the following
Solution: Using Recursion
def sumDigits(testVariable):# Base Caseif testVariable == "":return 0# Recursive Caseelse:return int(testVariable[0]) + sumDigits(testVariable[1:])# Driver Codeprint(sumDigits("345"))
Explanation
The solution to this problem is similar to the solution of finding the length of a string.
In this case, we, remove the first element of the string and call another instance of the same function. However, the first element of the string is converted to an integer type and when the child function returns its value, this converted integer is added to the result.
The base case remains the same, i.e., if the string is empty return .
Let’s have a look at the illustration:
Let’s try another challenge in the next lesson.