-3

The question is as follows: Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.

has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False

This is my answer:

def has_33(nums):
    for i in nums: 
        if nums[i] == 3 and nums[i+1] == 3:
            return True
        else: 
            return False    

When this code checked with:

has_33([1, 3, 3])   
has_33([1, 3, 1, 3])

it properly worked.

But when it checked with: has_33([3, 1, 3])

enter image description here

What does 'list index out of range' means? and how to fix it?

  • 1
    It seems like you expect `for i in nums` to return the _indexes_ in the list. But it does not -- it returns the _values_. – John Gordon Apr 11 '22 at 01:26
  • 1
    [Please do not upload images of code/data/errors when asking a question.](http://meta.stackoverflow.com/q/285551) – martineau Apr 11 '22 at 01:29
  • 1
    There are a bunch of different bugs in this function -- I had an answer all typed up running through all of them but was too slow to hit post. The bugs are: (1) you're iterating over values instead of indices, as already mentioned (2) you're always returning in the first iteration, instead of allowing it to continue as long as the condition isn't met and returning False *after* the loop is exhausted (3) if you're iterating by pairs of indices you need to make sure you stop the iteration one *before* the end. – Samwise Apr 11 '22 at 01:38

1 Answers1

0

It means that your plus 1 eventually becomes bigger than the length of the list, you can avoid this by adjusting the value to your length, this way (I also removed the ifs, because they aren't needed)

def has_33(nums):
    return '33' in [f'{nums[i]}{nums[i+1]}' for i in range(len(nums)-1)]

or without list comprehension, fstrings and so on, a way to do it would be:

def has_33(nums):
    for i in range(len(nums)-1):
        if (nums[i], nums[i+1]) == (3, 3):
            return True
    return False
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Your list comprehension requires that all of the combinations be calculated and put into a list, then that checked for membership. If you use `any` with a generator expression you can avoid this. `any(f"{nums[i]}{nums[i+1]}" == "33" for i in range(len(nums)-1))` – Chris Apr 11 '22 at 22:38
  • 1
    Also, you could slice the list and compare to `[3, 3]`: `nums[i:i+2] == [3, 3]` – Chris Apr 11 '22 at 22:46
  • @Chris you are right :) – Fabio Craig Wimmer Florey Apr 12 '22 at 07:30