Home > Mobile >  I have a list which has been created from another list. However, I do not want two names repeating a
I have a list which has been created from another list. However, I do not want two names repeating a

Time:12-18

Code

I have six names in a list and wish to repeat them 20 times randomly and save it to a list called lineup. However, I do not want these names repeating after each other. For example, I would not want something like ['Shadab', 'Shadab'..] next to each other.

How can I go about fixing that?

I tried to append the names from the bowlers list into a new list called lineup and after that, use indexing to replace repeatable names. However, I was not able to do that successfully.

CodePudding user response:

This can be the answer code of your question.

import random
### number of overs
overs = 20
bowlers = ['Wasim','Hasan','Fazal','Rumman','Abrar','Shadab']
lineup = []

for i in range(overs):
    lineup.append(random.choice(bowlers))
    if (i != 0) & (lineup[i-1]==lineup[i]):
        lineup.pop()
        bowlers_notprev = bowlers.copy()
        bowlers_notprev.remove(lineup[i-1])
        lineup.append(random.choice(bowlers_notprev))

Double for loops should not be used in this case. If the first for loop of your code is to add one person to the lineup list, and the second for loop is to check if it is the same as the previous one, you can also write the code as below.

for i in range(overs):
    z = random.choice(bowlers)
    lineup.append(z)

for x in range(overs-1):
    if lineup[x] == lineup[x 1]:
        rmv = lineup.pop(x)
        bowlers_notprev = bowlers.copy()
        bowlers_notprev.remove(rmv)
        lineup.insert(x, random.choice(bowlers_notprev))

And you can use list comprehension like below when sampling lineup from bolwers.

lineup = [random.choice(bowlers) for a in range(overs)]

CodePudding user response:

This is one more answer without conditional if:

import random
### number of overs
overs = 20
bowlers = ['Wasim','Hasan','Fazal','Rumman','Abrar','Shadab']
lineup = []
curr_bowler = random.choice(bowlers)

for i in range(overs):
    lineup.append(curr_bowler)
    bowlers.remove(curr_bowler)        
    last_bowler = curr_bowler
    curr_bowler = random.choice(bowlers)
    bowlers.append(last_bowler)
  • Related