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

Time:03-10

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.

CodePudding user response:

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

CodePudding user response:

I believe this does what you're looking for. Please let me know if you have any questions.

def smallest_positive(input_list):
    
    # Initialize the smallest value to none
    smallest = None
    
    # For each value in the input list
    for value in input_list:
        
        # First positive value automatically becomes the smallest
        if smallest is None and value > 0:
            smallest = value
            
        # For any positive value smaller than the current smallest, update
        # smallest to be this valuue
        elif value > 0 and value < smallest:
            smallest = value
            
    return smallest
  • Related