不确定下面的代码中输入是如何分割的。

huangapple go评论67阅读模式
英文:

Not sure how the input is broken up in below code

问题

N, M = map(int, input().split())
A = numpy.array([input().split() for _ in range(N)],int)
print(numpy.prod(numpy.sum(A, axis=0), axis=0))

英文:

So I have the problem which is that I have an array of dimensions N x M and I have to find the sum of array=0 and then find the product of the result.

E.g. for:
1 2 \n
3 4

It would be 1+3 and 2+4 = 4 6 -> and the product of this is 4*6 = 24

I know that the correct code is:

`import numpy
N, M = map(int, input().split())
A = numpy.array([input().split() for _ in range(N)],int)
print(numpy.prod(numpy.sum(A, axis=0), axis=0))`

However I am confused because the sample input is:
2 2
1 2
3 4

With output:
24

The first line 2 2 is the dimensions of the array (N,M) and the 2nd and 3rd lines are the array values. My question is how does the code know to split the input() so that in the 2nd line of the code the input is: 2 2
And in the third line of the code the input is: 1 2
3 4

When I try this code:

`import numpy as np
input_str = '2 2\n1 2\n3 4\n'
N,M = map(int, input_str.split())
print(N,M)`

I get the error: ValueError: too many values to unpack (expected 2)

Which I take to mean that it expected '2 2' in input_str in the 3rd line

However, when I split it into 2 separate inputs:

`import numpy as np
input_1 = '2 2'
input_2 = '1 2\n3 4'
N, M = map(int, input_1.split())
my_arr = [list(map(int, input_2.split())) for _ in range(N)]
print(np.prod(np.sum(my_arr, axis=0)))`

I get output: 384 which is not what I'm wanting.

Question is from this site: https://www.hackerrank.com/challenges/np-sum-and-prod/problem

Thanks for your assistance!

答案1

得分: 1

I guess you are spitting the input incorrectly. You should divide the second input line (input_2) into N lists, each containing M elements, as opposed to dividing it into a single list.

import numpy as np

input_1 = '2 2'
input_2 = '1 2\n3 4'
N, M = map(int, input_1.split())
my_arr = [list(map(int, input_2.split()))[i:i+M] for i in range(0, len(input_2.split()), M)]
print(np.prod(np.sum(my_arr, axis=0)))

Maybe this piece of code might help.

英文:

I guess you are spitting the input incorrectly. You should divide the second input line (input_2) into N lists, each containing M elements, as opposed to dividing it into a single list.

import numpy as np

input_1 = '2 2'
input_2 = '1 2\n3 4'
N, M = map(int, input_1.split())
my_arr = [list(map(int, input_2.split()))[i:i+M] for i in range(0, len(input_2.split()), M)]
print(np.prod(np.sum(my_arr, axis=0)))

Maybe this piece of code might help.

huangapple
  • 本文由 发表于 2023年4月13日 17:08:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76003670.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定