Reputation: 301
I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2").
The problem is: "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."
Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):
arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:
def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
Here is the solution according to codingbat.com:
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
Here is the current URL for this problem: http://codingbat.com/prob/p110166
Can anyone point me to what I'm doing wrong?
Upvotes: 3
Views: 1458
Reputation: 174624
The problem is "check the first four numbers of a list, to see if any of them is a 9".
Now, if the list is less than 4, then automatically the check will fail:
if len(arr) < 4:
return false
Next, you need to check if the first four items contain nine. There are many ways to do this, one of the easiest is:
for i in arr[:4]:
if i == '9':
return true
Combine the two:
def check_for_nine(arr):
if len(arr) < 4:
return false
for i in arr[:4]:
if i == '9':
return true
The issue with your initial approach is you are forcing the length to be 4, and assuming that at minimum the array will have 4 elements. If the array has 3 elements, then your code will not work.
To avoid this, don't assume a specific length. If you use slicing, then you are guaranteed that you will get at most 4 items.
Here is an example of this:
>>> i = [1,2]
>>> i[:4]
[1, 2]
Even though i
only has two items, the slice to 4 works and doesn't raise an error. Once i
has more than 4 items, it will limit to the first four:
>>> i = [1,2,3,4,5,6,7,8]
>>> i[:4]
[1, 2, 3, 4]
However, our problem statement specifically said that check if the first four items contain 9. If we just use the slice trick, like this:
for i in arr[:4]:
if i == '9':
return true
It will return true even if we pass it an array like ['1','9']
since the slice will always work.
To catch this condition - we first check if the length of the list is less than 4, because if it is - it automatically fails the condition.
Upvotes: 0
Reputation: 301
Thank you for all your answers, they have been really helpful!
I decided to use the IF loop instead of the FOR loop, like this:
def array_front9(arr):
if 9 in arr[0:4]:
return True
return False
As much as I can see, this solution works no matter what the length of the list is, and it seems like it fits the definition of the problem i.e. "no matter what the length of the list is, if any of the first four elements equals 9, return True".
Upvotes: 0
Reputation: 4441
Easier solution for this problem would be:
if len(arr) > 4:
if 9 in arr[0:4]:
return True
else:
return False
else:
print('Array length is shorter than 4')
return False
If you want to check for 9, even if the list length is less than 4, then below is the solution:
def check(arr):
max = 4 if len(arr) >= 4 else len(arr)
if 9 in arr[0:max]:
return True
else:
return False
print check(arr)
Upvotes: 0
Reputation: 46669
You have to get the minimum checking length of the input list:
def array_front9(nums):
return 9 in nums[:min(4,len(nums))]
Upvotes: 0
Reputation: 13510
Simply test this expression:
9 in arr[:4]
I explain:
As others have pointed out, your array might be shorter than 4 items, in which case indexing at, say 3
, the fourth number, will raise an IndexError
.
But let's use the feature that slicing
won't raise an exception, that is:
In [232]: a = [1, 2]
In [233]: a[:10]
Out[233]: [1, 2]
In the above example I took a slice from the beginning of the array up until the 10'th item, and didn't get an exception, but Python returned the entire list.
Thus, you could do the check as simply as:
9 in arr[:4]
and that's all!
Upvotes: 1
Reputation: 728
It is given in the problem that the array length may be less than 4. Your are just iterating over an array. You should first check whether the array
is at least of length 4
. If the array
is less than 4 then only iterate through the length of the array
.
n = 4
if len(arr) < 4:
n = len(arr)
for i in range(n):
#...Your code...
Upvotes: 2
Reputation: 2088
You use range(4)
. So it will always look for 4 numbers. So when there are only three numbers it will still look for a fourth one. The fourth one doesn't exist so it throws an error.
Instead you need to see what the lenght of the list is and then iterate over that lenght.
Like this:
for i in range(len(arr)):
if arr[i] == 9:
Or even simpler you can iterate over a list like this:
for list_item in arr:
if list_item == 9: # you don't even have to use the [i]
Upvotes: 0
Reputation: 8600
The problem states "The array length may be less than 4." Your code currently assumes the array is at least length 4. However, if i
is greater than the last index of the list, an IndexError
will be thrown.
You should first check if len(arr) < 4
and return False
if so.
Upvotes: 1