# [Tutor] question

Mats Wichmann mats at wichmann.us
Wed Apr 12 09:24:42 EDT 2023

```On 4/12/23 03:49, dn via Tutor wrote:
> On 12/04/2023 20.41, Prayash Bhuyan wrote:
>> import random
>>
>> # list of names
>> names_list = ["ayush","bhargav","akankhya","prayash"]
>>
>> # dictionary to keep track of numbers assigned to names
>> #numbers_dict = {}
...

> Choice 2: data-oriented
>
> - preparation step
> - create a list of group-numbers in range( NRgroups )
>    & using itertools.cycle() or .repeat(), create a uniformly-distributed
>    range of group-numbers, the same length as len( names_list ).
>
> - outer loop: for each name
>    - use len( group_numbers ) as the number of unassigned names
>      (or places in groups).
>    - create a random integer in range( unassignedNR )
>    - use that as an index to pop() a random group_number from the
>      list of group-numbers
>
> NB pop() removes that indexed-element from the list, and thus shortens
> it - hence looking at the len() each time around the loop
>
> As each name is assigned, the remaining/unassigned group_number-s will
> be reduced.
>
> Because the group_numbers were pre-defined and pre-distributed, there is
> no need to count how many members have been previously assigned to a
> group - the (math involved in the) preparation step takes care of that!

I'd build on from this model: if you really have these tight constraints
(the real world is often a lot more messy than knowing up front that
you'll have 20 names and exactly four groups, etc.) you can just
preallocate everything: build a list of group numbers that matches the
list of names, and shuffle it, getting your randomization that way.
Here's an example - just doing the assignment, not including any of the
interactive part.  Of course you can build this out with more details as
needed:

>>> import random
>>> names = [chr(x + ord('A')) for x in range(20)]
>>> names
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T']
>>> groups = list(range(1, 5)) * 5
>>> groups
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> random.shuffle(groups)
>>> groups
[2, 4, 3, 3, 2, 2, 2, 1, 4, 3, 3, 1, 4, 3, 1, 4, 4, 1, 1, 2]
>>> names_with_groups = dict(zip(names, groups))
>>> names_with_groups
{'A': 2, 'B': 4, 'C': 3, 'D': 3, 'E': 2, 'F': 2, 'G': 2, 'H': 1, 'I': 4,
'J': 3, 'K': 3, 'L': 1, 'M': 4, 'N': 3, 'O': 1, 'P': 4, 'Q': 4, 'R': 1,
'S': 1, 'T': 2}
>>>

```