这里有一个从左上到右下的单位矩阵。我试着翻转它,这样我就可以从右上角到左下角得到一排1,但我不想使用numpy。但我就是不知道怎么做…
num = int(input("enter your number"))
for i in range(0, num):
for j in range(0, num):
if (i == j):
print(1, sep=" ", end=" ")
else:
print(0, sep=" ", end=" ")
print()
示例:
输入:4
输出:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 1
column
、row
和num
之间存在简单的关系
if i + j + 1 == num:
完整代码:
num = int(input("enter your number"))
for i in range(0, num):
for j in range(0, num):
if i + j + 1 == num:
print(1, sep=" ", end=" ")
else:
print(0, sep=" ", end=" ")
print()
编辑:
另一个想法是逆转一个范围
for j in range(num-1, -1, -1):
完整代码:
num = int(input("enter your number"))
for i in range(0, num):
for j in range(num-1, -1, -1):
if i == j:
print(1, sep=" ", end=" ")
else:
print(0, sep=" ", end=" ")
print()
要创建反对角矩阵,请在每个(行,列(中放入1,其中column=n-1-行:
def anti_diagonal(n):
"""Return the n x n antidiagonal matrix as a list of lists. """
return [ [ 0 if column != n-1 - row else 1 for column in range(n)
] for row in range(n) ]