[Tutor] question
Dennis Lee Bieber
wlfraed at ix.netcom.com
Wed Apr 12 13:40:49 EDT 2023
On Wed, 12 Apr 2023 14:11:07 +0530, Prayash Bhuyan
<bhuyanprayash18 at gmail.com> declaimed the following:
>this is my code i am writing a code where the computer asks the user for a
>name and if the name is in the list then it randomly assigns a number which
>in this case is the group number ..Now suppose I have 20 members in the
>lsit and I want to form four groups with five members in each group ..now a
>particular random number between 1 and 4 should only appear 5 times and not
>more than that because if that occurs members will not be equally divided
>in the group ..thats what i want...and it is not an assignment it's
>something that i am doing to satisfy my curiosity
Don't use random()/randint()/etc...
You have a list of names nG * nM in length (number groups * number
members). In your example that is 4 * 5 => 20.
Take the original list of names, feed it to shuffle(), then take slices
of the shuffled list where each slice is sized nM
I have not tested the behavior for cases where the list of names is NOT
nG*nM in length.
>>> import random
>>> names = ("one two three four five "
... "six seven eight nine ten "
... "eleven twelve thirteen fourteen fifteen "
... "sixteen seventeen eighteen nineteen twenty").split()
>>> nM = 5
>>> names
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen', 'twenty']
>>> random.shuffle(names)
>>> names
['twenty', 'nineteen', 'nine', 'three', 'sixteen', 'thirteen', 'fourteen',
'eleven', 'fifteen', 'ten', 'two', 'eighteen', 'eight', 'twelve', 'seven',
'four', 'one', 'seventeen', 'six', 'five']
>>> for ix in range(0, len(names), nM):
... print(names[ix:ix+nM])
...
['twenty', 'nineteen', 'nine', 'three', 'sixteen']
['thirteen', 'fourteen', 'eleven', 'fifteen', 'ten']
['two', 'eighteen', 'eight', 'twelve', 'seven']
['four', 'one', 'seventeen', 'six', 'five']
>>>
More information about the Tutor
mailing list