尝试添加两个以字符串形式输入数字的矩阵,然后显示解决方案,但stdin和stdou有问题

2024-05-22 03:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

使用stdin输入两个矩阵,然后在stdout中显示结果,这是一个编程任务。我经常发现运行时出错,或者在程序正常运行时没有要显示的stdin或stdout

这是我的两个矩阵相加的代码

       """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
       """

请帮忙


Tags: oftheinforinputrawisrc1
1条回答
网友
1楼 · 发布于 2024-05-22 03:13:43

你可能对压痕有问题。。。我没有碰到一条线(除了调整压痕和它的预期工作!)

#!/usr/bin/env pyhton2
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()

相关问题 更多 >