OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

I am grouping integers into a nested list. But I end up with with two sublists each time instead of multiple

  • Thread starter Thread starter Eliel Cortes
  • Start date Start date
E

Eliel Cortes

Guest
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.

Code:
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
<p>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.</p>
<p>For example, When</p>
<p><code>key = 6</code> and <code>lst = [1, 1, 1, 0, 0, 6, 10, 5, 10]</code></p>
<p>Output should be:</p>
<p><code>[[1, 1, 1, 0, 0], [6, 10], [5], [10]]</code></p>
<p>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.</p>
<pre><code>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
</code></pre>
 

Latest posts

M
Replies
0
Views
1
Mohit Pant
M
Top