I am practicing some programming problems for my upcoming exam. This is one of the practice questions I did not understand:
"What does the following code (in Python) print?"
def f(s):
if len(s) <= 1:
return s
return f(f(s[1:])) + s[0] #Note double recursion
print f('mat')
print f('math')
Apparently, the answers are
atm
hatm
But why?
f("mat") = f(f("at"))+"m" -> f(f(f("t"))+"a") +"m" -> f("ta") + "m" -> "atm"
f("ta") = f(f("a")) + "t" -> f("a") + "t" -> "at"
f("at") = f(f("t"))+"a" -> f("t")+"a" - > "ta"
f("t") = "t"
f('mat')
f(f('at')) + 'm'
f('at') = f(f('t')) + 'a'
f('t') = 't'
f('at') = f('t') + 'a'
f('t') = 't'
f('at') = 'ta'
f('ta') + 'm'
f('ta') = f(f('a')) + 't'
f('a') = 'a'
f('ta') = f('a') + 't'
f('a') = 'a'
f('ta') = 'at'
'atm'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With