Well, its not the most readable way, but i think it a cool think to notice
def is_valid(direction):
n = ord(direction)
bits = count_bits(n)
result = (bits == 4) * row) + ((bits != 4) * col) + ((((n&7)==6) * -1) * size
if (0 > result > 10):
print('invalid')
def count_bits(n):
n = (n & 0x5555555555555555) + ((n & 0xAAAAAAAAAAAAAAAA) >> 1)
n = (n & 0x3333333333333333) + ((n & 0xCCCCCCCCCCCCCCCC) >> 2)
n = (n & 0x0F0F0F0F0F0F0F0F) + ((n & 0xF0F0F0F0F0F0F0F0) >> 4)
n = (n & 0x00FF00FF00FF00FF) + ((n & 0xFF00FF00FF00FF00) >> 8)
n = (n & 0x0000FFFF0000FFFF) + ((n & 0xFFFF0000FFFF0000) >> 16)
n = (n & 0x00000000FFFFFFFF) + ((n & 0xFFFFFFFF00000000) >> 32) # This last & isn't strictly necessary.
return n
Counting bit functino from : link
Explanation
count_bits - counts the set bits of a number
S
and N
require to use the row
element, which they both have 4 set bits in there ascii value, so it help us to determ the using of the value row or colum, it there are 4 set bits, we use the row
, and if not, we use the col
.
then we need to know if we want to substract the size, or adding it up, then we use (((n&7)==6)
which tells as if the 3 lsb is equals to 6, which will be true for N
and W