Can anyone please help me in understanding the following python code
Chris Angelico
rosuav at gmail.com
Thu May 30 06:47:22 EDT 2013
On Thu, May 30, 2013 at 8:19 PM, <bhk755 at gmail.com> wrote:
> Thanks for the reply Chris.
>
> I am newbie to python, so please excuse me if I am asking chilly questions.
All questions are welcome!
> Can you please explain more about the following sentence.
> "When it says "Splitting" with a single-element list, it then
> immediately prints "Merging" and returns (because all the rest of the
> code is guarded by the 'if'). Execution then continues where it left
> off, in the parent."
The code goes like this:
1) Print "Splitting"
2) If there's more than one element in the list:
2a) Divide the list in half
2b) Call self on each half
2c) Merge
3) Print "Merging
In step 2b, all the steps from 1 through 3 are executed again (twice).
Soon, those calls will just output "Splitting" followed by "Merging";
and then we go back to 2c. That's why it *seems* that the code goes
from 3 to 2c. You'll notice that the call depth decreases when this
happens.
> Because I am not sure how the control can go back to top of the function unless there is no loops there.
>
> Also, Can you please let me know how did you found out that I am using Python 2 Interpreter.
That one is actually based on my crystal ball. Here on python-list, we
issue them to all our top respondents; they're extremely useful. I'll
let you in on part of the secret of how this works, though.
In Python 2, 'print' is (by default) a statement. When you give it
something in parentheses, it sees a tuple:
print("Splitting ",alist)
('Splitting ', [54, 26, 93, 17, 77, 31, 44, 55, 20])
In Python 3, 'print' is a function. It takes arguments, and prints out
each argument, separated by spaces.
print("Splitting ",alist)
Splitting [17, 20, 26, 31, 44, 54, 55, 77, 93]
You can make Python 2 behave the same way by putting this at the top
of your program:
from __future__ import print_function
ChrisA
More information about the Python-list
mailing list