Write Python program with the following functions: A recursive function called s
ID: 3678679 • Letter: W
Question
Write Python program with the following functions:
A recursive function called stutter that returns a string with each character in its argument repeated. For example, if the string passed to stutter is "abc", stutter will return the string "aabbcc".
A recursive function called toNumber that returns the integer sum of all digit characters in a string. For example, the result of toNumber("ab3c7d1") would be 11. Assume that the length of any empty string is 0. (Hint: you may use the method isdigit() to check whether or not a character is a digit.)
Add a main function to test your code.
Explanation / Answer
You have asked for a recursive implementation so i have tried doing that.
But without making these functions recursive also we can do the tasks mentioned above
assignment.py
def toNumber(text):
if(len(text)==1):
if text.isdigit():
return int(text)
else:
return 0
sum=0;
for i in text:
sum=sum+toNumber(i)
return sum
def stutter(text):
if(len(text)==1):
return text*2
newText=''
for i in text:
newText=newText+stutter(i);
return newText
#for testing the methods
text="123xcde89"
sum=toNumber(text)
print sum
text="abc"
print stutter(text)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.