If the number 9 is in the first 4 digits of the input array, it should return True. The array length may be less than 4.
Why doesn't this loop work? It only returns True and False in some test cases.
def array_front9(nums):
for num in nums:
first4 = nums[0:4]
if num in first4 and num == 9:
return True
else:
return False
2 Answers 2
You don't need a for loop since the in operator would iterate through the characters of a string for you. 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]
Comments
A good first question is, "what does 9 mean"?
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.
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).
Second, you are too impatient!
Consider this input: [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,
numsis[0] * 4because it was passed in.Then
numstarts as0.Then
first4gets set to[0, 0, 0, 0].Then
num in first4is certainly true,but
num == 9is definitely not trueso the
andisFalse.Then the
iffails and theelseis executedSo your code executes a
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.
You are permitted to do a pre-emptive return when you know the result -- when you find a 9 in the first 4 places. But if you are going to scan over each of the 4 places, you cannot return false until you finish your scanning.
Something like this:
for num in nums[0:4]:
if num == 9:
return True
# Note: this is after the for loop
return False