入坑codewars第四天-Delete occurrences of an element if it occurs more than n times

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_37341950/article/details/84480882

第一题:

Enough is enough!
Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like this sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them that he will only sit during the session if they show the same motive at most N times. Luckily, Alice and Bob are able to encode the motive as a number. Can you help them to remove numbers such that their list contains each number only up to N times, without changing the order?

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].

Example
  delete_nth ([1,1,1,1],2) # return [1,1]

  delete_nth ([20,37,20,21],1) # return [20,37,21]

题意是:

给定列表lst和数字N,创建一个新列表,其中包含最多n次的每个lst数,而无需重新排序。例如,如果N = 2,输入为[1,2,3,1,2,1,2,3],则取[1,2,3,1,2],然后删除[1,2,3,1,2] ]因为这会导致1和2在结果中3次,然后取3,这导致[1,2,3,1,2,3]。

即,每个数按照原定的次序输出在规定的个数内

比如20,37,20,21;输入个数为1;则依次取20,37,20(不取,因为是第二个超过了1),21所以= 20,37,21

代码如下,也是参考了别人的思路,非常简短

def delete_nth(order,max_e):
    ans = []#建立一个新的列表存新数列
    for o in order:#在order列表中取数
        if ans.count(o) < max_e:#如果当前数字计数<给定的个数限制,则加到新列表ans中
            ans.append(o)
    return ans

第二题:

猜你喜欢

转载自blog.csdn.net/sinat_37341950/article/details/84480882
今日推荐