2

I have 2 lists of integers. I want to repeat one list members the times from another list. I tried using zip() function and also my following code, but I get the same error

'TypeError: 'int' object is not callable'

Here is my code -

def predict_from_distribution(distribution, range):

    classes = [0, 1, 2, 3, 4, 5]
    summation = np.cumsum(distribution)
    results = []
    uniform_samples = np.random.uniform(0, 1, range)
    iterations = np.multiply(distribution, len(uniform_samples))
    iterations = [int(num) for num in iterations]
    for i in range(len(classes)):
        for x in range(iterations[i]):
            results.append(classes[i] * x)
    return print(results)


predict_from_distribution([0.2, 0.1, 0.25, 0.15, 0.25, 0.05], 50)
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
Soumya C
  • 117
  • 10

2 Answers2

4

You have overriden the built-in method range with the value 50 by using range as a parameter name.

As a result, calling range(...) is now the same as if you would write 50(...) - that's why you get the error message TypeError: 'int' object is not callable.

If you use something else as parameter name (e.g. R), your code works fine.

import numpy as np

def predict_from_distribution(distribution, R):

    classes = [0, 1, 2, 3, 4, 5]
    summation = np.cumsum(distribution)
    results = []
    uniform_samples = np.random.uniform(0, 1, R)
    iterations = np.multiply(distribution, len(uniform_samples))
    iterations = [int(num) for num in iterations]
    for i in range(len(classes)):
        for x in range(iterations[i]):
            results.append(classes[i] * x)
    return print(results)


predict_from_distribution([0.2, 0.1, 0.25, 0.15, 0.25, 0.05], 50)
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
0

By the way, this was what I was trying to achieve with the code i.e predicting the classes of a biased dice when the experiment is repeated 'total' number of times. (without using any numpy random choice or other distributions)

import numpy as np

def predict_from_distribution(distribution, total):

classes = [0, 1, 2, 3, 4, 5]
summation = int(sum(distribution))
if not summation == 1:
    print('Error : The sum of the probabilities do not add up to 1')
results = []
iterations = np.multiply(distribution, total)
iterations = [int(num) for num in iterations]
for i in range(len(classes)):
    for x in range(iterations[i]):
        results.append(classes[i])
return print(results)

predict_from_distribution([0.2, 0.1, 0.25, 0.15, 0.25, 0.05], 50)

Soumya C
  • 117
  • 10