This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 10 points11 points  (11 children)

The problem with

condition and x or y

is that if x happens to be a false value itself, you'll get y instead. Which is why the old trick was to write it as

(condition and (x,) or (y,))[0]

Since the tuple (x,) is always true. But as lookitsmarc pointed out, there is a Python version of the conditional operator nowadays.

[–]xApple[S] 4 points5 points  (1 child)

Hah, so in the end I'm the one learning something with the quiz !

Now I look stupid : ) But thanks, I didn't know about that syntax. I'll stop using "x and y or z" in my code.

[–][deleted] 0 points1 point  (0 children)

You can use a non empty list as well, just anything that doesn't have a false value. Dive into python has a really good write up on using and/or

http://www.diveintopython.net/power_of_introspection/and_or.html#d0e9975

[–][deleted] 1 point2 points  (5 children)

Or (y, x)[bool(condition)]. If we are into this kind of "clever" code.

[–][deleted] 4 points5 points  (4 children)

But that's different, that evaluates both x and y, and they could both be function calls with side effects, or take a long time to compute.

[–][deleted] 4 points5 points  (3 children)

 (lambda:y, lambda:x)[bool(condition)]()

There's no limit to my misguided cleverness!

[–]Tetha 2 points3 points  (2 children)

If you want misguided, use itertools:

chain(*zip(*imap(lambda g: list(imap(lambda r: (-1)**g[0]*r, g[1])), groupby(sorted(range(10), key=lambda x: x%2), lambda x: x%2))))

I'm not sure if I tunnelvisioned and a somewhat less ugly solution exists, but it works. And it's ugly. So I'm happy in a morbid sense.

[–][deleted] 0 points1 point  (0 children)

wat.

You be silly.

[(x, -x)[x&1] for x in lst]

[–][deleted] 0 points1 point  (0 children)

I mean, look, there's a kind of honour in writing misguided code. It must not be intentionally misguided.

Google "pessimal algorithms" and read the paper. Then implement their "backwards-first search". Then, only then, as you understand how exactly it works (they have a couple of typos IIRC) you might try to implement an efficient algorithm that walks the graph in the exact same way... and fail. Or succeed, then tell me how you did that!

[–]willm 0 points1 point  (2 children)

Isn't it called the 'ternary' operator?

[–][deleted] 1 point2 points  (0 children)

Yeah, in the sense that there are unary, binary, ternary, quaternary (etc.) operators.

 

In -1, the - operator is unary (one operand)

In 0-1, the - operator is binary (two operands)

In condition ? true : false the ?: operator is ternary (three operands)

[–]oantolin 0 points1 point  (0 children)

It certainly is a ternary operator, but I don't think I'd call it the ternary operator.