美文网首页kata
每日kata~10~Pick peaks

每日kata~10~Pick peaks

作者: Lacia | 来源:发表于2020-05-12 18:00 被阅读0次

题目

https://www.codewars.com/kata/5279f6fe5ab7f447890006a7
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.

For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5).

The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}.

Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)

All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.

The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).

Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3] does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)

我的笨蛋解

def pick_peaks(arr):
    a = arr
    b = 0
    c = 0
    flag = 0
    res = {"pos": [], "peaks": []}
    for i in range(1,len(arr)-1):
        if a[i]>a[i-1] and a[i]>a[i+1]:
            res["pos"].append(i)
            res["peaks"].append(a[i])
        elif a[i]>a[i-1] and a[i]==a[i+1]:
            b = i
            c = a[i]
            flag = 1
        elif a[i]==a[i-1] and a[i]<a[i+1] and flag==1:
            b = 0
            c = 0
            flag = 0

        elif a[i]==a[i-1] and a[i]>a[i+1] and flag==1:
            res["pos"].append(b)
            res["peaks"].append(c)
            flag = 0

    return res

大神的解

Beautiful

def pick_peaks(arr):
    pos = []
    prob_peak = False
    for i in range(1, len(arr)):
        if arr[i] > arr[i-1]:
            prob_peak = i
        elif arr[i] < arr[i-1] and prob_peak:
            pos.append(prob_peak)
            prob_peak = False
    return {'pos':pos, 'peaks':[arr[i] for i in pos]}

相关文章

网友评论

    本文标题:每日kata~10~Pick peaks

    本文链接:https://www.haomeiwen.com/subject/jklinhtx.html