-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprobability.py
More file actions
40 lines (31 loc) · 1.2 KB
/
probability.py
File metadata and controls
40 lines (31 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# probability.py
from math import log
def probabilities (X) -> dict:
""" This function maps the set of outcomes found in the sequence of events, 'X', to their respective probabilty of occuring in 'X'.
The return value is a python dictionary where the keys are the set of outcomes and the values are their associated probabilities."""
# The set of outcomes, denoted as 'C', and the total events, denoted as 'T'.
C, T = set(X), len(X)
return {c: X.count(c) / T for c in C}
def shannon (P, b : int = None) -> float:
""" Shannon or Informational Entropy
Calculates the shannon entropy, denoted as 'H', of a discrete random variable, 'X'.
Parameters:
1.) P: An iterable of probabilities associated with the set of outcomes of 'X'.
2.) b: The logarithmic base used in calculating 'H'. The default value is len(P). """
# Check params.
if b == None: b = len(P)
if b <= 0: raise ValueError('Argument Value Error:\tThe logarithmic base must be a positive integer.')
# Init return value.
res = 0
for p in P:
res += p*log(p)
res /= log(b)
return -res
def main(args):
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))