我遇到过一个类似的问题,解决方案是一个while循环,它从未满足其结束条件,但这一次我在另一个for循环中使用了嵌套的for循环,并且看不出它是否是无限循环。有没有人能帮我看看我错过了什么。我有一个终端的screenshot,你可以看到只有一个空行表明它仍在运行。代码如下:
import stdarray
import stdio
# Entry point (DO NOT EDIT).
def main():
a = stdarray.readFloat2D()
c = _transpose(a)
for row in c:
for v in row[:-1]:
stdio.write(str(v) + ' ')
stdio.writeln(row[-1])
# Returns the transpose of a.
def _transpose(a):
# Get the dimensions of matrix a.
m = len(a) # number of rows in a
n = len(a[0]) # number of columns in a
# Create an n-by-m matrix c with all elements initialized to 0.0.
c = stdarray.create2D(n, m, 0)
# Fill in the elements of c such that c[i][j] = a[j][i], where 0 <= i < n and 0 <= j < m.
for i in range(n):
for j in range(m):
c[i][j] = a[j][i]
# Return c.
return c
if __name__ == '__main__':
main()
发布于 2021-04-05 10:03:02
我想这来自于我在谷歌上找到的https://introcs.cs.princeton.edu/python/code/
如果查看stdarray.py中的代码,就会发现在调用stdarray.readFloat2D()
时,输入的行数和列数需要2个整数(每次一个),然后n
会用浮点数来填充该矩阵。因此,如果输入3和4作为行和列,则需要输入12个浮点数来填充矩阵
def readFloat2D():
"""
Read from sys.stdin and return a two-dimensional array of floats.
Two integers at the beginning of sys.stdin define the array's
dimensions.
"""
rowCount = stdio.readInt()
colCount = stdio.readInt()
a = create2D(rowCount, colCount, 0.0)
for row in range(rowCount):
for col in range(colCount):
print(f'row {row} col {col}')
a[row][col] = stdio.readFloat()
return a
运行该程序的示例:
2
3
4.3
2.5
6.7
4.5
7.8
2.0
2 3
4.3 2.5 6.7
4.5 7.8 2.0
最后3行是输出,其余是输入。
https://stackoverflow.com/questions/66947315
复制相似问题