[英]How do I iterate through part of an array and why doesn't my loop work?
If the number 9 is in the first 4 digits of the input array, it should return True.如果数字 9 在输入数组的前 4 位,它应该返回 True。 The array length may be less than 4.
数组长度可能小于 4。
Why doesn't this loop work?为什么这个循环不起作用? It only returns True and False in some test cases.
它仅在某些测试用例中返回 True 和 False。
def array_front9(nums):
for num in nums:
first4 = nums[0:4]
if num in first4 and num == 9:
return True
else:
return False
You don't need a for
loop since the in
operator would iterate through the characters of a string for you.您不需要
for
循环,因为in
运算符会为您遍历字符串的字符。 You should also compare a string to a string, rather than a number, which would never be equal to a string:您还应该将字符串与字符串进行比较,而不是数字,它永远不会等于字符串:
def array_front9(nums):
return '9' in nums[0:4]
A good first question is, "what does 9 mean"?一个好的第一个问题是,“9 是什么意思”?
If you have an array of numbers read from the command line, or from user input, then the "9" is likely the character "9", which is ASCII code 57, or unicode code point U+0039.如果您有从命令行或用户输入读取的数字数组,则“9”可能是字符“9”,即 ASCII 代码 57,或 unicode 代码点 U+0039。
On the other hand, if you have actual integers in your array, then you are likely dealing with the integer value 9 (which would be an ASCII TAB character).另一方面,如果您的数组中有实际整数,那么您可能会处理 integer 值 9(这将是一个 ASCII TAB字符)。
Second, you are too impatient!第二,你太不耐烦了!
Consider this input: [0, 0, 0, 0]
.考虑这个输入:
[0, 0, 0, 0]
。
What happens?怎么了?
def array_front9(nums):
for num in nums:
first4 = nums[0:4]
if num in first4 and num == 9:
return True
else:
return False
Well,
nums
is[0] * 4
because it was passed in.嗯,
nums
是[0] * 4
因为它被传入了。Then
num
starts as0
.然后
num
从0
开始。Then
first4
gets set to[0, 0, 0, 0]
.然后
first4
设置为[0, 0, 0, 0]
。Then
num in first4
is certainly true,那么
num in first4
肯定是真的,but
num == 9
is definitely not true但是
num == 9
绝对不是真的so the
and
isFalse
.所以
and
是False
。Then the
if
fails and theelse
is executed然后
if
失败,执行else
So your code executes a
return False.
因此,您的代码执行
return False.
But that's wrong!但这是错误的!
Because it happened while you were still looking at the very first value in the array.因为它发生在您仍在查看数组中的第一个值时。 You never checked the other values, because you
return False
too soon.您从未检查过其他值,因为您
return False
太快了。
You are permitted to do a pre-emptive return when you know the result -- when you find a 9 in the first 4 places.当你知道结果时——当你在前 4 个地方找到一个 9 时,你被允许做一个先发制人的回报。 But if you are going to scan over each of the 4 places, you cannot return false until you finish your scanning.
但是,如果您要扫描 4 个位置中的每一个,则在完成扫描之前不能返回 false。
Something like this:像这样的东西:
for num in nums[0:4]:
if num == 9:
return True
# Note: this is after the for loop
return False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.