Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ant6n
Last active December 27, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ant6n/7237768 to your computer and use it in GitHub Desktop.
Save ant6n/7237768 to your computer and use it in GitHub Desktop.
Question: "Python:
>>> LINE A
>>> LINE B
>>> LINE C
False
>>> LINE A; LINE B; LINE C
True
what are the lines? nothing stateful allowed & no __methods."
(https://twitter.com/akaptur/status/395252265117687808).
My answer:
The given example. It relies on the fact that if the three lines are written together,
then they become part of the body of the for loop, whereas separated the for loop only
has the single statement in it. This is used to have variable (x) set to either 0 or 2
at the end of the loop. Since the print statement will be executed twice if it's inside
the loop (the loop body executes twice), Nothing gets printed if x is 1, which happens
during the first iteration when the lines are written together.
The "x = n or x-1" allows initializing x on the first iteration - because n is -1, it
will be assigned -1. On the second iteration, n == 0 == False, so the statement will
assign x-1 to x.
Executing in Ipython I get:
In [142]: for n in range(-1,1):x=n or x-1;
In [143]: x+=2;
In [144]: sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True"))
False
In [145]: for n in range(-1,1):x=n or x-1;x+=2;sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True"))
True
In [146]:
for n in range(-1,1):x=n or x-1;x+=2;sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True"))
for n in range(-1,1):x=n or x-1;
x+=2;
sys.stdout.write("" if x == 1 else ("False" if x == 0 else "True"))
@cpatulea
Copy link

The cpython repl does not like this - it wants more loop body:

>>> for n in range(-1,1):x=n or x-1;
...

My impression from the problem statement is that each line should be a complete statement, such that the repl returns to the ps1 prompt (>>>) after each.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment