Python Forum
an algorithm for this? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: an algorithm for this? (/thread-28417.html)



an algorithm for this? - rudihammad - Jul-18-2020

Hello,
I have this list
myList = [0, 1, 2, 3, 4, 3, 4, 1, 2]
And I was wondering how can I convert it in this
myList = [[0], [1, 2, 3, 4], [3, 4], [1, 2]]
any algorithm for this?

thanks


RE: an algorithm for this? - ndc85430 - Jul-18-2020

What have you tried? It looks pretty straightforward.


RE: an algorithm for this? - Gribouillis - Jul-18-2020

Your second line of code is already a very efficient algorithm.


RE: an algorithm for this? - buran - Jul-18-2020

first of all, can you explain what the logic is? why inner lists have 1, 4, 2, 2 - elements?


RE: an algorithm for this? - DeaD_EyE - Jul-18-2020

The example looks like you want to split all numbers, where the last number must be n - 1 and the 0 seems to be a special case. Maybe because it's the first value.

def group(iterable):
    stack = []
    for element in iterable:
        if element == 0:
            # special case 0
            yield [0]
        elif stack and stack[-1] + 1 != element:
            # stack is not empty and last element is
            # not incremented by 1
            yield stack[:]
            # clear the stack after yielding the last
            # stack
            stack.clear()
        # append the element after
        stack.append(element)
    # yield the remaining stack
    yield stack[:]


myList = [0, 1, 2, 3, 4, 3, 4, 1, 2]
print(list(group(myList)))
Output:
[[0], [0, 1, 2, 3, 4], [3, 4], [1, 2]]
With more_itertools it's bit easier:

import more_itertools


myList = [0, 1, 2, 3, 4, 3, 4, 1, 2]
print(list(more_itertools.split_when(myList, lambda x,y: x + 1 != y)))

# or use a function instead  of lambda
def condition(last_value, current_value):
    return last_value + 1 != current_value

print(list(more_itertools.split_when(myList, condition)))


# and with the 0 as special case

def condition(last_value, current_value):
    return last_value == 0 or last_value + 1 != current_value

print(list(more_itertools.split_when(myList, condition)))
Always if condition return a True, the list is splitted.

Documentation: more_itertools.split_when


RE: an algorithm for this? - rudihammad - Jul-18-2020

Awesome thanks, DeaD_EyE.
What I was trying to do was to create a new list each time where the next number was not equal + 1 to the previous,with the exception
of the 0.