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
print(entropy("1223334444"))</syntaxhighlight
{{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())
▲1.8464393446710154
===Uses Python 2===
|