def function(s):
if len(s) == 1:
print s[0],
else:
function(s[1:])
print s[0],
function("1234") ends up printing 4 3 2 1
Why does this happen? In the function, obviously the first condition is not met. In the else condition, s[1:] is put in for s, yet its length is not 1. I just don’t see how anything outside of s[0] would be printed to the screen. There’s nothing in that function that looks like it’d print s[1:], let alone in reverse. I’m pretty confused.
This is a case of recursion, you are calling the function itself over and over with shorter and shorter substrings of the original input, until it is a string of length 1 (the last one in the original input) in which case it starts printing it and then “unwinding” and printing the rest of the string in reverse.
Take a look at this annoted code:
the output you get is:
The first time you call the function you drop through to the
elseclause and in line (B) you call the function again, but this time with “234”. Now the function starts again but with “234” and again you drop through to theelseand now call function again, but now with “34”, function runs again, now with you drop through to theelseonce more and call function with just “4” .. this time since it’s of length 1, you print it (line A).Now you return from this function (the unwinding process) – and resume from the point where you were before you made your recursive call and you print the rest of the string in reverse by printing the first character of the current remaining character (line C).
Recursion can be hard to grasp the first time you encounter it – that’s perfectly normal. At some point it will click and become clear. You may want to do some reading about the general concept and search for some clear annotated examples (most CS/programming books will have some).
Here is a short YouTube video that explains recursion in Python with a simple example, hope it helps: http://www.youtube.com/watch?v=72hal4Cp_2I