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