Skip to content

Instantly share code, notes, and snippets.

@jColeChanged
Created March 5, 2011 03:05
Show Gist options
  • Save jColeChanged/856057 to your computer and use it in GitHub Desktop.
Save jColeChanged/856057 to your computer and use it in GitHub Desktop.
def bayes(a, b_given_a, b_given_not_a):
"""Calculates P(a|b) using bayes theorem.
Bayes theorem states that:
P(b|a) * P(a)
P(a|b) = --------------------------------
P(b|a) * P(a) + P(b|~a) * P(~a)
Intuitively this is saying that the probability of b given a is equivalent
to the number of times both b and a occur over the number of time b occurs.
"""
b_and_a = a * b_given_a
b_and_not_a = b_given_not_a * (1 - a)
return b_and_a / (b_and_a + b_and_not_a)
if __name__ == "__main__":
a = input("P(a): ")
b_given_a = input("P(b|a): ")
b_given_not_a = input("P(b|~a): ")
print bayes(a, b_given_a, b_given_not_a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment