【问题标题】:Trouble understanding modulus on a negative in 'Conways Game of Life'难以理解“康威人生游戏”中负数的模数
【发布时间】:2020-05-06 16:02:29
【问题描述】:

我正在阅读“用 python 自动化无聊的东西”这本书,无法理解使用 % 运算符的简单表达式。表达式是leftCoord = (x - 1) % WIDTH,在循环的第一次迭代中计算为(0 - 1) % 60。在我看来,% 运算符应该评估为除法的其余部分。为什么它评估为 9?

这是程序中出现问题的表达式之前的部分:

import random,time,copy

WIDTH = 60
HEIGHT = 20

# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
    column = [] # Create a new column.
    for y in range(HEIGHT):
        if random.randint(0,1) == 0:
            column.append('#') # Add a living cell.
        else:
            column.append(' ') # Add a dead cell.
    nextCells.append(column) # nextCells is a list of column lists.

while True: # Main program loop.
    print('\n\n\n\n\n') # Separate each step with newlines.
    currentCells = copy.deepcopy(nextCells)

    # Print currentCells on the screen:
    for y in range(HEIGHT):
        for x in range(WIDTH):
            print(currentCells[x][y], end='') # Print the # or space.
        print() # Print a newline at the end of the row.


    # Calculate the next step's cells based on current step's cells:
    for x in range(WIDTH):
        for y in range(HEIGHT):
            # Get neighboring coordinates:
            # % WIDTH ensures leftCoord is always between 0 and WIDTH -1
            leftCoord  = (x - 1) % WIDTH
            rightCoord = (x + 1) % WIDTH
            aboveCoord = (y - 1) % HEIGHT
            belowCoord = (y + 1) % HEIGHT

【问题讨论】:

  • 这需要更多上下文。这不是一个完整的陈述,所以希望你把它从更长的表达式中提取出来。

标签: python-3.x modulus


【解决方案1】:

为了举例,假设您使用的是 10x10 的表格。

当第一个数字小于第二个数字时,% 运算符就不那么直观了。尝试进入交互式 python shell 并运行 4 % 10。尝试 8 % 10。注意你总是得到相同的数字吗?那是因为除法的答案是 0... 你的整数作为余数剩下。对于表中的大多数数字,模数根本没有任何作用。

现在尝试 -1 % 10 (模拟这将对顶行执行什么操作)。它给你 9,表示底行。如果您运行 10 % 10 (模拟底行),它会给您 0,表示顶行。实际上,这会使表格“换行”......顶行中的单元格会影响底部,反之亦然。它还缠绕在两侧。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多