python detect ranges in list

Solutions on MaxInterview for python detect ranges in list by the best coders in the world

showing results for - "python detect ranges in list"
Maria
02 Jul 2019
1def detect_range(input_list):
2    start = None
3    length = 0
4
5    for elem in input_list:
6
7        # First element
8        if start is None:
9            start = elem
10            length = 1
11            continue
12
13        # Element in row, just count up
14        if elem == start + length:
15            length += 1
16            continue
17
18        # Otherwise, yield
19        if length == 1:
20            yield start
21        else:
22            yield (start, start+length)
23
24        start = elem
25        length = 1
26
27    if length == 1:
28        yield start
29    else:
30        yield (start, start+length)
31
32
33print(list(detect_range(a)))
34