Home > Software engineering >  Different lines of input and output in Python
Different lines of input and output in Python

Time:03-13

I'm currently trying to solve the max value problem. However, I'm now having a hard time getting many outputs at the same time. I try to use input().splitlines() to do it, but I only get one output. The test case and output need to have many lines just as the box's examples. If anyone can provide me with some assistance, I would be very much appreciated it.

Example:
Input:
1,2,3
4,5,6
7,8,9

output:
3 
6
9

for line in input().splitlines():

   nums = []
   for num in line.split(','):
       nums.append(int(num))
       print(nums)
   max(nums) 

CodePudding user response:

input does not handle multiline, you need to loop. You can use iter with a sentinel to repeat the input and break the loop (here empty line).

nums = []
for line in iter(input, ''):
    nums.append(max(map(int, line.split(','))))
print(nums)

example:

1,2,3
4,5,6
7,8,9

[3, 6, 9]

NB. this code does not have any check and works only if you input integers separated by commas

CodePudding user response:

Can you try this out?

max_list = []

while True: #loop thru till you get input as input() reads a line only
    line_input = input() #read a line
    if line_input: #read till you get input.
        num_list = []
        for num in line_input.split(","):  #split the inputs by separator ','
            num_list.append(int(num))  # convert to int and then store, as input is read as string
        max_list.append(max(num_list))
    else:
        break #break when no input available or just 'Enter Key'

for max in max_list:
    print(max)

  • Related