Check which part of a list is consecutive (not using sort)

Viewed 76

I would like to understand how consecutive numbers could be found in a list. This is the code I’ve written so far:

v = []
while True:
    n = int(input("Insert a number (0 for exit) -> "))
    if n == 0: break
    v.append(n)

for i in range(len(v)):
    if v[i] - 1 == v[i - 1]:
        print(v[i - 1])

but this code doesn't print the last number of v[i], can someone help me?

2 Answers

I don't know if I get your question right but a simple solution could be:

first = True
for i in range(1, len(v)):
    if v[i]-1 == v[i-1]:
        if first:
            first = False
            print("-")
            print(v[i-1])
        print(v[i])
    else:
        first = True

So that for an input like:

[4, 3, 6, 2, 7, 1, 2, 3, 4, 6, 5, 6, 8, 7]

you get:

-
1
2
3
4
-
5
6

Just write:

for i in range(1, len(v)):
    if (v[i] - 1) == v[i - 1]:
        print(v[i]) 
Related