Reputation: 29
enter code here count = 0
for i in range(1,len(listOfmountains)-1):
if listOfmountains[i+1] > listOfmountains[i]:
count +=1
elif listOfmountains[i-1] > listOfmountains[i]:
count +=1
return count
enter code hereif __name__ == "__main__":
testcase = [1000,1250,1200,1300,1100,1500,1400]
print("{} is the number of peaks in {}".format(countPeaks(testcase),testcase))
testcase = [1000,1250,2000,1600,2100]
print("{} is the number of peaks in {}".format(countPeaks(testcase),testcase))
testcase = [2000, 1250, 3500, 1600, 1400, 1650, 1800, 850, 1775, 1900]
print("{} is the number of peaks in {}".format(countPeaks(testcase), testcase))
I want to start at 1 and end at the number before the last number. I am iterating through a list. I am trying to see the number of peaks not counting the first number and last number by the way.
Upvotes: 0
Views: 60
Reputation: 3155
You were nearly there, you just need to change range(1, len(listOfMountains))
to range(1, len(listOfMountains)-1
.
The method signature for range()
is as follows:
range(start, stop, step)
range()
will create a range that includes the start value and excludes the stop value. For example:
print([i for i in range(0,4)])
will only print the values: [0,1,2,3]
(note that it excludes the stop value).
Upvotes: 1
Reputation: 311
Just substract 1 from the upper bound of the range function:
count = 0
for i in range(1,len(listOfmountains)-1):
if listOfmountains[i+1] > listOfmountains[i]:
count +=1
elif listOfmountains[i-1] > listOfmountains[i]:
count +=1
return count
Upvotes: 0