Last active
March 14, 2018 07:53
-
-
Save wynand1004/7356b734378a381d4031c5d05af7a15c to your computer and use it in GitHub Desktop.
Something I saw on Reddit and decided to give a try. Link in header.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Coding Challenge | |
# Reddit: https://www.reddit.com/r/learnprogramming/comments/847ckg/i_failed_a_coding_interview_but_then_afterwards/ | |
# The problem was given a file of sentences, one sentence per line, | |
# implement a function that takes in 2 words, prob(a, b), | |
# and outputs the probability of a occurring given that the | |
# preceding word is b. | |
# Some test data already in a list with punctuation removed | |
sentences = ["Please buy me a drink", | |
"Please buy me a drink Bob", | |
"Please get me a drink Sue", | |
"Please find me a drink Joe", | |
"Please give me a Coke Joe" | |
] | |
def prob(a, b, sentences): | |
"""Probability of a occurring given that b is the preceding | |
word in the supplied sentences""" | |
# Text stores all text | |
text = "" | |
# Could use join but let's use a loop | |
for sentence in sentences: | |
text += " " + sentence.lower() | |
# Create a list of all the words | |
words = text.split(" ") | |
# Keep track of how many a and b there are | |
a_count = 0 | |
b_count = 0 | |
# Iterate through the list and find the word b | |
for index in range(len(words)-1): | |
if words[index] == b.lower(): | |
b_count += 1 | |
# If the next word is a | |
if words[index+1] == a.lower(): | |
a_count += 1 | |
# Calculate the probability | |
if b_count != 0: | |
probability = float(a_count) / float(b_count) | |
else: | |
probability = "{} not found".format(b) | |
# Show result | |
print("{}: {} {}: {} Probability: {}".format(a, a_count, b, b_count, probability)) | |
print("\n\nTest Results\n") | |
prob("drink", "a", sentences) | |
prob("me", "drink", sentences) | |
prob("buy", "Please", sentences) | |
prob("get", "cheer", sentences) | |
print("\n\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment