1

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
0

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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, nums is [0] * 4 because it was passed in.

Then num starts as 0.

Then first4 gets set to [0, 0, 0, 0].

Then num in first4 is certainly true,

but num == 9 is definitely not true

so the and is False.

Then the if fails and the else is executed

So 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

2 Comments

Ok why is the false outside of the for loop?
Because while you're inside the for loop, you haven't checked them all! Only when you're done with the loop can you say, "I checked them all, and none of them match." Until then, you might only say, "Aha! I found a match!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.