Home > front end >  How remove elements in array with out messing with the counter or list length
How remove elements in array with out messing with the counter or list length

Time:11-10

Codewars: 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]

I'll loop through the array to find the elements that have more than "x" amount. But The problem for me is that when I want to remove that element it changes the length of the array there for throwing off my loop counter. And then when I try another way by creating another list and then again looping through the original list and seeing if the element has more than "x" amount then I'll copy that element into the new array leaving the old array alone and it keeping its index and the loop is fine but now I do not know how to stop copying the element once it hits its desired amount. Please help me. I have been on this answer for a week now.

CodePudding user response:

Maybe you could try this snippet to see that helps?

Have not done too many edge cases - so please raise questions, if run into some edges.

def delete_nth(lst, N):
    
    seen = {}
    res = []
    
    for x in lst:
      if x not in seen :
        seen[x] = 0
      else:
        seen[x]  = 1
        
      if seen[x] <N:
        res.append(x)
    return res

print(delete_nth([1, 1, 1, 1], 2))      # [1, 1]
print(delete_nth([20, 37, 20, 22], 1))  # [20, 37, 22]
  • Related