Kshtj
Kshtj

Reputation: 109

how to count for a range of integers in a list

I am trying to find the probability of the numbers in a list.I have a list say:

a =[62.0, 0.0, 67.0, 69.0, 0.0, 76.0, 0.0, 0.0, 69.0, 70.0, 73.0, 0.0, 0.0, 56.0, 80.0, 0.0, 59.0, 65.0, 78.0, 0.0, 43.0, 0.0, 87.0]

i want to find out the probability of number from 0-25,25-50,50-100 and more than 100. i tried using this:

a.count(range(25))/len(a)
a.count(range(25,50))/len(a)

But am not getting the required results. Can someone help with whats wrong here?

Upvotes: 1

Views: 4789

Answers (4)

Paul Lemarchand
Paul Lemarchand

Reputation: 2096

Adding to @Samwise's answer, since OP @Kshtj said in a comment they don't want too many lines of code... You can simply write a function or lambda to get the frequency as such, which will be more easily scalable:

get_freq = lambda a, low, high: sum(low <= i < high for i in a) / len(a)

>>>get_freq(a, 0, 25)
0.391304347826087
>>>get_freq(a, 50, 100)
0.5652173913043478

Upvotes: 3

Sven Eberth
Sven Eberth

Reputation: 3115

a = [62.0, 0.0, 67.0, 69.0, 0.0, 76.0, 0.0, 0.0, 69.0, 70.0, 73.0, 0.0, 0.0, 56.0, 80.0, 0.0, 59.0, 65.0, 78.0, 0.0, 43.0, 0.0, 87.0]

print("0-25:", len(list(filter(lambda x: 0 <= x <= 25, a))) / len(a))
print("25-50:", len(list(filter(lambda x: 25 < x <= 50, a))) / len(a))
print("50-100:", len(list(filter(lambda x: 50 < x <= 100, a))) / len(a))
print(">100:", len(list(filter(lambda x: x > 100, a))) / len(a))

Output

0-25: 0.391304347826087
25-50: 0.043478260869565216
50-100: 0.5652173913043478
>100: 0.0

Upvotes: 0

Diego Palacios
Diego Palacios

Reputation: 1144

>>> len(list(filter(lambda x: x<=25, a)))/len(a)
0.391304347826087

Upvotes: 2

Samwise
Samwise

Reputation: 71454

a.count(range(25)) gives 0 because range(25) isn't an element of a. What you want to count is the occurrences of each individual element of range(25) within a, e.g.:

>>> sum(a.count(i) for i in range(25))
9

Alternatively, you could iterate over each element of a and check it for inclusion in the range (I think this'll be a bit faster since in theory you don't need to iterate over a range to test whether something is in it):

>>> sum(i in range(25) for i in a)
9

Upvotes: 5

Related Questions