I'm somewhat new to python and I'm practicing on a website called "geeks for geeks". Here is a link to the problem I'm working on. The goal of the exercise is to print the first negative integer in a sub array of user specified size. When I try to append the user inputs to the list, the interpreter is giving me a value error. It's obviously not a type error but I can't figure out what kind of input could be given to the program to give it that error. The inputs are on a file on geeks for geek's servers so I can only test on inputs I've made.
# This file is for a programing practice exercise of geeksforgeerks.org
# The exercise is first negative int in window of size k
# selecting number of test cases
T = int(input())
for t in range(T):
# initializing array
n = int(input())
arr = []
while n > 0:
arr.append(int(input().strip()))
n-=1
k = int(input())
win = 0 # index of first element in widow subarray
# terminate loop when the window can't extend further
while win < len(array) - k -1:
# boolean for no negatives found
noNeg = True
for i in range(win, k):
if arr[i] < 0:
print(arr[i])
noNeg = False
break
elif i == k-1 and noNeg:
# 0 if last sub arr index reached and found no negs
print(0)
win+=1
The interpreter is giving the following error on line 11:
print(int(input().strip()))
ValueError: invalid literal for int() with base 10: '-8 2 3 -6 10'
The input data contains multiple numbers on the same line. input()
returns a whole line of input, and when you call int(input().strip())
you're trying to parse that whole line as a single number.
You need to split it at whitespace. So instead of a while
loop, you can use:
arr = map(int, input().strip().split())