Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

manipulate list of list using random and restrictions

I have two lists a and b.

a=[[3, 1], [3, 2, 3], [5, 1, 4, 8], [3, 5], [10, 1, 3, 6, 7],[2,1,2]]
b=[[4], [3], [9], [5], [21],[5]]

List of list a is interpreted as follows.

  • a[0]=[3,1]. This means I want 3 items, where item 1 must be included.
  • a[-1]=[2,1,2] I want 2 items, where item 1 and item 2 must
    be included.
  • a[2] = [5,1,4,8] I want 5 items, where item 1, item 4 and item 8 must be included.

List of list b is the available list of item from which list a can take from.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • b[0]=[4] this means item 1, item 2, item 3 and item 4 is available. This is linked
    to a[0]
  • b[-1]=[5] item 1, item 2, item 3, item 4 and item 5 is available. This is linked to a[-1]
  • b[2]=[9] this means i have 9 items is available. This is linked to a[2]

I’m trying to create a new list of list c such that it produces the following result.

For a[0]=[3,1] and b[0]=[4] it should produce the following result [1,2,4]

For a[-1]=[2,1,2] and b[-1]=[5] it should produce [1,2]

For a[2] = [5,1,4,8] and b[2]=[9] should produce [1,4,8,3,9]

What I have tried so far:

import random

a=[[3, 1], [3, 2, 3], [5, 1, 4, 8], [3, 5], [10, 1, 3, 6, 7],[2,1,2]]

b=[[4], [3], [9], [5], [21],[5]]

c=[sorted(random.sample(range(1, j[0]+1), int(i[0]))) for i,j in zip(a,b)]

print(c) # produces [[1, 3, 4], [1, 2, 3], [1, 3, 4, 6, 9], [1, 4, 5], [2, 5, 6, 7, 13, 15, 16, 19, 20, 21], [3, 4]]

As you can see, list c does not take into account those restrictions that I need.


Desired output will look something like this.

c= [[1,2,4],[2,3,1],[1,4,8,3,9],[5,1,3],[1,3,6,7,2,5,9,10,20,21],[1,2]]

>Solution :

You can run a loop over the two lists and construct a remaining_items list to randomly sample from –

 c = []
 for constraints, items in zip(a, b):
    num_items, *required_items = constraints
    pick_list = list(_ for _ in range(1, items[0] + 1) if _ not in required_items)
    num_items_to_pick = num_items - len(required_items)
    remaining_items = random.sample(pick_list, num_items_to_pick)
    print(required_items + remaining_items)
    c.append(required_items + remaining_items)

Output

[[1, 2, 3],
 [2, 3, 1],
 [1, 4, 8, 3, 6],
 [5, 3, 1],
 [1, 3, 6, 7, 18, 2, 14, 21, 19, 15],
 [1, 2]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading