如何获得矩形的周长?
在下面的示例中,它可以工作,但是如果我将x1,y1,x2,y2更改为不同的值或使板更大,则我从wall函数获得的坐标是错误的。墙壁功能有什么问题?
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}
关于python - 如何获得在板上创建的矩形的周长,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42332054/