入坑codewars第四天-Delete occurrences of an element if it occurs more than n times
阿新 • • 發佈:2018-11-25
第一題:
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
第二題: