I have a list in Python, how can I find the smallest empty number in this list?
Example:
[1, 2, 4, 5, 6, 7, 9]
The numbers 3 and 8 are missing in this ordered list. How do I find the smallest number 3?
class Find():
def finding(self):
a = [1, 2, 4, 5, 6, 7, 9]
b = sorted(a)
print(b)
cont = 1
for index in range(len(b)):
cont = index 1
cont = len(b) 1
print("empty value: " str(cont))
Find = Find()
Find.finding()
Since I will add different codes later, the self finding(self) argument is required.
Thanks!
CodePudding user response:
One possible approach: iterate over pairs of adjacent numbers, and return the first one where the later number is greater by more than 1.
>>> def find_missing(arr):
... return next(a 1 for a, b in zip(arr, arr[1:]) if b > a 1)
...
>>> find_missing([1, 2, 4, 5, 6, 7, 9])
3
If you need to call this from Find.finding()
you could do:
def find_missing(arr):
return next(a 1 for a, b in zip(arr, arr[1:]) if b > a 1)
class Find():
def finding(self):
a = [1, 2, 4, 5, 6, 7, 9]
print(f"empty value: {find_missing(sorted(a))}")
Find = Find()
Find.finding()
The loop that you wrote doesn't accomplish anything because it doesn't look at the values of the list, and it overwrites the cont
variable with len(b) 1
. You might have more luck with something like:
for index in range(len(b)):
cont = index 1
if b[index] 1 != b[cont]:
print(f"empty value: {b[index] 1}")
break
CodePudding user response:
Here's a solution: loop through the lst (sorted) and a range of numbers with the same length of the lst. If the item from the lst is ever greater than the range item, return that range item to get the "empty" value.
Code:
def findSmallestEmpty(lst):
lst.sort()
relevantRange = range(1, len(lst))
for lstElement, rangeElement in zip(lst, relevantRange):
if lstElement > rangeElement:
return rangeElement
lst = [1, 2, 4, 5]
element = findSmallestEmpty(lst)
This assumes that all the numbers are positive and that the lowest possible number is 1.