Question

I'm writing a program that will roll any number of dice, with any number of sides, any number of times. I'm stuck in my function that rolls the dice a number of times and then replaces the zeros in the list with the roll. I keep on getting an error on rolls[rv]+=1:

TypeError: list indices must be integers, not list

My ctrList function that I sent to rolls, does return a list and I have tried changing that list into an int or str in my rollSim function, but nothing seems to work. Maybe I am going about this problem in the wrong way? Here is the code I have for this area so far:

numDice=int(input("How many dice do you want to roll? "))
numSides=int(input("How many Sides does each have? "))
numRolls=int(input("How many times do you want to roll the dice? "))


def ctrList(numSides, numDice): #Function that seeds  list with all zeros
    L=[]
    ctr=0
    possible= ((numSides * numDice)+1)
    for p in range (possible):
        ctr+=1
        L.append(0)
    return L

def rollSim(numDice, numSides, numRolls, rollDice):    

    rolls=ctrList(numSides, numDice) 
    for i in range (numRolls):
        rv= rollDice(numDice, numSides )
        rolls[rv]+=1        #where I keep on getting the error at :(
    return rolls

def rollDice(numDice, numSides ): #Function that rolls dice
    L=[]
    ctr=0
    for dice in range (numDice):
         L.append (random.randint(1, numSides))
         ctr+=1
    return L
Was it helpful?

Solution

It just seems that instead of:

for i in range (numRolls):
    rv= rollDice(numDice, numSides )
    rolls[rv]+=1        #where I keep on getting the error at :(

you need:

for i in range (numRolls):
    rv = rollDice(numDice, numSides)
    for dice in rv:
        rolls[dice] += 1

Your rollDice returns results for numDice dices (a list). Then you try to index the rolls list with another list, which doesn't make any sense (and that's what the error is saying exactly).

You can also change the method to return only one result, for one dice:

def rollDice(numSides):
    return random.randint(1, numSides)

So your version of counting code will work. Depends on what you want.

OTHER TIPS

Your rollDice function returns a list, so when you do

rv = rollDice(numDice, numSides)

You assign a list to rv. You can't do rolls[rv] from there, rv needs to be an int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top