[英]Initializing list of ints. Interpreter returns “ValueError: invalid litteral for int()”
I'm somewhat new to python and I'm practicing on a website called "geeks for geeks".我对 python 有点陌生,我正在一个名为“geeks for geeks”的网站上练习。 Link to the problem I'm working on here The goal of the exercise is to print the first negative integer in a sub array of user specified size.
链接到我正在处理的问题练习的目标是在用户指定大小的子数组中打印第一个负数 integer。 When I try to append the user inputs to the list, the interpreter is giving me a value error.
当我尝试将用户输入到列表中的 append 时,解释器给了我一个值错误。 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:解释器在第 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. input()
返回一整行输入,当您调用int(input().strip())
时,您试图将整行解析为单个数字。
You need to split it at whitespace.您需要在空白处拆分它。 So instead of a
while
loop, you can use:因此,您可以使用以下命令代替
while
循环:
arr = map(int, input().strip().split())
Looks like you're inputting multiple integers, int()
won't know how to convert them - it expects a single integer to be contained in the string.看起来您正在输入多个整数,
int()
不知道如何转换它们 - 它希望字符串中包含单个 integer 。 You'll want to split up the string and then convert:您需要拆分字符串然后转换:
Ts = [int(word) for word in input().strip().split(" ")]
Note that this will give you a list instead of a single integer.请注意,这将为您提供一个列表,而不是单个 integer。
you are feeding the input with multiple integers, you can extend your array at line 11 with your desired values:您正在为输入提供多个整数,您可以在第 11 行使用所需的值扩展您的数组:
arr = []
arr.extend(map(int, input().strip().split()))
# input: -8 2 3 -6 10
output: output:
[-8, 2, 3, -6, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.