CodingBat - Warmup2 - ARRAY_FRONT9

Viewed 1130

I'm very new to programming and I'd like your expertise on a problem I've come across on CodingBat. But I am not sure why my solution doesn't work. What am I missing here?

THE PROBLEM

Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.

array_front9([1, 2, 9, 3, 4]) → True
array_front9([1, 2, 3, 4, 9]) → False
array_front9([1, 2, 3, 4, 5]) → False

MY SOLUTION

def array_front9(nums):
    for i in range(0,len(nums)):
        if len(nums)> 0 and nums[i] == 9:
            return True
        else:
            return False

SOLUTION ONLINE

def array_front9(nums):
  # First figure the end for the loop
  end = len(nums)
    if end > 4:
    end = 4

    for i in range(end):  # loop over index [0, 1, 2, 3]
        if nums[i] == 9:
            return True
        return False

Your assistance is appreciated. Thank you all.

Screenshot with the expected answers

4 Answers

Your solution is exiting prematurely with its return False line. As it's currently written, the code says, "Check the first number in the list. If it's a 9, end the function and return True. Otherwise, end the function and return False." That's what return statements do: end the function and (optionally) return something.

All you need to do to fix this is remove the else block and change the indentation of return False:

def array_front9(nums):
    for i in range(0,len(nums)):
        if nums[i] == 9:
            return True
    return False

(Your extra check for len(nums) > 0 is unnecessary since range(0, 0) will simply do nothing and the for loop will be skipped.)

By unindenting return False, that line will now run only after the for loop has completed, which is what you want. Note you'll still need to modify this code to check only the first 4 items in the array.

Also, outside of a learning context like CodingBat, in the real world Python does all of this work for you. You can just write 9 in nums[:4] and get your answer.

ANSWER UPDATE

Thanks to user JDAZ, I've come up with a working solution. Hoping this can shed some light towards beginners.

SOLUTION:

def array_front9(nums):
    for i in range(0,len(nums)):
        if nums[i] == 9 and i < 4:
            return True
    return False

enter image description here

Your code will always return False.

In your code, you create an empty list mylist and don't put anything in it. Length of such list is always 0. So, the condition in your if loop will never be true.

Solution:

def array_front9(nums):
  for i in nums[0:3]:
    if i == 9:
      return True
  return False

enter image description here

Related