模式
你只得到一個正方形的邊長:
- 邊長總是 = ODD。
- 正方形的中間值ALWAYS = 0。
- 每隔一個值 =到正方形中心的距離。
撰寫一個程式來概括這個演算法,并通過輸出一個串列串列來創建輸入方塊的串列表示
示例輸出
"""
if input = 1
Matching square: 0 => List Equivalent = [[0]]
if input = 3
Matching square: 1 1 1 => List Equivalent = [[1, 1, 1],
1 0 1 [1, 0, 1],
1 1 1 [1, 1, 1]]
if input = 5
Matching square: 2 2 2 2 2 => List Equivalent = [[2, 2, 2, 2, 2],
2 1 1 1 2 [2, 1, 1, 1, 2],
2 1 0 1 2 [2, 1, 0, 1, 2],
2 1 1 1 2 [2, 1, 1, 1, 2],
2 2 2 2 2 [2, 2, 2, 2, 2]]
if input = 7
Matching square: 3 3 3 3 3 3 3 => List Equivalent = [[3, 3, 3, 3, 3, 3, 3],
3 2 2 2 2 2 3 [3, 2, 2, 2, 2, 2, 3],
3 2 1 1 1 2 3 [3, 2, 1, 1, 1, 2, 3],
3 2 1 0 1 2 3 [3, 2, 1, 0, 1, 2, 3],
3 2 1 1 1 2 3 [3, 2, 1, 1, 1, 2, 3],
3 2 2 2 2 2 3 [3, 2, 2, 2, 2, 2, 3],
3 3 3 3 3 3 3 [3, 3, 3, 3, 3, 3, 3]]
"""
我正在嘗試一個我將發布的解決方案,該解決方案將正方形不均勻地分割為 0 左右,如下所示:
side = 5 _ _ _ _ _ _
Matching square: 2 2 2 2 2 Split square: 2 1 0 1 2
2 1 1 1 2 2 1 1 1 2
2 1 0 1 2 2 2 2 2 2
2 1 1 1 2
2 2 2 2 2
并弄清楚如何根據與頂行的距離等生成每一行
問題
我正在嘗試解決的這種模式/問題的任何現有解決方案?我不知道要搜索什么
uj5u.com熱心網友回復:
一種相對簡單但不優雅的方法是將矩陣從外向內螺旋,并為每個新周期遞減值。如下:
def create_matrix(n):
curr = n // 2
matrix = [[0]*n for _ in range(n)]
counter = 0
N = n*n
left, right, top, bottom = 0, n-1, 0, n-1
while True:
# top
for i in range(left, right 1):
matrix[top][i] = curr
counter = 1
top = 1
if counter >= N:
break
# right
for i in range(top, bottom 1):
matrix[i][right] = curr
counter = 1
right -= 1
if counter >= N:
break
# bottom
for i in range(left, right 1):
matrix[bottom][i] = curr
counter = 1
bottom -= 1
if counter >= N:
break
# left
for i in range(top, bottom 1):
matrix[i][left] = curr
counter = 1
left = 1
if counter >= N:
break
curr -= 1
return matrix
快速測驗:
In [2]: create_matrix(11)
Out[2]:
[[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5],
[5, 4, 3, 3, 3, 3, 3, 3, 3, 4, 5],
[5, 4, 3, 2, 2, 2, 2, 2, 3, 4, 5],
[5, 4, 3, 2, 1, 1, 1, 2, 3, 4, 5],
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5],
[5, 4, 3, 2, 1, 1, 1, 2, 3, 4, 5],
[5, 4, 3, 2, 2, 2, 2, 2, 3, 4, 5],
[5, 4, 3, 3, 3, 3, 3, 3, 3, 4, 5],
[5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5],
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]]
In [3]: create_matrix(5)
Out[3]:
[[2, 2, 2, 2, 2],
[2, 1, 1, 1, 2],
[2, 1, 0, 1, 2],
[2, 1, 1, 1, 2],
[2, 2, 2, 2, 2]]
uj5u.com熱心網友回復:
以更簡單的方式解決
square_size = 11
centre_x = (square_size - 1) // 2
centre_y = (square_size - 1) // 2
matrix = []
for x in range(square_size):
row = []
for y in range(square_size):
x_dif = abs(x - centre_x)
y_dif = abs(y - centre_y)
value = max(x_dif, y_dif)
row.append(value)
matrix.append(row)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/388167.html
下一篇:根據另一個陣列和條件過濾一組物件
