'How To write a function to Check for a Sequence of integers in an array in python
I'm trying to figure out why the code I wrote to find a sequence of integers in any given array is not catching all the instances. Could you help, please?
Here's the code:
def array123(nums):
if len(nums) < 3:
return False
else:
for i in range(len(nums) - 1):
if nums[i:i + 3] == [1, 2, 3]:
return True
return False
Solution 1:[1]
The return False
part should be indented as follows.
def array123(nums):
if len(nums) < 3:
return False
else:
for i in range(len(nums) - 1):
if nums[i:i + 3] == [1, 2, 3]:
return True
return False # This should be indented this way.
Solution 2:[2]
def array123(nums):
nums_to_string = str(nums)
if len(nums_to_string) < 3:
return False
else:
for i in range(len(nums_to_string) - 1):
if nums_to_string[i:i + 3] == "123":
return True
return False
Solution 3:[3]
def array123(nums):
for i in range(len(nums)-2):
if nums[i:i + 3] == [1, 2, 3]:
return True
return False
"""'i' in range and then go for the length of nums because I don't know how long nums are going to be as a list. I will say -2 because I don't want to go all the way to the end. so -2 back because I'm going to be counting in steps of three."""
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 | nilrj |
Solution 2 | Stef Renneboog |
Solution 3 |