Comment cela peut-il très long instruction if simplifiée?
-
28-09-2019 - |
Question
Comment cela peut-instruction if être simplifiée? Il fait un signe plus: http://i.stack.imgur.com/PtHO1.png
Si l'instruction est terminée, puis un bloc est fixé au coordonnées x et y.
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):
...
La solution
est le même:
if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1):
Autres conseils
En gros vous carreler un modèle binaire 5x5. Voici une expression claire de ce qui suit:
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]:
...
Ceci est une approche très simple et générale qui permettrait au motif d'être facilement modifié.
Il y a deux corrections triviales:
- Cache le résultat de
x % 5
ety % 5
- Utilisez
in
ou<
enchaînée pour tester les valeurs:
En outre, le test <= 4
(ou < 5
) est en fait redondante parce que tous valeur de lx
et ly
sera <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):
Ou vous pouvez simplement garder une liste des tuples réellement autorisés:
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:
Miser sur la réponse de Konrad, vous pouvez simplifier davantage:
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))):
seconde réponse Konrad: -
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:
est probablement le meilleur.
Cependant, je vais contribuer: -
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):
La solution générale à l'optimisation d'une fonction logique de ce type est un Karnaugh map . Votre table de vérité serait le littéral, plus la forme que vous voulez avec des lignes et des colonnes étant vos tests modulaires.