How to shorten this if and elif code in Python

There are two variables aand b, each of which can be positive or negative. The identifier must be set based on four conditions. How can the code below be minimized so that the same task can be achieved? Comprehension of a list or bitwise operation or something in this direction can shorten this, but I have no idea how to do it.

if a > 0 and b > 0:
    direction = 'NORTH EAST'

elif a > 0 and b < 0:
    direction = 'SOUTH EAST'

elif a < 0 and b < 0:
    direction = 'SOUTH WEST'

elif a < 0 and b > 0:
    direction = 'NORTH WEST'
+4
source share
4 answers

You can use conditional expressions such as

("NORTH " if b > 0 else "SOUTH ") + ("EAST" if a > 0 else "WEST")

There is another hack that can be used here.

["SOUTH ", "NORTH "][b > 0] + ["WEST", "EAST"][a > 0]

, Python . Python :

print 1 == True
# True
print 0 == False
# True
+2

:

direction = ' '.join(['NORTH' if a > 0 else 'SOUTH',
                      'EAST' if b > 0 else 'WEST'])

:

>>> for a in (-1, 1):
...     for b in (-1, 1):
...         print ' '.join(['NORTH' if a > 0 else 'SOUTH',
...                         'EAST' if b > 0 else 'WEST'])
... 
SOUTH WEST
SOUTH EAST
NORTH WEST
NORTH EAST
+1

. , :

>>> 
>>> a = 1
>>> b = -1
>>> lat = 'NORTH' if a > 0 else 'SOUTH'
>>> lon = 'EAST' if b > 0 else 'WEST'
>>> direction = '{} {}'.format(lat, lon)
>>> direction
'NORTH WEST'
>>>
0
source

Or use the dictionary as a map

map[-1] = {-1:'SOUTH WEST', 1: 'NORTH WEST'}
map[1] = {-1:'SOUTH EST', 1: 'NORTH EST'}
direction = map[a/abs(a)][b/abs(b)]
0
source

Source: https://habr.com/ru/post/1531947/


All Articles