How can I simplify this very long if-expression?

How to simplify this if statement? This makes a plus sign: http://i.stack.imgur.com/PtHO1.png

If the instruction is complete, then the block is specified in x and y coordinates.

for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \ (y%5 == 2 or y%5 == 3 or y%5 == 4) and \ not(x%5 == 2 and y%5 == 2) and \ not(x%5 == 4 and y%5 == 2) and \ not(x%5 == 2 and y%5 == 4) and \ not(x%5 == 4 and y%5 == 4): ... 
+6
python if-statement graphics modulus
source share
6 answers

Same:

 if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): 
+15
source share

You basically break up the 5x5 binary pattern. Here's the explicit expression:

 pattern = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 1, 1], [0, 0, 0, 1, 0]] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if pattern[x%5][y%5]: ... 

This is a very simple and general approach, making it easy to modify the template.

+12
source share

There are two trivial fixes:

  • Download result x % 5 and y % 5
  • Use in or a chain < to check the values:

In addition, the test for <= 4 (or < 5 ) is actually redundant, since each value of lx and ly will be <5.

 for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 # for local-x ly = y % 5 # for local-y if lx > 1 and y > 1 and \ not (lx == 2 and ly == 2) and \ not (lx == 4 and ly == 2) and \ not (lx == 2 and ly == 4) and \ not (lx == 4 and ly == 4): 

Or you can just save the list of actually allowed tuples:

 cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x % 5, y % 5) in cross_fields: 
+7
source share

Based on Conrad's answer, you can simplify it:

 for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 # for local-x ly = y % 5 # for local-y if (1 < lx < 5 and 1 < y < 5 and (lx, ly) not in ((2, 2), (4, 2), (2, 4), (4, 2))): 
+2
source share

Conrad's second answer: -

 cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)] for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): if (x % 5, y % 5) in cross_fields: 

probably the best.

However, I will contribute: -

 for y in range(MAP_HEIGHT): for x in range(MAP_WIDTH): lx = x % 5 ly = y % 5 if (lx > 1 and ly == 3) or (ly > 1 and lx == 3): 
+1
source share

A common solution for optimizing such a logical function is the Carnot map . Your truth table is the literal plus you want, with rows and columns being your unit tests.

0
source share

All Articles