Skip to content

Instantly share code, notes, and snippets.

@mebusw
Created June 13, 2017 08:30
Show Gist options
  • Save mebusw/f2195056a92904b6d2a2cf11abb7c4d6 to your computer and use it in GitHub Desktop.
Save mebusw/f2195056a92904b6d2a2cf11abb7c4d6 to your computer and use it in GitHub Desktop.
#!encoding=utf8
"""
建立在山峰和峡谷的城堡酒店,看具体描述:https://coding.net/u/wanghao/p/The-Castle-Company/git/blob/master/README.md
建立在山峰和峡谷的城堡酒店
给定一组整数数组,可以把它们想象成高度,如[3,2,5,6,7,5,3]从而形成一条地形数据。
要求:找到所有的峰值和谷值的总数,所谓峰值就是他之前的数字和之后的数字都比他小,谷值就是之前和之后的数字都比他大。
如 [2,4,3]中 4 可以记为一个峰值, [5,3,6]中3可以记为一个谷值,这个峰/谷值可以是一个数或者一系列相同的数,如 [3,5,5,5,4] 三个 5 可以看作是一个峰值。
"""
import unittest
def peak(heights):
result = []
total = 0
head = 0
while head < len(heights) - 2:
flat = 1
while heights[head+flat] == heights[head+flat+1]:
flat += 1
is_highest = heights[head+1] > heights[head] and heights[head+1] > heights[head+1+flat]
is_lowest = heights[head+1] < heights[head] and heights[head+1] < heights[head+1+flat]
if is_highest or is_lowest:
result.append(heights[head:head+2+flat])
head += flat
return result
class TestPeak(unittest.TestCase):
def test_peak(self):
self.assertEquals([[2,4,3]], peak([2,4,3]))
self.assertEquals([], peak([2,2,3]))
self.assertEquals([[4,5,3]], peak([2,4,5,3]))
# self.assertEquals([[2,4,1],[1,3,1]], peak([2,4,1,3,1]))
self.assertEquals([[2,-2,1], [-2, 1, -5],[1,-5,1]], peak([2,-2,1,-5,1]))
self.assertEquals([[2,4,1], [4, 1, 3],[1,3,1]], peak([2,4,1,3,1]))
self.assertEquals([[3,5,5,5,4]], peak([3,5,5,5,4]))
self.assertEquals([[3,5,5,5,4],[5,4,8]], peak([3,5,5,5,4,8]))
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment