""" conditional_example.py in class Feb 21 """ a = 'a' b = 'b' c = 'c' text = (a, b, a, a, c, a, b) pairs = [] for i in range(len(text) - 1): pairs.append( (text[i], text[i+1]) ) # print(pairs) # Or in one line: pairs = zip(text[:-1], text[1:]) def p_2nd(second, first): """ Return p(second=2nd | first=1st) conditional probability """ # uses global "pairs" variable matches_first = [y for (x,y) in pairs if x == first] matches_both = [1 for y in matches_first if y == second] return len(matches_both) / len(matches_first) def p_2nd_kenny(second, first): """ same (copyright 'the K')""" count_matches_first = 0 count_matches_both = 0 for (x, y) in pairs: if x == first: count_matches_first += 1 if y == second: count_matches_both += 1 return count_matches_first / count_matches_second