Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Moria Doors by Krischtopp
import string
def find_word(message):
# Convert message to lowercase, remove punctuation, split into words and reverse word order
# (we want the last word instead of the first in case multiple words have the same likeness sums)
message = "".join(char for char in message.lower() if char not in string.punctuation).split()[::-1]
sums = []
for word in message:
# Calculate sums. It doesn't matter if we calculate likeness of a word with itself,
# because it will not change which words will have the highest sum
sums.append(sum(calculate_likeness(word, other_word) for other_word in message))
# It's not necessary to calculate average to find the key word, so we just do max(sums)
return message[sums.index(max(sums))]
def calculate_likeness(word1, word2):
likeness = 0
if word1[0] == word2[0]: # Beginning
likeness += 10
if word1[-1] == word2[-1]: # Ending
likeness += 10
if len(word1) <= len(word2): # Compare length
likeness += 30 * len(word1) / len(word2)
else:
likeness += 30 * len(word2) / len(word1)
likeness += 50 * len(set(word1) & set(word2)) / len(set(word1) | set(word2)) # Compare unique letters
return likeness
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert find_word("Speak friend and enter.") == "friend", "Friend"
assert find_word("Beard and Bread") == "bread", "Bread is Beard"
assert find_word("The Doors of Durin, Lord of Moria. Speak friend and enter. "
"I Narvi made them. Celebrimbor of Hollin drew these signs") == "durin", "Durin"
assert find_word("Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy."
" According to a researcher at Cambridge University.") == "according", "Research"
assert find_word("One, two, two, three, three, three.") == "three", "Repeating"
Jan. 26, 2016
Comments: