Home > Back-end >  How to use RECURSION to group items in a list using python
How to use RECURSION to group items in a list using python

Time:02-05

I'm trying to create a function that consumes a flat list and returns a list of lists/nested list that basically groups the values of the original list together based on their value.

so basically

L = [ 1, 19, 5, 2, 22, 12 28]

if I group them in groups of based on groups of 10 L will become

L = [[1, 2, 5], [12, 19], [22, 28]]

However I HAVE to use recursion to do this. I'm a little lost and don't know where to start. If I can have a bit of help I would appreciate it

def group_lists(L, pos): 
      if pos>=len(L):
        return none 
      else:
        if L[pos]<=10:
          return ?    
        elif 20>=L[pos]>10:
          return ? 
        else: 
          return ?    

CodePudding user response:

You should pass the intermediate result through the recursive calls, and then return it when you've run out of elements. If you must use exactly two parameters for whatever reason, make a wrapper function or use the global keyword.

def group_lists(L, pos, result): 
  if len(L) <= pos:
    return result
  else:
    result[L[pos] // 10].append(L[pos])
    return group_lists(L, pos   1, result)
    
L = [ 1, 19, 5, 2, 22, 12, 28]

print(group_lists(L, 0, [[], [], []]))

CodePudding user response:

Here's a version that adds one sublist per recursive call:

>>> def group_lists(arr):
...     if isinstance(arr[-1], list):
...         return arr
...     i = sum(isinstance(sub, list) for sub in arr)
...     return group_lists(
...         arr[:i]
...           [[n for n in arr[i:] if n // 10 == i]]
...           [n for n in arr[i:] if n // 10 != i]
...     )
...
>>> group_lists([1, 19, 5, 2, 22, 12, 28])
[[1, 5, 2], [19, 12], [22, 28]]

CodePudding user response:

You can try the following:

lst = [1, 19, 5, 2, 22, 12, 28]

def group_lists(lst):
    if not lst: # empty list
        return []
    output = group_lists(lst[1:]) # recursion
    while len(output) <= lst[0] // 10: # if not enough slots
        output.append([]) # make as many as needed
    output[lst[0] // 10].append(lst[0]) # append the item to the right slot
    return output

print(group_lists(lst)) # [[2, 5, 1], [12, 19], [28, 22]]

This would automatically add slots as needed, using a while loop. It will make empty slots if your input is something like[1, 21].

CodePudding user response:

You can use defaultdict structure from collection module like

from collections import defaultdict
def group_list(L, res=defaultdict(list)):
    if len(L) == 1:
        res[L[0] // 10].append(L[0])
        return
    if len(L) == 0:
        return
    group_list(L[:len(L) // 2])
    group_list(L[len(L) // 2:])
    return res

print(group_list([ 1, 19, 5, 2, 22, 12, 28]))

#defaultdict(<class 'list'>, {0: [1, 5, 2], 1: [19, 12], 2: [22, 28]})
  •  Tags:  
  • Related