To verify ALL the numbers that may be missing from a list whichever, just use the code below.
NOTE: This code may include any lists of integers - increasing, decreasing, alternating, with positive values, with negative values, with null values and with positive, negative and null values.
def faltante(lis):
menor = min(lis)
maior = max(lis)
faltando = list()
for c in range(menor, maior + 1):
if c not in lis:
faltando.append(c)
return faltando
numeros = list(map(int, input('Digite alguns números: ').split()))
print(f'Os números faltantes são:\n{faltante(numeros)}')
Note that when we execute this code we receive the following message: Digite alguns números:
. Right now we must type all the number we desire, in the same line, separated for a single space and press enter
.
After inserting the values, they will be mounted in the list números
and then it is passed as a parameter to the function faltante
. Getting there, is calculated the menor
and maior
value of that list. Subsequently, the for will travel the range(menor, maior + 1)
and, with the aid of the block if
, is checked whether each element of the respective interaction does not belong to the list - parameter lis
. If the item does not belong to the list, it is added to the list faltando
.
After these operations the list of missing numbers is displayed.
Let’s test the execution of the code?
Example 1:
Let’s enter the values...
1 2 3 5 6 7 8 10
The exit will be:
[4, 9]
Example 2:
Let’s enter the values...
1 5 7 9
The exit will be:
[2, 3, 4, 6, 8]
Example 3:
Let’s enter the values:
1 12 13 15 17 20
The exit will be:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 16, 18, 19]
Note that in both examples, the code was able to verify and display ALL the values MISSING in a single list and in ascending order.
Something else, when calculating the menor
and the maior
list value already enabled the function to work with values that are also not in order - rising or decreasing.
Example 4:
Let’s enter the values:
12 9 2 5 18
The exit will be:
[3, 4, 6, 7, 8, 10, 11, 13, 14, 15, 16, 17]
Example 5:
Let’s type in the figures:
4 20
The exit will be:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Example 6:
Let’s enter the values:
-10 -3 6 12
The exit will be:
[-9, -8, -7, -6, -5, -4, -2, -1, 0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11]
Summary
This code is able to identify and display all the missing values of a list of numbers whole - positive, negative and null - regardless of the order - ascending, decreasing or alternating - that the values are.
Marco, good afternoon! Enter in your code an example of a list you want to test and the expected result. Hugs!
– lmonferrari
The numbers will always be in ascending order?
– hkotsubo
Yes. They’ll be in ascending order
– Marco Raad
Only one number will be missing or more than one number may be missing from the list?
– Augusto Vasques