您的位置:首页 > 编程语言 > Python开发

codewars习题(2) python3 算法 Delete occurrences of an element if it occurs more than n times 6级

2018-01-27 21:25 387 查看
描述:


Task

Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this
would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

给定一个数组及一个最大值,不改变其顺序,在不超过最大值的情况下,删除多余的元素

举例:delete_nth ([1,1,1,1],2)#
return [1,1] delete_nth ([20,37,20,21],1)#
return [20,37,21]

算法;def delete_nth(order,max_e):

    a = []

    p = []

    b = order

    t = 0

    for i in b:

        for j in b:

            if i == j:

                t += 1

        if t > max_e and i not in a:

            a.append(i)

        t = 0

    t = 0

    for i in a:

        for j in b:

            if i == j:

                t += 1

        t = t - max_e

        while t > 0:

            p.append(i)

            t -= 1

        t = 0

    order.reverse()

    for i in p:

        order.remove(i)

    order.reverse()

    return order

  首先;利用双循环遍历列表,将需要删除的值装进新列表a里,然后遍历列表a,b,将需要删除的多余的元素都装进

新列表p里,然后翻转列表order,遍历列表p,删除每次的首个需要删除的元素,然后再反转order,(order就是b,为了方便)

这样就不用改变且顺序并且能删除指定值了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐