1

Given an integer list and a key, I am required to group the list by greater than or equal to the key, or less than the key.

For example, When

key = 6 and lst = [1, 1, 1, 0, 0, 6, 10, 5, 10]

Output should be:

[[1, 1, 1, 0, 0], [6, 10], [5], [10]]

A new sublist must be created if while looping a new condition is met. When the process of grouping is over, the sublists are placed into a list. If the list is empty, it returns an empty list.

def group_ints(lst, key):
    greater_or_equal = []
    lessthan = []
    result = []
    
    if lst == None:
        return []
    else: 
        for i in lst:
            if i >= key:
                greater_or_equal.append(i)
            elif i < key:
                lessthan.append(i)
        if greater_or_equal:
            result.append(greater_or_equal)
        if lessthan:
            result.append(lessthan)
    return result
3
  • 2
    @diggusbickus 6 and 10 are both >= 6. 5 is < 6. 10 is >= 6. Commented Jun 24, 2024 at 16:27
  • 2
    result.append(greater_or_equal) and result.append(lessthan) are the only two places in the code that add something to result. So yes, of course result is only going to have, at most, two things in it... Commented Jun 24, 2024 at 16:34
  • 1
    What is your question? You didn't ask any. Commented Jun 25, 2024 at 10:05

2 Answers 2

4

You're only building two lists: greater_or_equal and lessthan, yet it is clear that the expected result could have any number of sublists, not just two. So every time you switch category, you'll have to create a new list (to serve as sub list).

Here is how you could do it:

def group_ints(lst, key):
    if not lst:
        return []
    
    result = [lst[:1]]  # start with the first value already in its own sublist

    for i in lst:
        # Is the current value of a different category than the last one?
        if (i >= key) != (result[-1][0] >= key):  # We need a new list
            result.append([])  # create and add it to the result
        result[-1].append(i)
    return result
Sign up to request clarification or add additional context in comments.

Comments

1

You can use itertools.groupby() and pass lambda x: x >= key as the key= parameter to achieve this:

from itertools import groupby


def split_list(lst: list[int], key: int):
    return [list(g) for _k, g in groupby(lst, key=lambda x: x >= key)]


assert split_list([1, 1, 1, 0, 0, 6, 10, 5, 10], key=6) == [[1, 1, 1, 0, 0], [6, 10], [5], [10]]
assert split_list([], key=6) == []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.