iratxe - 5 months ago 23

Python Question

I have a exercise ,Input data will contain the total count of pairs to process in the first line.

The following lines will contain pairs themselves - one pair at each line.

Answer should contain the results separated by spaces.

My code:

`n = int(raw_input())`

sum = 0

for i in range(n):

y = raw_input().split(" ")

for i in y:

sum = sum + int(i)

print sum

With my code , I come the Sum together, but I will that the results to come separated by spaces . Thanks for yours help .

Answer

with your current code what you get is the total sum of all the given numbers, to get the sum per line you need to initialize your counter in the outer loop, and then print it, and as you want to print all it in the same line there are several ways to do it, like save it in a list or telling print that don't print a new, line which is done by adding a `,`

at the end like `print x,`

with that in mind then the changes needed are

```
n = int(raw_input())
for i in range(n):
pairs = raw_input().split() #by default split use spaces
pair_sum = 0
for p in pairs:
pair_sum += int(p) # a += b is the same as a = a + b
print pair_sum,
print "" # to print a new line so any future print is not done in the same line as the previous one
```

that was the version with print per line, next is the version using list

```
n = int(raw_input())
resul_per_line = []
for i in range(n):
pairs = raw_input().split() #by default split use spaces
pair_sum = 0
for p in pairs:
pair_sum += int(p) # a += b is the same as a = a + b
resul_per_line.append( str(pair_sum) ) #conver each number to a string to use with join bellow
print " ".join(resul_per_line)
```

with either of the above let said for example that the input data is

```
3
1 2
40 50
600 700
```

then the result would be

```
3 90 1300
```

some parts of the above code can be simplify by using built in functions like `map`

and `sum`

, for example this part

```
pair_sum = 0
for p in pairs:
pair_sum += int(p)
```

can become

```
pair_sum = sum( map(int,pairs) )
```