manxing
manxing

Reputation: 3305

simple calculation in python

I have a list of integers ordered from maximum to minimum, like this: [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]

I just simply want to calculate the portion of each value in this list, like 5% is '1', 4% is '3' ,1% is 2345 and print out this result

What's an easy way to do this?

Upvotes: 0

Views: 179

Answers (4)

machine yearning
machine yearning

Reputation: 10119

This solution takes advantage of the fact that your elements are already ordered, and only makes a single pass through your original list (and a constant number of passes through the remaining data structures.

>>> from itertools import groupby
>>> x = [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]
>>> grouped_x = [(k, sum(1 for i in g)) for k,g in groupby(x)]
>>> grouped_x
[(2345, 1), (67, 1), (24, 2), (11, 2), (6, 5), (3, 5), (1, 6)]

The groupby expression is borrowed from the first question I ever asked on SO, and basically just groups each contiguous block of the same value into a list of (value, instance generator) pairs. Then the outer list comprehension just converts the instance generators into their total length.

I think OP's figures were not accurate, but this seems to be something like what he was getting at. I took the ceiling function, but you could also round

>>> from math import ceil
>>> for k, v in grouped_x:
print int(ceil(100 * v / float(len(x)))),
print  "% is", k


5 % is 2345
5 % is 67
10 % is 24
10 % is 11
23 % is 6
23 % is 3
28 % is 1

Upvotes: 2

lig
lig

Reputation: 3890

from collections import Counter, OrderedDict

items_count = len(x)

percentage_tuples = map(lambda tup: (tup[0], 100 * float(tup[1]) / items_count),
    Counter(x).most_common())
percentage_dict = OrderedDict(percentage_tuples)

percentage_dict will be ordered by portion from high to lower.

to print it out:

for item in percentage_tuples:
    print("%d%% is '%s'" % (item[1], item[0]))

Upvotes: 0

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

One way. I'm sure there will be better ways to do it.

   import collections
   d = collections.defaultdict(float)

   ip = [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]
   length = len(ip)

   for i in ip:
       d[i] += 1

   for i in d:
       print "%5d : %.2f%%" % (i, (d[i]/length) * 100)

Upvotes: 3

rodrigo
rodrigo

Reputation: 98358

Not a simple function, but a bit of list comprehension:

x = [2345,67,24,24,11,11,6,6,6,6,6,3,3,3,3,3,1,1,1,1,1,1]
print [(i,x.count(i) * 100 / len(x)) for i in set(x)]

Will print

[(1, 27), (67, 4), (6, 22), (2345, 4), (11, 9), (3, 22), (24, 9)]

That are pairs of element / percent.

Upvotes: 0

Related Questions