python - 如何获得船上创建的矩形的周长

标签 python python-2.7

如何求矩形的周长?

在下面的示例中它可以工作,但如果我将 x1、y1、x2、y2 更改为不同的值或使板更大,我从墙函数获得的坐标是错误的。墙功能有什么问题?

board_width = 8
board_height = 8
board = []

for line in range(0, board_height):
    lst = []
    for i in range(0, board_width):
        lst.append("x")
    board.append(lst)

#         X  Y  X2 Y2
# rect = [2, 4,  5, 7]
x1 = 2
y1 = 4
x2 = 5
y2 = 7


def create_rect():
    # go through the tiles in the rectangle and make them passable
    for x in range(x1, x2):
        for y in range(y1, y2):
            board[y][x] = " "

create_rect()

for i in board:
    for x in i:
        print x,
    print
print

# x1 = 1    y1 = 2      x2 = 4      y2 = 5
# answer
# x,y
# top wall --------
# 3,1 / 3,2 / 3,3 / 3,4 / 3,5 /
# lef wall |    |
# 1,3 / 1,4 / 1,5 / 1,6 / 1,7 /
# rgh wall |    |
# 5,3 / 5,4 / 5,5 / 5,6 / 5,7 /
# bot wall --------
# 1,7 / 2,7 / 3,7 / 4,7 / 5,7 /


def walls(x1, y1, x2, y2):
    flst = []
    lst = []
    # top wall
    for i in range(x1-1, x2+1):
        lst.append((x1+1, i))
    flst.append(lst)
    lst = []

    # left wall
    for i in range(y1-1, y2+1):
        lst.append((x1-1, i))
    flst.append(lst)
    lst = []

    # right wall
    for i in range(y1-1, y2+1):
        lst.append((x2, i))
    flst.append(lst)
    lst = []

    # bottom wall
    for i in range(x1-1, x2+1):
        lst.append((i, y2))
    flst.append(lst)

    return flst

nlst = walls(x1, y1, x2, y2)

for i in nlst:
    print i

最佳答案

添加一些代码以在视觉上覆盖板顶部的墙壁:

for points in nlst:
    for x, y in points:
        v = board[y][x]
        v = '+' if v == '.' else '.'
        board[y][x] = v

然后在最后打印板子。您会发现,即使使用板尺寸 (8 x 8) 和 x1y1 等的当前值,您的墙也不正确(2、4、5、7)。

然后注释掉 walls() 的不同部分以隔离问题。换句话说,一次只需组装一堵墙,然后打印只有一堵墙的板。你会发现问题出在顶墙上。它看起来像这样:

x x x x x x x x
x x x . x x x x
x x x . x x x x
x x x . x x x x
x x   .   x x x
x x   .   x x x
x x       x x x
x x x x x x x x

并且您可以按照以下方式大大简化walls():

def walls(x1, y1, x2, y2):
    xs = range(x1 - 1, x2 + 1)
    ys = range(y1 - 1, y2 + 1)
    return [
        [(x, y1 - 1) for x in xs],  # top
        [(x, y2) for x in xs],      # lft
        [(x1 - 1, y) for y in ys],  # rgt
        [(x2, y) for y in ys],      # bot
    ]

    # Even better: return a dict-of-lists so the data
    # structure would be self documenting.
    # {'top': [...], 'bot': [...], etc}

关于python - 如何获得船上创建的矩形的周长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42332054/

相关文章:

python - SQLAlchemy 和空 IN 子句

python - Pandas DataFrame 重置缓存

python - Numpy reshape 产生不同的大小错误

python - PySpark 广播变量连接

python - 使用 Python 将空文件夹附加到 KML 文件中的现有文件夹

python - 正则表达式没有抓取所有组,不能在多行中工作

python - 如何抑制正在导入的模块的标准输出日志输出?

python - 在 python 中从 excelsheet 中读取特定的单元格值

python - Distutils 编译器选项配置

django - 在 Django 表单中的两个字段中将一个字段设置为必填字段