Skip to content Skip to sidebar Skip to footer

Google Foobar Minion Labor Shifts Challenge

I have a Google foobar challenge: Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of

Solution 1:

Even shorter

def​ ​solution(data,​ ​n):​
    return [x for x in data if data.count(x) <= n]

Solution 2:

This is an old question but has not yet received the correct answer. Before looking into the complexity your answer is incorrect. You have to be careful when you want to modify the data structure the loop is dependent on. In your case

for i indata:
  if i == _id:
    data.remove(_id)
  else:
    continue

will not delete 'id' from 'data' in all cases, because you are changing the length of 'data' along the process and you will skip over some occurrence of 'id' in 'data' when you do this. Instead what you can do is store the index of occurrence of 'id' in the first for loop then delete them in the reverse order in a second 'for loop'. In your algorithm, the above bug occurs twice (in both of the 'for loops').

Solution 3:

def​ ​answer(data=[],​ ​n=0):
    d={}
    for i indata:
        if i not in d:
            d[i] = 1else:
            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 indataif x not in target]
    return result

Solution 4:

I do not know if it is the best way to do it. But I had reversed the list to do it. My code is as follows:

def solution(data, n):
    # Your code here
    data.reverse()
    forvalindata:
        num=data.count(val)
        if(num>n):
            for i in range(num):
              data.remove(val)
        data.reverse()
        return(data)

Solution 5:

I recently ran into this and saw that there are specific conditions that have to be met, such as if there are no matching total numbers that equal n then the entire list is returned. I figured it out this way:

defanswer(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.iflen(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

Input:

answer([0, 2, 2, 1, 1, 3, 3, 3, 4, 5, 5], 2)

Output:

[1, 2, 5]
        

Post a Comment for "Google Foobar Minion Labor Shifts Challenge"