【问题标题】:Python 3.5 - How can I make this code more efficient/shorter? [closed]Python 3.5 - 我怎样才能让这段代码更高效/更短? [关闭]
【发布时间】:2015-11-22 02:19:57
【问题描述】:

我有一个

list = [value, value, value, value, value, value, value, value, value]

其中 value 取值:-1、0 或 1。

if list[0] + list[1] + list[2] == 3:
    alternative1 = True
elif list[0] + list[1] + list[2] == -3:
    alternative2 = True
elif list[3] + list[4] + list[5] == 3:
    alternative1 = True
elif list[3] + list[4] + list[5] == -3:
    alternative2 = True
elif list[6] + list[7] + list[8] == 3:
    alternative1 = True
elif list[6] + list[7] + list[8] == -3:
    alternative2 = True
elif list[0] + list[3] + list[6] == 3:
    alternative1 = True
elif list[0] + list[3] + list[6] == -3:
    alternative2 = True
elif list[1] + list[4] + list[7] == 3:
    alternative1 = True
elif list[1] + list[4] + list[7] == -3:
    alternative2 = True
elif list[2] + list[5] + list[8] == 3:
    alternative1 = True
elif list[2] + list[5] + list[8] == -3:
    alternative2 = True
elif list[0] + list[4] + list[8] == 3:
    alternative1 = True
elif list[0] + list[4] + list[8] == -3:
    alternative2 = True
elif list[2] + list[4] + list[6] == 3:
    alternative1 = True
elif list[2] + list[4] + list[6] == -3:
    alternative2 = True

那么我怎样才能使这段代码更高效/更短?我想我可以使用某种 while 循环或类似的方法来完成此操作,但我无法让列表占位符匹配。

【问题讨论】:

  • 这是列、行和对角线,不是吗?某种井字游戏?
  • for index1, index2, index3 in [(0, 1, 2), ...]: if list[index1] + list[index2] + list[index3] == mul: ...?并且不要影响list
  • 是的,实际上是一个非常相似的问题。 @德尔根
  • 不要命名list,因为那是内置类型的名称。
  • 我投票结束这个问题,因为它要求对工作代码进行代码审查,这更适合codereview.stackexchange.com

标签: python python-3.x optimization


【解决方案1】:

一些一般性建议:

  • 当您的逻辑在数据中而不是代码中时,代码通常更加更清晰且更易于修改。构建将情况映射到操作的数据结构。 Jon Bentley 的 Programming Pearls 详细介绍了这一点。
  • 您可以将 dict 用作​​二维数组:board={} 然后 board[2,2] 其中键是元组。
  • 完成此操作后,您可以规范化图案以以相同方式处理相互反射或旋转的图案。 (以下未显示。)

为了更具体,让我们假设这是标准井字游戏,并考虑如何检测胜利,这似乎是您至少在部分代码中的目标。我们将使用二维数组,1, 0, -1 表示 X, empty, O,就像您正在做的那样(尽管您的特定编码可能会有所不同)。

# List of winning combos.
win_runs = [
    ((0,0), (0,1), (0,2)), # ... rows
    ((0,0), (1,0), (2,0)), # ... columns
    ((2,0), (1,1), (0,2)), # ... diagonals
]

# Initialize empty board.
board = {(i,j): 0 for i in range(3) for j in range(3)}

# Set up a win in leftmost column.
board[0,0] = board[1,0] = board[2,0] = -1

# Check if anyone has a win.
for run in win_runs:
    values = {board[tup] for tup in run} # values is a set
    if len(values) == 1 and 0 not in values:
        print('{} wins'.format(values.pop()))
        break
else:  # executed only if for loop is exhausted
    print('no one wins yet')

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多