Home > Software engineering >  My code appends the same list 10 times instead of appending 10 randomized lists?
My code appends the same list 10 times instead of appending 10 randomized lists?

Time:09-05

At the moment, the while loop creates one list and appends it 10 times to the results list.

What do I need to change in the def dice() so that the while loop creates 10 different lists and appends them to the results list?

from random import choice

list = [1, 2, 3, 4, "a", "b", "c", "d"]
winner = []
ticket = [1, 2]
results = []
class Die: 
    def __init__(self, a_list):
        self.a_list = a_list
    
    def dice(self):
        while len(results) < 10:
            results.append(winner)
            while len(winner) < 2:
                die = choice(self.a_list)
                winner.append(die)
        print(results)
            

        

my_dice = Die(list)

my_dice.dice()

CodePudding user response:

I wrote a different approach using zip, if this works for you:

import random

lis = [1, 2, 3, 4, "a", "b", "c", "d"]
combo_1 = []
ticket = [1, 2]
combo_2 = []

class Die: 
    def __init__(self, a_list):
        self.a_list = a_list
    
    def dice(self):
        while len(results) < 10:
            combo_2.append(random.choice(self.a_list))
            combo_1.append(random.choice(self.a_list))
        dice = [list(i) for i in zip(combo_1, combo_2)]
            
        print(dice)
            

my_dice = Die(lis)

my_dice.dice()

Output:

[['b', 'd'], [3, 'b'], ['c', 'b'], ['d', 2], ['a', 4], ['d', 2], ['c', 'c'], ['b', 'b'], [3, 'b'], [3, 3]]

CodePudding user response:

Currently you never reset winner to be empty, so it just keeps growing in size. But I think you're overcomplicating this.

  1. You don't need a while loop if it's of fixed size - use for loop instead
  2. If the sub-list only has two values, you don't need a loop at all
  3. You're losing some of the benefit of having a class by having global variables

And syntactically list is a bad name for a variable because it shadows the builtin, and I would avoid having a method that prints at the end without returning anything.

How about this?

import random

class Die:
    def __init__(self, dice_options):
        self.dice_options = dice_options

    def dice(self):
        return [
            [random.choice(self.dice_options), random.choice(self.dice_options)]
            for _ in range(10)
        ]

my_dice = Die([1, 2, 3, 4, "a", "b", "c", "d"])
print(my_dice.dice())
# [[3, 'd'], ['d', 2], ['b', 4], [1, 'd'], [4, 'c'], ['b', 4], [2, 1], ['a', 'd'], ['a', 'd'], ['b', 4]]
  • Related