Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given an array of integers, remove the n smallest – Codewars, Python

Here is the link for Codewars page.

My code fails the tests part of the question given below,
Q: Given an array of integers, remove the n smallest. If there are multiple elements with the same value, remove the ones with a lower index first. If n is greater than the length of the array/list, return an empty list/array. If n is zero or less, return the original array/list.
Don’t change the order of the elements that are left.

And here is my attempt:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def remove_smallest(n, arr):
    if n > 0:
        smallest_nums = sorted(arr)[:n]
        return [x for x in arr if x not in smallest_nums]
    return arr

I am not able to figure out the reason why my code does not work, it manages to pass all the basic 7 tests when I test the code, but when I try to attempt, my code fails quite a few of the random tests. The arrays used in the random tests are very huge, and I am not sure how to use them to find out where I went wrong. Any sort of advice that will help me debug the code by providing some techniques will be really helpful, Thank you.

>Solution :

The problem is that your return statement takes values that are not in that smallest_nums, but that could be filtering away too much. Some occurrences of the maximum value in that smallest_nums might still need to stay in the list.

Here is a minimal input for which your code fails:

print(remove_smallest(1, [1, 1]))

This prints an empty list, but it should print [1].

So you’ll need to take into account how many of that maximum value are in the original input and how many you have put in the smallest_nums and leave the difference in arr.

If you need a spoiler, here is your code adapted with that fix:

def remove_smallest(n, arr):
if n > 0 and arr:
smallest_nums = sorted(arr)[:n]
greatest = smallest_nums[-1]
count = len(smallest_nums) - smallest_nums.index(greatest)
return [x for x in arr
if x not in smallest_nums
or (x == greatest and (count := count - 1) < 0)]
return arr

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading