Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
an algorithm for this?
#1
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
Reply
#2
What have you tried? It looks pretty straightforward.
Reply
#3
Your second line of code is already a very efficient algorithm.
Reply
#4
first of all, can you explain what the logic is? why inner lists have 1, 4, 2, 2 - elements?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020