Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the smallest positive number not in list

Tags:

python

list

I have a list in python like this:

myList = [1,14,2,5,3,7,8,12]

How can I easily find the first unused value? (in this case '4')

like image 729
jul Avatar asked Jan 27 '15 17:01

jul


People also ask

Can you find the smallest positive number?

1 is the smallest positive integer Was this answer helpful?

How do you find the first positive number in an array?

Solution idea and steps We sort the array. Suppose we are using heap sort which is an in-place O(nlogn) sorting algorithm. Now we run a loop and skip the negative numbers and zero present in the starting positions of the array. Starting from the first index, when we find X[i] < 1, we increment i by 1.


1 Answers

Easy to read, easy to understand, gets the job done:

def solution(A):
    smallest = 1
    unique = set(A)
    for int in unique:
        if int == smallest:
            smallest += 1
    return smallest
like image 114
Dev Avatar answered Nov 15 '22 15:11

Dev