I am trying to see if groups of three with consecutive elements have a zigzag pattern. Add to an empty list "1" for a zig, "1" for a zag, or "0" for neither. It seems to satisfy my first "if" condition and my "else" statement but never the middle. I've tried it as two if statement, one if and one elif, and nested. The answer should be [1,1,0] but I can only get [1,0] or no output and sometimes " index out of range". input [1,2,1,3,4] output [1,1,0]
def solution(numbers):
arr = []
for i in range(len(numbers)-2):
if numbers[i+1] > numbers[i] and numbers[i+2]:
arr.append(1)
if numbers[i+1] < numbers[i] and numbers[i+2]:
arr.append(1)
else:
arr.append(0)
return arr
You've got a sliding window here.
You're getting
IndexErrorbecause your code hasfor i in range(len(numbers)), and then you ask fornumbers[i+2]. To prevent this, reduce the range:But you may prefer to
zipsome slices together: