Well, for each element, you need to check the next 2 (i.e., for each position i
, you need to check the positions i + 1
and i + 2
). Then you must iterate up len - 2
instead of len - 1
:
numeros = [10, 5, 7, 9, 20, 16, 11, 12, 13, 3]
for i in range(len(numeros) - 2):
if numeros[i] + 1 == numeros[i + 1] == numeros[i + 2] - 1:
print(f'Tem 3 números consecutivos: {numeros[i]}, {numeros[i + 1]}, {numeros[i + 2]}')
break
else:
print('não tem 3 números consecutivos')
In the for
, just see if the position element i
summed with 1 is equal to the position element i + 1
, which in turn is equal to the element of the position i + 2
subtracted from 1. If it is, I print the numbers and interrupt the loop with break
.
If you don’t have 3 consecutive numbers, it won’t reach the break
and falls into else
(yes, the else
is from for
, in Python this is perfectly possible).
I don’t know why you created the list C
, because if the idea is only to know if you have or not, you would not need to store the numbers. But if you want, you can make a Slice to get the list of consecutive:
numeros = [10, 5, 7, 9, 20, 16, 11, 12, 13, 3]
for i in range(len(numeros) - 2):
consecutivos = numeros[i:i + 3] # slice para pegar os elementos i, i + 1 e i + 2
if consecutivos[0] + 1 == consecutivos[1] == consecutivos[2] - 1:
break
else: # se não achou, deixa a lista de consecutivos vazia
consecutivos = []
if consecutivos: # se a lista não está vazia
print(f'Os números consecutivos são {", ".join(map(str, consecutivos))}')
else: # se a lista é vazia
print('não tem 3 números consecutivos')
And there’s also the solution - medium over enginnered and based in this reply by Soen - using the module itertools
:
from itertools import tee
def threes(iterator):
a, b, c = tee(iterator, 3)
next(b, None)
next(c, None)
next(c, None)
return zip(a, b, c)
numeros = [10, 5, 7, 9, 20, 16, 11, 12, 13, 3]
for a, b, c in threes(numeros):
if a + 1 == b == c - 1:
consecutivos = [a, b, c]
break
else:
consecutivos = []
if consecutivos: # se a lista não está vazia
print(f'Os números consecutivos são {", ".join(map(str, consecutivos))}')
else: # se a lista é vazia
print('não tem 3 números consecutivos')
The idea is that tee
generates 3 independent iterators from the list of numbers. As all point to the beginning of the list, I call next
why b
point to the second element and c
point to the third. Then use zip
which returns an iterator for the 3 generated iterators (a
points to the first element, b
for the second, and c
to the third).
When iterating for the result of all this, I always have 3 consecutive numbers on the list, and then just do the same check of the previous examples. Like zip
ends when the smallest iterator is finished, the loop ends correctly when I reach the last number.