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.
JavaScript
x
16
16
1
import numpy as np
2
import random as rnd
3
4
zufall = rnd.randint(0,1)
5
zufall_list = []
6
hoehe = int(input("Höhe? "))
7
behaelter = np.zeros(hoehe+1, int)
8
9
10
for i in range(hoehe):
11
zufall_list.append(rnd.randint(0,1))
12
13
for j in str(sum(zufall_list)):
14
behaelter[j] += 1
15
print(zufall_list)
16
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
JavaScript
1
3
1
for j in str(sum(zufall_list)):
2
behaelter[j] += 1
3
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.