I’m a Python 3.0 beginner and I’m struggling to find a solution to the following problem. It’s a step for a Galton Board simulation exercise.
- I have an numpy array, which length is auto generated based on another variable
- I am then generating a set of numbers, adding them to a list and summing them
- I would finally want to add a counter of +1 to the array index, which equals the number in the sum in step 2.
import numpy as np import random as rnd zufall = rnd.randint(0,1) zufall_list = [] hoehe = int(input("Höhe? ")) behaelter = np.zeros(hoehe+1, int) for i in range(hoehe): zufall_list.append(rnd.randint(0,1)) for j in str(sum(zufall_list)): behaelter[j] += 1 print(zufall_list)
I get an IndexError: only integers, slices (
:), ellipsis (
…), numpy.newaxis (None) and integer or boolean arrays are valid indices
error and don`t understand why that is.
Advertisement
Answer
for j in str(sum(zufall_list)): behaelter[j] += 1
In this line, you are using str(sum(…)), a string as index. Although string is iterable, it cannot be used as an index.
In your case, I would do behaelter[int(j)] to change ‘j’ into an integer so that you can use it as an index.