MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / calculate_prob

Function calculate_prob

maths/entropy.py:15–90  ·  view source on GitHub ↗

This method takes path and two dict as argument and than calculates entropy of them. :param dict: :param dict: :return: Prints 1) Entropy of information based on 1 alphabet 2) Entropy of information based on couples of 2 alphabet 3) print Entropy of H(X n|Xn-1)

(text: str)

Source from the content-addressed store, hash-verified

13
14
15def calculate_prob(text: str) -> None:
16 """
17 This method takes path and two dict as argument
18 and than calculates entropy of them.
19 :param dict:
20 :param dict:
21 :return: Prints
22 1) Entropy of information based on 1 alphabet
23 2) Entropy of information based on couples of 2 alphabet
24 3) print Entropy of H(X n|Xn-1)
25
26 Text from random books. Also, random quotes.
27 >>> text = ("Behind Winston's back the voice "
28 ... "from the telescreen was still "
29 ... "babbling and the overfulfilment")
30 >>> calculate_prob(text)
31 4.0
32 6.0
33 2.0
34
35 >>> text = ("The Ministry of Truth—Minitrue, in Newspeak [Newspeak was the official"
36 ... "face in elegant lettering, the three")
37 >>> calculate_prob(text)
38 4.0
39 5.0
40 1.0
41 >>> text = ("Had repulsive dashwoods suspicion sincerity but advantage now him. "
42 ... "Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. "
43 ... "You greatest jointure saw horrible. He private he on be imagine "
44 ... "suppose. Fertile beloved evident through no service elderly is. Blind "
45 ... "there if every no so at. Own neglected you preferred way sincerity "
46 ... "delivered his attempted. To of message cottage windows do besides "
47 ... "against uncivil. Delightful unreserved impossible few estimating "
48 ... "men favourable see entreaties. She propriety immediate was improving. "
49 ... "He or entrance humoured likewise moderate. Much nor game son say "
50 ... "feel. Fat make met can must form into gate. Me we offending prevailed "
51 ... "discovery.")
52 >>> calculate_prob(text)
53 4.0
54 7.0
55 3.0
56 """
57 single_char_strings, two_char_strings = analyze_text(text)
58 my_alphas = list(" " + ascii_lowercase)
59 # what is our total sum of probabilities.
60 all_sum = sum(single_char_strings.values())
61
62 # one length string
63 my_fir_sum = 0
64 # for each alpha we go in our dict and if it is in it we calculate entropy
65 for ch in my_alphas:
66 if ch in single_char_strings:
67 my_str = single_char_strings[ch]
68 prob = my_str / all_sum
69 my_fir_sum += prob * math.log2(prob) # entropy formula.
70
71 # print entropy
72 print(f"{round(-1 * my_fir_sum):.1f}")

Callers

nothing calls this directly

Calls 1

analyze_textFunction · 0.85

Tested by

no test coverage detected