Recursive and random list grouping

I am trying to write a function that creates a dichotomously grouped list, f. ex. if my input looks like this:

[a, b, c, d, e, f, g, h]

I want to select a random integer that will split it into smaller sublists again and again recursively until the length of the subscriptions is maximum, for example:

[[a, [b, c]], [d, [[e, f], [g, h]]]]

This is what I have so far, but still gives me a TypeError (list indices should be integers or slices, not a list):

def split_list(l): if l.__len__() > 2: pivot = np.random.random_integers(0, l.__len__() - 1) print(pivot, l) l = [RandomTree.split_list(l[:pivot])][RandomTree.split_list(l[pivot:])] return l 

I am stuck and I would be very grateful for any advice.

+5
source share
2 answers

Here's a solution that won't create singleton lists, according to your example:

 import random def splitlist(l, minlen=2): if len(l) <= minlen: # if the list is 2 or smaller, return l if len(l) > 1 else l[0] # return the list, or its only element x = random.randint(1, len(l)-1) # choose a random split return [splitlist(l[:x], minlen), splitlist(l[x:], minlen)] 

Usage example:

 >>> splitlist(list(range(8))) [[0, [1, [2, [3, 4]]]], [[5, 6], 7]] 
+2
source

In your question, it is not very clear what data types are used and, apparently, they are using some kind of non-traditional type of recursion (possibly as part of a class). To scroll scroll down a bit.

I took the liberty of changing the code a bit and using the regular random library, so what you are looking for might look like

 import random # at the module-declaration part of your program def split_list (l): if len(l) < 2: return l pivot = random.randint(1, len(l) - 1) return [RandomTree.split_list(l[:pivot]) + RandomTree.split_list(l[pivot:])] 

We stop recursion in one list of elements and apply recursion further, if we have not stopped using a random index, pulled out a possible range (note that random.randint generates an index with the specified boundaries).


Your error does not use any concatenation operator between the two parts of the return value.

[A][B] does not merge both lists, but tries to index the list specified in B (in your case) from A , which is an incorrect use of the type.

Therefore, you can resort to the original function (with obsolete numpy random) as

 def split_list(l): if l.__len__() > 2: pivot = np.random.random_integers(0, l.__len__() - 1) l = [RandomTree.split_list(l[:pivot])] + [RandomTree.split_list(l[pivot:])] return l 
+6
source

Source: https://habr.com/ru/post/1274838/


All Articles