Impact of python numArray calculation on print line

I wrote two sets of codes

Set 1:

numArray = map(int, input('input content:').split())
print('numArray is', list(numArray))

sum_integer = 0
for number in numArray:
    sum_integer += number*number

print('sum is:', sum_integer)

Install 2:

numArray = map(int, input('input content:').split())

sum_integer = 0
for number in numArray:
    sum_integer += number*number

print('sum is:', sum_integer)

You can see that it is to create a set of numbers by entering and then calculating the sum of the square for each number. The difference between Set 1 and Set 2 is just a lineprint()

Suppose I entered: 4 7 2 8 5for both sets

for Set 1: I get:

numArray is [4, 7, 2, 8, 5]
sum is: 0

for Set 2: I get:

sum is 158

How could one line print()change the logic of calculation?

+4
source share
2 answers

mapreturns an iterator. By calling list, you consume it, leaving it empty for the following code. If you want to reuse a sequence of numbers several times (for example, for printing and then summing), you can save the list:

numArray = list(map(int, input('input content:').split()))
+3

@Mureinik answer, - , one-line sum:

sum_integer = sum(n ** 2 for n in numArray)

code one-line:

sum_integer = sum(int(n) ** 2 for n in input('input content:'))
+2

Source: https://habr.com/ru/post/1688348/


All Articles