'What does i in range(len(nums)-2): do? in Python
I understand list iteration and range and len() function but I'm not getting what the -2 does exactly..
this was a problem on codingBat
Given an array of ints, return True if the sequence of numbers 1, 2, 3 appears in the array somewhere.
array123([1, 1, 2, 3, 1]) → True
array123([1, 1, 2, 4, 1]) → False
array123([1, 1, 2, 1, 2, 3]) → True
Solution:
def array123(nums):
# Note: iterate with length-2, so can use i+1 and i+2 in the loop
**for i in range(len(nums)-2):**
if nums[i]==1 and nums[i+1]==2 and nums[i+2]==3:
return True
return False
Solution 1:[1]
Assuming nums is a list or an array, the len() built in Python function will get the length of items in an array and then we iterate in a for loop starting at 0 and continuing to add 1 to the variable "i" until it is equal to the length of "nums" minus two and we stop once it reaches that threshold.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zachary |
