0

I am very new to coding, two weeks in. So I do apologize if this is a very silly question.

I have been trying to complete the following codingbat 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.

Why does the below code not return the correct answer?

def array_front9(nums):
  if len(nums)>4:
    count = 4
  else:
    count = len(nums)

  for i in range(0,count):
    if nums[i]==9:
      return True
    else:  
      return False

If the return False is placed on a new line and not in the loop it works.

Can someone please explain this to me.

Sociopath
  • 13,068
  • 19
  • 47
  • 75

3 Answers3

2

On the first iteration of the loop, the loop checks if nums[0] is 9 and always returns either True or False; you're not giving any chance for the rest of the elements to be inspected. You should only return True if the element being inspected is 9, and return False only when this fails for the first four elements, i.e. outside the loop.

def array_front9(nums):
    return 9 in nums[:4]
fractals
  • 816
  • 8
  • 23
1

I think you need:

def array_front9(nums):
    count = 4
    if len(nums)<4:
        count = len(nums)
    if 9 in nums[:count]:
        return True
    return False

What's wrong with your code

if nums[i]==9:
      return True
else:  
      return False

In above lines you're just checking for 1st value if it is 9 then it returns True else False

Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

The problem in your code is if the first number in your list is not 9 then the loop will stop and function execution will stop it's because of return False in else condition.

def array_front9(nums):
  count = [len(nums), 4][len(nums) > 5]
  for i in range(count):
    if nums[i] == 9:
      return True
  return False
deadshot
  • 8,881
  • 4
  • 20
  • 39