-1
#here is the code                                     
def has_33(nums):                                        
    for i in range(0,len(nums)-1):                  
        if nums[i:i+2]==[3,3]:
            return True
    return False
nums = [1,2,3,3]
print(has_33(nums))

questions:

  1. why the code used len(nums)-1 in second line?(why used -1 ?)
  2. in the 3rd line why do they used [i:i+2]==[3,3] and how does this code perform ?

please let me know , i am basically a noob in coding right now please help me to under stand how this code works

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53

3 Answers3

0
  1. Because a list of the length n has only n-1 pairs (for example, [1,2,3,4] has [1,2], [2,3] and [3,4])
  2. Beacuse list[x:y] does not return element y of the list.
0
  1. If you're looking for two elements in a row, there's no point in checking the last element of the list, since there's nothing after it. So the loop stops at the 2nd-to-last index.
  2. nums[i:i+2] returns a slice of the list from element i to element i+1. Those are 2 consecutive elements. Then it compares this to [3, 3] to see if that pair of elements are two 3's next to each other.
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The following code is simple and should work for what you want to do.

a=[0, 1, 2, 0, 3]

def has_33():
    last_i = 0
    for i in a:
        if last_i==3 and i==3:
            return True
        if i==3:
            last_i = 3
    return False

print(has_33())

Also works in different combinations of ...3,3...

CodinGuy
  • 33
  • 1
  • 5