-4

How do you write one line of Python Code with 3 if statements each returning a statement? EX:

if ((x<c) and (c<r)):
    return c
if ((c<x) and (x<r)):
    return x
if (c<b) and (r<x)):
    return r
martineau
  • 99,260
  • 22
  • 139
  • 249
N.R
  • 1

3 Answers3

1

In general, don't: it's harder to read. Instead, simply clear out the redundancy in your existing code:

if x < c < r:
    return c
elif c < x < r:
    return x
elif c < b and r < x:
    return r

The same redundancy elimination can fuel the one-liner, but even then, it's still a pain to read, especially with the meaningless variable names.

return c if x < c < r \
  else x if c < x < r \
  else r if c < b and r < x \
  else None
Prune
  • 72,213
  • 14
  • 48
  • 72
-1

you could do it like this:

c if ((x<c) and (c<r)) else x if ((c<x) and (x<r)) else r

Another way, propably not really practical but still possible:

from itertools import compress
list(compress([c, x, r], [((x<c)&(c<r)), ((c<x)&(x<r)), ((c<b)&(r<x))]))[0]
Andreas
  • 4,572
  • 2
  • 4
  • 25
-3

Use conditional expressions. Add parentheses around the nested one to ensure proper precedence.

return c if (x < c and c < r) else (x if (c < x and x < r) else (r if (c < b and r < x) else None))

You need to make the None default return value explicit, since conditional expressions require both if and else expressions. This will happen if any of the values are equal, rather than strictly less than each other.

That said, I strongly recommend against this. It's not nearly as clear as your original code. There's no bonus for one-liners, except in Code Golf competitions.

It also seems like you're always returning the middle of the 3 values. So you can simply sort them and return the middle one:

return sorted([x, c, r])[1]

However, this doesn't return None in the case that some of the values are equal. Maybe that can't happen?

Barmar
  • 596,455
  • 48
  • 393
  • 495