我有一个Google foobar挑战:
编写一个名为answer(data,n)的函数,该函数接收一个小于100个整数和一个数字n的列表,并返回相同的列表,但所有出现n次以上的数字完全删除。返回的列表应保留与原始列表相同的顺序 - 您不希望混淆那些精心规划的轮班!例如,如果数据是[5,10,15,10,7]并且n是1,则答案(数据,n)将返回列表[5,15,7],因为10发生两次,因此被从完全列出。
这是我的答案:
def answer(data=[], n=0):
for id in data:
num = data.count(id)
if num > n:
for i in data:
if i == id:
data.remove (id)
else:
continue
else:
continue
return data
但它没有通过测试。
答案 0 :(得分:0)
您可以通过在一行中使用列表推导来解决此问题(对于较大的数据集不是最佳的):
def answer(data, n):
return [x for x in data if x not in [y for y in set(data) if data.count(y) > n]]
正常方式:
def answer(data, n):
data_set = set(data)
for d in data_set:
if data.count(d) > n:
data = filter(lambda a: a != d, data)
return data
答案 1 :(得分:0)
def answer(data=[], n=0):
d={}
for i in data:
if i not in d:
d[i] = 1
else:
d[i] = d[i]+1
target=[]
for i in d.keys():
if d[i] > n:
target.append(i) #get those numbers appear counts more than n
result=[x for x in data if x not in target]
return result
答案 2 :(得分:0)
更短
def solution(data, n):
return [x for x in data if data.count(x) <= n]
答案 3 :(得分:0)
我不知道这是否是最好的方法。但是我已经颠倒了名单。我的代码如下:
def solution(data, n):
# Your code here
data.reverse()
for val in data:
num=data.count(val)
if(num>n):
for i in range(num):
data.remove(val)
data.reverse()
return(data)
答案 4 :(得分:0)
我最近遇到了这个问题,发现必须满足一些特定条件,例如,如果没有匹配的总数等于n,则返回整个列表。我是这样想的:
def answer(data, n):
#Append all match count cases in data to bl and eliminate duplicates.
#For example [5, 10, 15, 10, 7], n = 2, bl = [10, 10]. The function set()
#will remove the duplicates.
bl = list(set(x for x in data if data.count(x) == n))
#Returns a statement if the list has more than 100 integers within.
if len(data) > 100:
return "\nToo many data integers! Data must be below 100 integers."
#Returns empty list if n = 0.
if n == 0:
return bl
#Return list if duplicates were found, otherwise return the original list.
if bl:
return bl
else:
return data
输入:
answer([0, 2, 2, 1, 1, 3, 3, 3, 4, 5, 5], 2)
输出:
[1, 2, 5]
答案 5 :(得分:0)
def main():
data = [2, 3, 2, 5, 6, 2, 5, 1, 8, 9, 9, -9]
n = 3
res = answer(data, n)
print(res)
def answer(data, n):
store = []
for x in range(len(data)):
count = 0
for y in data:
if y == data[x]:
count += 1
if count > n:
if data[x] not in store:
store.append(data[x])
for z in store:
for r in reversed(range(len(data))):
if data[r] == z:
data.pop(r)
return data
main()
答案 6 :(得分:-1)
测试用例失败数据= [1,2,2,3,3,3,4,5,5],n = 1