Python 简化包含 OR 和 AND 的 if 条件

Python Simplifying if's conditions that contains ORs and ANDs

我正在 Python 中制作控制台内的 Battleship 游戏,我有一个代码可以检查这艘船是否适合列表。它看起来不太吸引人,我想把它简化成一个更吸引人的版本。

if (direction is "N" and row - size < 0) or \
  (direction is "E" and column + size > 10) or \
  (direction is "S" and row + size > 10) or \
  (direction is "W" and column - size < 0):
    print("It does not fit")

我正在考虑使用字典,但想不出在里面使用变量和数学运算符 (-+ <>) 的方法

if any([direction is "N" and row - size < 0, direction is "E" and column + size > 10, direction is "S" and row + size > 10, direction is "W" and column - size < 0]):
    print("It does not fit")

当然你的代码有很多改进,但这是一个开始

其他改进

if any([direction == "N" and size > row, direction == "E" and column + size > 10, direction == "S" and row + size > 10, direction == "W" and size > column]):

更好的方法,更清晰;

dir_classifier = {'N': size > row, 
'E': (column + size) > 10,
 'W': size > column,
 'S': (row + size > 10)}


if dir_classifier[direction]:
     print("It does not fit")

如果可能,从条件中删除 "negation"。然后提取条件到函数isFit(direction, row, column, size)。所以它看起来像这样:

if isFit(direction, row, column, size):
    print('It fits!!!')
else:
    print('It does not fit')

这样看起来简洁易读。

此外,您可以使用 sizedirectioncolumnrow 等属性创建适当的 Ship class。那么它会更好看:

if isFit(ship):
    print('...')

此外,isFit 可以是 Ship class:

的方法
if ship.isFit():
    print('...')

好吧,这不是最易读的方式,但我认为注意到它是一个很酷的想法

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

计数位函数来自:link

说明

count_bits - 计算数字的集合位

SN 需要使用 row 元素,它们在 ascii 值中都有 4 个设置位,因此它可以帮助我们确定值的使用行或列,如果有4个设置位,我们使用row,如果没有,我们使用col.

然后我们需要知道我们是想减去大小还是加起来,然后我们使用 (((n&7)==6) 就好像 3 lsb 等于 6,这对 [= 是正确的12=] 和 W