ValueError: invalid literal for int() with base 10: '3 -1 1 14'

62 Views Asked by At

ValueError: invalid literal for int() with base 10: '3 -1 1 14'

I got this error. Actually I am trying to take a stream of n integers separated by whitespace as input without any list or dict, but I am new to python.

The input is:

4
3 -1 1 14

It is a question requirement to do it without any list / set / dictionary comprehension.

The question states:

Description

  1. We want you to calculate the sum of squares of given integers, excluding any negatives. The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.
  2. Each of the test cases will consist of a line with an integer X (0 < X <= 100), followed by another line consisting of X number of space-separated integers Yn (-100 <= Yn <= 100).
  3. For each test case, calculate the sum of squares of the integers, excluding any negatives, and print the calculated sum in the output.
  4. Note: There should be no output until all the input has been received.
  5. Note 2: Do not put blank lines between test cases solutions.
  6. Note 3: Take input from standard input, and output to standard output.

Specific rules for Python solution

  1. Your source code must be a single file, containing at least a main function
  2. Do not use any for loop, while loop, or any list / set / dictionary comprehension
  3. Your solution will be tested against Python 3.11 (as of February 2023) or higher

I tried to take input using recursion but got stuck in whitespace and got the same error. I wonder if I take it as string input and then convert them to numbers would that work?

Here is my code:

def helper2(n: int, sum: int):
    m = int(input()).split()
    if m > 0:
        sum += m * m
    else:
        sum += 0
    helper2(n - 1, sum)

def helper(n: int):
    if n == 0:
        return 0
    m = int(input())
    sum = 0
    helper2(m, sum)
    helper(n - 1)
    return sum

def main():
    n = int(input())
    sum = helper(n)
    print(sum)

if __name__ == "__main__":
    main()

I know that the input in python is taken as a string or list (for arrays) but we can't use any loop or list, dict comprehension I am confused is there any other way to take the array as input.

1

There are 1 best solutions below

1
Maxi H. On
def main():
    n: int = int(input())
    input_str: str = input()
    final_sum: int = add(n - 1, 0, input_str)
    print(final_sum)

def add(n: int, sum_of_ints: int, input_str: str):
    # turning the input_str int a list of ints and taking the value at location n
    x: int = list(map(int, input_str.split()))[n]
    
    # adding x to the sum
    if x > 0:
        sum_of_ints += x ** 2
        
    # calling the add function and setting the sum to its output
    if n > 0:
        sum_of_ints = add(n - 1, sum_of_ints, input_str)
        
    # returning the output
    return sum_of_ints


if __name__ == "__main__":
    main()