This Python program will determine whether the input array is a mountain array or not. I've found answers on stackoverflow for this same error in other programs I've made, but not this one. It seems to work without issue when a valid mountain array is the input, but I'm having issues when I change the first half of the test array to make it an invalid. Rather than it returning False, which is the goal, I'm getting this error: UnboundLocalError: local variable 'y' referenced before assignment
. Also, I was getting the same error for the z
variable, so I added the else
statements and it fixed it. Can't figure out why it didn't fix the y
variable as well. Here's my code:
def validMountainArray(arr):
maxElem = max(arr)
maxIndex = arr.index(maxElem)
if len(arr) < 3:
return False
else:
beginning = arr[:maxIndex]
end = arr[maxIndex + 1:]
for i in range(1, len(beginning) - 1):
if beginning[i + 1] > beginning[i]:
y = True
else:
y = False
for i in range(1, len(end) - 1):
if end[i + 1] < end[i]:
z = True
else:
z = False
if y == True and z == True:
return True
else:
return False