Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the following recursive function give the outputs 'atm' and 'hatm'?

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?

like image 675
Max Muller Avatar asked Feb 15 '23 21:02

Max Muller


2 Answers

  1. 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"
like image 176
Joran Beasley Avatar answered Apr 27 '23 15:04

Joran Beasley


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'
like image 25
clcto Avatar answered Apr 27 '23 17:04

clcto