Sosek
Sosek

Reputation: 121

How to get all consecutive sequences of numbers from given set of numbers?

I will start the description of the problem with an example so that the question is clear.

List of numbers: [1,2,3,4]

How can I get each successive string: [[1],[1,2],[1,2,3],[1,2,3,4],[2],[2,3],[2,3,4],[3],[3,4],[4]]

I've been trying to solve this problem for a while and managed to get [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]] with lots of useless repetitions.


list = [1,2,3,4]

i = 0
j = 0
tempList = []
sequancesList = []

while i < len(list):
    while j < len(list):
        tempList.append(list[j])
        sequancesList.append(tempList)
        j += 1
    i += 1
    j = i
    tempList = []

def deleteDuplicates(list):
    noduplist = []
    for element in list:
        if element not in noduplist:
            noduplist.append(element)
    return noduplist

finalSequancesList = deleteDuplicates(sequancesList)

print(finalSequancesList)

Upvotes: 1

Views: 660

Answers (3)

C Hecht
C Hecht

Reputation: 1016

Edit: As was stated in the comments, the approach below works only if the list contains whole, ascending numbers and not in other instances.

There are two ways to do this, either as a nested for-loop or a one-liner using list-comprehension. Both versions below:

Nested for-loop

nrs = list(range(1,5))
result = []
for i in nrs:
    for j in range(i, max(nrs)+1):
        result.append(list(range(i,j+1)))
print(result)

List-comprehension

result = [list(range(i,j+1)) for i in nrs for j in range(i, max(nrs)+1)]
print(result)

Upvotes: 1

Bharel
Bharel

Reputation: 26900

Here is a generator that does exactly that:

def iter_successive(input_list):
    for i in range(len(input_list)):
        for j in range(i+1,len(input_list)+1):
            yield input_list[i:j]

>>> list(iter_successive(input_list))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]

Comparable one-liner solution:

def iter_successive(input_list):
    return (input_list[i:j] for i in range(len(input_list))
            for j in range(i+1,len(input_list)+1))

Upvotes: 1

Jett Chen
Jett Chen

Reputation: 382

Here's how to do it:

list = [1,2,3,4]

sequancesList = []

for i in range(len(list)):
    tmp = []
    for j in range(i,len(list)):
        tmp.append(list[j])
        sequancesList.append(tmp[:])

print(sequancesList)

-> [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]

Upvotes: 3

Related Questions