Mythic-ctrl
Mythic-ctrl

Reputation: 37

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. 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

Upvotes: 1

Views: 121

Answers (2)

aghast
aghast

Reputation: 15300

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

Upvotes: 0

blhsing
blhsing

Reputation: 106488

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]

Upvotes: 1

Related Questions