Entropy: Difference between revisions

→‎Python: More succinct version: move constant operations out of the sum
(Fixed go map version for unicode strings)
(→‎Python: More succinct version: move constant operations out of the sum)
Line 2,567:
 
===Python: More succinct version===
 
The <tt>Counter</tt> module is only available in Python >= 2.7.
<syntaxhighlight lang="python">from math import log2
>>> from collections import Counter
 
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return log2(lns) - sum( count/lns * math.loglog2(count/lns, 2) for count in p.values()) / lns
 
print(entropy("1223334444"))</syntaxhighlight lang="python">>>> import math
{{out}}
>>> from collections import Counter
<pre>1.8464393446710154</pre>
>>>
>>> def entropy(s):
... p, lns = Counter(s), float(len(s))
... return -sum( count/lns * math.log(count/lns, 2) for count in p.values())
...
>>> entropy("1223334444")
1.8464393446710154
>>> </syntaxhighlight>
 
===Uses Python 2===
559

edits