如何求矩形的周长?
在下面的示例中它可以工作,但如果我将 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
) 和 x1
、y1
等的当前值,您的墙也不正确(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}
我是一名优秀的程序员,十分优秀!