0
class Solution:
  def reverse(self, string):
    if len(string) == 0:
      return string
    else:
      return self.reverse(string[1:]) + string[0]

 a = 'hello'
print Solution().reverse(a)

output seems to be 'olleh' but my logic says it should be 'hello' after + string[0] any one knows why?

  • It's a recursive function. – Harry Mar 22 '21 at 05:54
  • 1
    I have no idea how "your logic" works, but it should be very obvious that you can't possibly get back 'hello'. Consider the *first* time that `self.reverse(string[1:]) + string[0]` runs. The `self.reverse(string[1:])` part has to result in *something*, right? And `string[0]` will evaluate to `'h'`, right? And we're going to put that "something" *before* the `'h'`, right? And we aren't putting anything after the `'h'`, right? So... – Karl Knechtel Mar 22 '21 at 06:01
  • string='hello' and string[1:] = 'ello' + string[0]=h so now we have = elloh if you recurse it one more time then its llohe, then lohel, then ohell, finally hello we end up with the same 'hello' is what I see from the code how is the result olleh is my question? – user15087554 Mar 23 '21 at 23:40

0 Answers0