This is my accepted submission for LeetCode. The problem is
You are given a 0-indexed integer array
nums
. An indexi
is part of a hill innums
if the closest non-equal neighbors ofi
are smaller thannums[i]
. Similarly, an indexi
is part of a valley innums
if the closest non-equal neighbors ofi
are larger thannums[i]
. Adjacent indicesi
andj
are part of the same hill or valley ifnums[i] == nums[j]
.Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.
Return the number of hills and valleys in nums.
(from LeetCode website)
It seemed to make the most sense to break this out by cases basically using if/elif. Due to rules, it also made sense to me at the time to reverse the list and go backwards in order to find whether still in a hill or valley. Do you see any improvements I could make?
class Solution(object):
def countHillValley(self, nums):
hills = 0
valley = 0
for index, item in enumerate(nums):
lastIndex = len(nums)-1
prevItem = nums[index-1]
nextItem = 0
if index != lastIndex:
nextItem = nums[index+1]
# no left neighbor
if index == 0:
hills += 0
valley += 0
# last index, no right neighbor
elif index == lastIndex:
# at last index there is no non-equal
# neighbor on the right
# so index is neither a hill or a valley
hills += 0
valley += 0
elif item > prevItem and item > nextItem:
hills += 1
elif item < prevItem and item == nextItem:
# enumerate over remainder of list
# start at next index
# This creates a list slice
# until find next non-equal neighbor
for interiorIndex, interiorItem in enumerate(nums[index:]):
if interiorItem != item:
if item < interiorItem:
valley += 1
break
if item > interiorItem:
hills += 0
break
elif item < prevItem and item < nextItem:
valley += 1
elif item < prevItem and item > nextItem:
valley += 0
elif item > prevItem and item < nextItem:
valley += 0
elif item == prevItem and item > nextItem:
reversedList = reversed(list(enumerate(nums[:index])))
for prevIndex, prevItem in reversedList:
if prevItem != item:
if item < prevItem:
hills += 0
valley += 0
break
if item > prevItem:
hills += 0
break
elif item > prevItem and item == nextItem:
for interiorIndex, interiorItem in enumerate(nums[index:]):
if interiorItem != item:
if item > interiorItem:
hills += 1
break
else:
valley += 0
break
return hills+valley