python binning frequency values iteratively

30 Views Asked by At

I am just starting with python. I have produced a list of ten random numbers from 1 to 100 and entered them into a list. Now I want to bin their frequencies in a second list also with ten elements each constituting one bin with bin width ten. I initialized the second list, all positions to 0. Then I wanted to simply increment the frequency bins by subtracting 1 from the random values in the first list and divide by ten, making the resulting integers correspond to indices from 0 to 9. This worked fine in C but I am not getting it in python (I realize there are more pythonic ways to doing this). I tried a few things but to no avail. Any quick fixes? here is the code:

A = [] #list of random sample expositions
i = 1
while i <= 10: # inner loop to generate random sampling experiment
    x = random.randrange (0, 100, 1)
    A.append (x)
    i += 1
Freq = [0] * 10
for x in A:
    += Freq [(int ((x-1)/10))]
1

There are 1 best solutions below

0
Woodford On BEST ANSWER

This isn't valid Python:

+= Freq [(int ((x-1)/10))]

You probably want something closer to this:

Freq [(int ((x-1)/10))] += 1

Regarding the "pythonicness" of your solution, you could go with something like:

import random

# identify "magic numbers/constants"
N = 10

# use a more appropriate random function with a list comprehension
A = [random.randint(1, 100) for _ in range(N)]

Freq = [0] * N
for x in A:
    # the // operator produces an integer result
    Freq[(x-1)//N] += 1

Depending on how you plan to use Freq you might consider collection.Counter instead:

from collections import Counter
Freq = Counter((x-1)//N for x in A)