'How to use RECURSION to group items in a list using python
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 ?
Solution 1:[1]
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]]
Solution 2:[2]
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].
Solution 3:[3]
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]})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samwise |
| Solution 2 | |
| Solution 3 | Eugene |
