Demo entry 2821726

hangman

   

Submitted by anonymous on Oct 06, 2015 at 06:04
Language: Python. Code size: 2.3 kB.

import operator

def probability_l_given_word(l, key):
    if l in key:
        return 1.0
    return 0.0
    
def probability_word_given_evidence(key, incorrect, correct, denominator):
    e_given_w = probability_evidence_given_word(key, incorrect, correct)
    if e_given_w == 0.0:
        return 0.0
    word = float(word_counts[key])/total_count
    return e_given_w*word/denominator
    
def denominator(incorrect, correct):
    d = 0.0
    for key in word_counts:
        e_given_w = float(probability_evidence_given_word(key, incorrect, correct))
        word = float(word_counts[key])/total_count
        d += e_given_w*word
    return d
    
def probability_evidence_given_word(key, incorrect, correct):
    for i in range(0, len(key)):
        if correct[i] == '_':
            if key[i] in incorrect:
                return 0.0
        else:
            if correct[i] != key[i]:
                return 0.0
    return 1.0

f = open('hw1_word_counts_05.txt', 'r')
lines = f.read().split('\n')

total_count = 0
word_counts = {}
n = 0

for line in lines[:-1]:
    w = line.split(' ')
    word_counts[w[0]] = float(w[1])
    total_count += float(w[1])
    n += 1
sorted_f = sorted(word_counts.items(), key=operator.itemgetter(1), reverse = True)
print("Most Frequent: " + str([t[0] for t in sorted_f[:8]]))
print("Least Frequent: " + str([t[0] for t in sorted_f[-14:]]))

incorrect = raw_input('incorrectly guessed: ')
correct = raw_input('correctly guessed: ')
incorrect += correct

letters = {'A':0,'B':0,'C':0,'D':0,'E':0,'F':0,'G':0,'H':0,'I':0,'J':0,'K':0,'L':0,'M':0,'N':0,'O':0,'P':0,'Q':0,'R':0,'S':0,'T':0,'U':0,'V':0,'W':0,'X':0,'Y':0,'Z':0}
d = denominator(incorrect, correct)
for l in letters:
    prob = 0.0
    if l in incorrect:
        letters[l] = float(prob)
        print(l+" : "+str(prob))
        continue
    for key in word_counts:
        l_given_word = float(probability_l_given_word(l,key))
        word_given_evidence = probability_word_given_evidence(key, incorrect, correct, d)
        prob += l_given_word*word_given_evidence
    letters[l] = float(prob)
    print(l+" : "+str(prob))
    
print("Next Best Guess" + str(max(letters.iteritems(), key=operator.itemgetter(1))))

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).