1

I want to write a function that returns a list of randomly splitted chunks, given a list of sizes of each chunk. For example, say I have a list of unique integers from 0 to 9

lst = list(range(10))

I want to split into 4 chunks of sizes 1, 2, 2 and 5, so the function should take an input variable sizes as below:

my_func(lst, sizes=[1, 2, 2, 5])

I expect the function to return something like

[[3], [1, 7], [2, 4], [0, 5, 6, 8, 9]]

If the input sizes = [5, 1, 4], I expect the function to return something in order like

[[1, 3, 4, 6, 8], [9], [0, 2, 5, 7]]

Any suggestions?

3
  • 1
    Please see: stackoverflow.com/q/976882/8881141 Commented Mar 5, 2021 at 10:13
  • 1
    Please update your question with the code you have tried. Commented Mar 5, 2021 at 10:13
  • okay. I think I got it after you remind me of random.shuffle. Commented Mar 5, 2021 at 10:16

3 Answers 3

2

My approach is to use random.shuffle and then go through the shuffled array!

import random
def my_func(lst, sizes):
    random.shuffle(lst)
    ret = []
    pointer = 0
    for s in sizes:
        ret.append(lst[pointer:pointer+s])
        pointer+=s
    return ret

lst = list(range(10))
print(my_func(lst, sizes = [1, 2, 2, 5]))
print(my_func(lst, sizes = [5, 1, 4]))
[[5], [6, 7], [4, 0], [8, 3, 9, 2, 1]]
[[5, 2, 4, 3, 0], [8], [6, 7, 9, 1]]
Sign up to request clarification or add additional context in comments.

Comments

0

Use random.shuffle to shuffle your list. Also just keep slicing the list.

import random

def random_split(lst, sizes):
    if sum(sizes) != len(lst):
        raise ValueError("Sizes should match list length!")
    lst = lst.copy() # Copy list
    random.shuffle(lst) # shuffle
    res = []
    for size in sizes:
        split_list, lst = lst[:size], lst[size:] # Make two pieces of the list
        # split_list.sort()
        # Above line should be used if each sublist should be sorted
        res.append(split_list)
    return res

2 Comments

Hi mate, this is a duplicate answer!
@KuldeepSinghSidhu Not exactly both were in short succession. Honest mistake friend. :)
0

you can do something like this:

import random

lis=[]
g_lis=[]

for i in sizes:
    list_int = i

    for j in range(list_int):
        num = random.randint(0,9)
        lis.append(num)

    g_lis.append(lis)

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.