Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a list into two random parts [duplicate]

I have 12 people who i need to divide into 2 different teams. What i need to do is pick random 6 numbers between 0 and 11 for the first team and do the same for the second one with no overlap. What is the most efficient way to do this?

import random

A = random.choice([x for x in range(12)])

B = random.choice([x for x in range(12) if x != A])

C = random.choice([x for x in range(12) if (x != A) and (x != B)])

team1 = random.sample(range(0, 12), 6)
team2 = random.sample(range(0, 12), 6)

This is what i wrote so far. Any help is appreciated.

like image 378
What a Shame Avatar asked Sep 21 '20 13:09

What a Shame


People also ask

How do you split a list in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.

How do you split a list into an N sublist in Python?

In Python, we can split a list into n sublists a number of different ways. Given a length, or lengths, of the sublists, we can use a loop, or list comprehension to split a list into n sublists. A more efficient way to split a list into sublists is with yield().


2 Answers

You can use sets and set difference, like this:

import random

all_players = set(range(12))

team1 =  set(random.sample(all_players, 6))
team2 = all_players - team1

print(team1)
print(team2)

Example Output:

{1, 5, 8, 9, 10, 11}
{0, 2, 3, 4, 6, 7}
like image 70
Adam.Er8 Avatar answered Sep 28 '22 03:09

Adam.Er8


While using sets is cooler, you can as well shuffle the list of 12 players and slice it:

import random

all_players = list(range(12))

random.shuffle(all_players)

print(all_players[:6])
print(all_players[6:])

Output:

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

Especially if you need to do this multiple times you avoid creating multiple sets/lists over and over, instead you have one 12 element list as datastore.


Timings:

import random

for l in range(12,30,2):

    def shuffle():
      all_players = list(range(l))
      random.shuffle(all_players)
      return all_players[: l // 2], all_players[l // 2 :]
      
    def sets():
      all_players = set(range(l))
      team1 = set(random.sample(all_players, l//2))
      return team1, all_players - team1

    from timeit import timeit

    print(l, timeit(shuffle, number=10000))
    print(l, timeit(sets, number=10000), "\n")

Output:

12 0.27789219999999994   # shuffle marginally faster
12 0.2809480000000001    # sets

14 0.3270378999999999    # still less memory but slower
14 0.3056880999999998    # sets faster

[...]

26 0.6052818999999996
26 0.4748621000000002

28 0.6143755999999998
28 0.49672119999999964
like image 32
Patrick Artner Avatar answered Sep 28 '22 02:09

Patrick Artner