【发布时间】:2016-09-07 09:30:59
【问题描述】:
使用标准输入输入两个矩阵然后在标准输出中显示结果是一项编程任务。当程序运行良好时,我经常发现运行时错误或没有标准输入或标准输出显示。
这是我添加两个矩阵的代码。
"""The constraint is the numbers will be entered only without any
string to be seen on console and also that to be in the same
fashion being each number input separated by a white space."""
import sys
def main():
num1 = []
num2 = []
rc1 = raw_input().split(' ')
rc1_arr = [int(z) for z in rc1]
r1 = rc1_arr[0]
c1 = rc1_arr[1]
while(r1 != 0):
mat1 = raw_input().split(' ')
arr1 = [int(z1) for z1 in mat1]
num1.append(arr1)
r1=r1-1
rc2 = raw_input().split(' ')
rc2_arr = [int(z) for z in rc2]
r2 = rc2_arr[0]
c2 = rc2_arr[1]
while(r2 != 0):
mat2 = raw_input().split(' ')
arr2 = [int(z2) for z2 in mat2]
num2.append(arr2)
r2=r2-1
for i in range(max(rc1_arr[0],rc2_arr[0])):
for j in range(max(rc1_arr[1],rc2_arr[1])):
su = num1[i][j]+num2[i][j]
sys.stdout.write(str(su))
sys.stdout.write(" ")
sys.stdout.write("\n")
main()
""" while running in idle it looks like this
##The input part is:
3 3 ## represents no. of rows and columns
1 2 3 ## This is the matrix 1 of 3*3
4 5 6
7 8 9
3 3 ## represents no. of rows and columns for second matrix
1 1 1 ## This is the matrix 2 of 3*3
1 1 1
1 1 1
## And the output is like:
2 3 4 ## Sum of the above two matrices.
5 6 7
8 9 10
"""
请帮忙。
【问题讨论】:
-
能否请您指定您想要的输入和输出。
-
@Ezio 我添加了一些注释行来显示输入和输出以查看它...
-
当两个矩阵的行数和列数相同时,您的程序似乎运行良好。如果两个矩阵的行数和列数不同,就会失败。
-
是的,代码工作正常,但我需要在标准输入和标准输出中提供输入和输出,以便在线解释器为我提供一些结果......另外,如果你已经确定了不等号的问题。行和列,请你建议一个技巧来删除它...
-
声明两个行数和列数相同的数组。行数 = max(rc1_arr[0],rc2_arr[0]) 列数 = max(rc1_arr[1],rc2_arr[1])。用 0 初始化两个数组,然后与用户一起获取条目并填充相应的单元格。没有获取任何条目的单元格将包含 0,因此添加保持不变。
标签: python matrix stdout stdin sys