Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
cisc/entropy.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
21 lines (17 sloc)
494 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Computes entropy of a sequence of messages | |
""" | |
from __future__ import division | |
from collections import Counter | |
from math import log | |
def entropy(sequence): | |
res = 0 | |
n = len(sequence) | |
counts = Counter(sequence).values() | |
for count in counts: | |
res -= (count / n) * (log(count, 2) - log(n, 2)) | |
return res | |
if __name__=="__main__": | |
print entropy([1, 2, 1, 1, 1, 1]) | |
print entropy([1, 1, 1, 1, 1, 1]) | |
print entropy([1, 1, 1, 2, 2, 2]) |