0

I was using CodeWars and I was training with this 6 kyu kata, and while it seemed simple enough I keep on getting issues and errors with my code. It works on most of them but for some it just doesn't delete the elements. And it seems so random like there is no reason behind why it's cutting off. What's going on?

def delete_nth(order,max_e):
    order.reverse()
    for e in order:
        if order.count(e) > max_e:
            order.remove(e)
    order.reverse()
    return order
KingPin
  • 1
  • 1
  • Can you give the example for which it's not working – Lakshika Parihar Jul 28 '21 at 18:12
  • Testing for delete_nth([40, 48, 48, 48, 43, 5, 16, 43, 16, 1, 19, 43, 30, 43, 40, 43, 48, 43, 40, 48, 43, 43, 40, 48, 43, 16, 48, 48, 48, 16, 16, 19, 40, 48, 18, 16, 5, 43, 16, 16, 16],2) It should work on random inputs too!: [40, 48, 48, 48, 43, 5, 16, 43, 16, 1, 19, 43, 30, 43, 40, 43, 48, 43, 48, 16, 19, 18, 5] should equal [40, 48, 48, 43, 5, 16, 43, 16, 1, 19, 30, 40, 19, 18, 5] – KingPin Jul 28 '21 at 18:19
  • Testing for delete_nth([23, 29, 29, 29, 29, 29, 29, 39, 29, 29, 39, 29, 39, 29, 23],1) It should work on random inputs too!: [23, 29, 29, 29, 29, 29, 29, 39] should equal [23, 29, 39] – KingPin Jul 28 '21 at 18:20
  • Mutating a list as you iterate over it almost inevitably produces weird results. Check out the linked duplicate for more info and some workarounds. Easiest solution is going to be building a new list as you iterate over the old one. – Samwise Jul 28 '21 at 18:20
  • def delete_nth(order,max_e): for e in set(order): if order.count(e) > max_e: while e in order: order.remove(e) order.append(e) return order order = [1,1,2,2,3,3,3,3,5] print(delete_nth(order,3)) – Lakshika Parihar Jul 28 '21 at 18:23
  • If you use collections.Counter(), you don't need to use list.count(). list.count() is O(n), so using list.count() inside the loop makes the function O(n^2). collections.Counter() is a subclass of dict() so it has O(1) access time and creating it is O(n). – jpkotta Jul 28 '21 at 18:34

0 Answers0