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

Find smallest positive number in a list without using a built-in function

I am trying to find the smallest positive number in a list without using any built-in function.

This is what I have tried.

def smallest_positive(lst):
    smallest = lst[0]
    for i in lst:
        if (i > 0) and (smallest > i):
            smallest = i
    return smallest

My test cases are:

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

print(smallest_positive([4, -6, 7, 2, -4, 10]))
# outputs: 2 CORRECT

print(smallest_positive([.22, 5, 3, -.1, 7, 6, 7]))
# outputs: .22 CORRECT

print(smallest_positive([-6, -7, -9]))
# outputs: -6 INCORRECT # I expect output to be None

print(smallest_positive([]))
# outputs: Traceback INCORRECT # I expect output to be None

Some test cases did not pass.

>Solution :

When you set smallest = list[0], it might be a negative number and screws the rest of your algorithms, so :

def smallest_positive(list):
    smallest = None
    for i in list:
        if i > 0 and (smallest is None or smallest > i):
            smallest = i
    return smallest

output for your test cases:

>>
2
0.22
None
None
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