Marek
Marek

Reputation: 1249

Easier way to write conditional statement

Is there any prettier way to write this if-statement:

if not (self.is_legal(l) or self.is_legal(u) or self.is_legal(r) or self.is_legal(d)):

I've tried this, but it didn't work.

if not self.is_legal(l or r or d or u):

Or maybe the first one is the prettiest?

Upvotes: 4

Views: 117

Answers (4)

Rabia Naz
Rabia Naz

Reputation: 96

You can enhance the readability of your code by employing the any function. In the following code, a generator expression within the any function is used to determine whether any of the moves conforms to the legality condition specified by self.is_legal.

if not any(self.is_legal(move) for move in (l, u, r, d)):

Upvotes: 0

Rick
Rick

Reputation: 45231

You can use a tuple or set:

if False in (self.is_legal(l), self.is_legal(u), self.is_legal(r), self.is_legal(d)):

if {False} <= {self.is_legal(l), self.is_legal(u), self.is_legal(r)}:

Extending this idea a bit further:

if {False} <= {self.is_legal(var) for var in (l, u, r, d)}: 

Or using the fact that an empty list or set or whatever is false:

if [var for var in (l, u, r, d) if self.is_legal(var) is False]:

I guess it all depends on what you consider to be "pretty".

Upvotes: 0

dawg
dawg

Reputation: 103694

An empty list in Python is false.

You can produce an empty list with a comprehension and a conditional like so:

>>> def is_legal(x):
...    return x>5
... 
>>> bool([x for x in (1,2,3,4) if is_legal(x)])
False
>>> bool([x for x in (1,2,3,4,6) if is_legal(x)])
True

Upvotes: 0

user2555451
user2555451

Reputation:

You can use any and a generator expression:

if not any(self.is_legal(x) for x in (l, u, r, d)):

Or, if you prefer all instead of any:

if all(not self.is_legal(x) for x in (l, u, r, d)):

The first solution seems to read a little better though.


As for why your attempted solution did not work, the or operator in Python does not behave as you think it does. From the docs:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So, self.is_legal(l or r or d or u) was only passing the first truthy value to the self.is_legal method, not all of them.

Upvotes: 12

Related Questions