查找列表中最近的缺失数



我在Python中有一个列表,我如何在这个列表中找到最小的空数?

的例子:

[1,2,4,5,6,7,9]

这个有序列表中缺少数字3和8。我怎么找到最小的数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()

由于稍后我将添加不同的代码,因此需要self finding(self)参数。

谢谢!

一种可能的方法:迭代相邻的数字对,并返回后一个数字大于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

如果你需要从Find.finding()调用这个,你可以这样做:

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()

你写的循环没有完成任何事情,因为它没有查看列表的值,而且它用len(b) + 1覆盖了cont变量。你可能更幸运的是:

for index in range(len(b)):
cont = index + 1
if b[index] + 1 != b[cont]:
print(f"empty value: {b[index] + 1}")
break

这里有一个解决方案:循环遍历列表(排序)和列表长度相同的数字范围。如果列表中的项大于范围项,则返回该范围项以获得"空";价值。

代码:

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)

这里假设所有的数都是正数,并且最小的可能数是1。

最新更新