Home > Back-end >  Program that reads a series of lines, each one with positive integers, and outputs the sum of the fi
Program that reads a series of lines, each one with positive integers, and outputs the sum of the fi

Time:11-02

Write a program that reads a series of lines, each of them containing a sequence of non negative integers, and prints as output the value of the sum of the first line that contains an even number of elements ending in 3. If there is no such line, the output will be -1.

For instance, for the input:

23 12 4 25
44 43 23 3 12 8
33 4 9 73 14
88 92 55

The output would be 133, because the third line contains 2 numbers ending in 3 (33 and 73), and the previous lines contained an odd number of such elements (1 and 3 respectively). Thus, the third line is the first with an even number of elements ending in 3. The sum of the element of this line is 33 4 9 73 14 = 133

So, in conclusion:

  • Input is a series of lines with numbers. Each line contains at least one number.
  • Output is the sum of the elements in the first line that happens to have an even number of elements ending in 3, or -1 if there is no such line.

My try far now is:

import sys
line = sys.stdin.read().split()
# even number of elements ending in 3
for i in range(len(line)): # Make str input int
    line[i] = int(line[i])

print(line)

With this all integer input in different lines is stored in a single list. But how I am able to distinguish which integers are from line 1? or 2? Solution needs to be with the import sys parameter. My question is about how to treat the input. How can I store values from each line in a list for each?

UPDATE: I was trying some things, not the result for the question but maybe clears what I want.

import sys
line = sys.stdin.readline().split() # ['23', '12', '4', '25']
while line != '':
    lista_numb = []
    for i in line:
        if i.endswith('3'):
            lista_numb.append(i)
    print(lista_numb)
    line = sys.stdin.readline().split()
if len(lista_numb)%2 == 0: # even
    print(sum(line))

CodePudding user response:

OK, first you need to know what sys.stdin.read() type --> This is a string.

Related: What does sys.stdin read?

sys.stdin is similar to a file reader.

For your problem, we can use

lines = sys.stdin.readlines()

This will automatically split your input into a list of string.

You could also use:

lines = sys.stdin.read()
lines = lines.split("\n")

With \n is a special character for new line (or Enter).

Then try to solve your problem from here.

CodePudding user response:

Try:

import sys
while True:
    # Read a line from stdin and skip the new line character at end of the line
    line = sys.stdin.readline().strip('\n')
    if line == "":
        print(-1)
        break
    nums = line.split() # split on white space characters
    # Calculate amount of numbers ending with '3'
    nums_endingwith_3 = sum(1 for num in nums if num.endswith('3'))
    if nums_endingwith_3 > 0 and nums_endingwith_3 % 2 == 0:
        print( sum(int(num) for num in nums) )
        break # exit the while True loop

The code above enters an endless loop ( while True: ) of getting single lines of input from stdin with sys.stdin.readline().strip('\n') strips the new line at the end of the input-string as .readline() returns lines including new line character.

This answers your question of how to get single lines of input.

In the endless loop the break command stops the loop run after detection of a line with an even number of numbers ending with '3'. The line before the break prints the requested sum and if there is some further code after the loop body code block it will be executed as break not only stops the loop but also causes an exit from the loop body code block.

The if line == "": condition prints -1 if no line satisfies the condition of even occurrences of ending with '3' and exits the loop with break.

Notice that you need to test if the amount of found numbers ending with '3' is greater than zero to avoid getting a wrong result in case no number ends with '3'. This is required because 0 % 2 == 0 is True .

If you want to separate the input and its processing you need to collect all the input first in a list of input lines and then process the lines as done in following code:

import sys

lines = []
while True:
    line = sys.stdin.readline().strip('\n')
    if line == "":
        break # end of data input, exit the loop
    lines.append(line)

found_sum = None
for line in lines: 
    nums = line.split() # split on white space characters
    # Calculate amount of numbers ending with '3'
    nums_endingwith_3 = sum(1 for num in nums if num.endswith('3'))
    if nums_endingwith_3 > 0 and nums_endingwith_3 % 2 == 0:
        found_sum = sum(int(num) for num in nums)
        break # exit the loop

if found_sum != None: 
    print( found_sum )
else:
    print(-1)
  • Related