@andrewjorgensen/wordsums

A program to answer a difficult elementary school math assignment.

Files

- main.py
- words

main.py

# How many answers to find for each COUNT=30 # These are the letters a-z from string import ascii_lowercase as letters # Assign values to each letter as given in the assingment # stored as a dictionary with a: -13 and so on. v = dict(zip(letters, range(-13, 13))) # To store tuples of the calculated values calculations = [] # "words" is a word list with one English word per line with open('words', 'r') as words: for word in words: # Each line has a '\n' newline at the end, so strip it word = word.strip() # Ignore words that have capital letters or other characters if not set(word).issubset(set(letters)): continue # Enumerate the assigned values for letters in the word values = list((v.get(l, 0) for l in word)) # String together a calculation (like +5-2+3...) calculation = ''.join(('%+d' % v for v in values)) # Add a tuple of the word, the "show your work", and the total calculations.append((word, calculation, sum(values))) # Sort the calculations by word length calculations = sorted(calculations, key=lambda a: len(a[0])) print('Find a word that has a value of 18.') # Let's grab the longest five and the shortest 10 eighteens = list((c for c in calculations if c[2] == 18)) for answer in eighteens[:COUNT] + eighteens[-COUNT:]: print('%s: %s=%d' % answer) print('Find a word that has a value of -16.') # Let's grab the longest five and the shortest 10 minussixteens = list((c for c in calculations if c[2] == -16)) for answer in minussixteens[:COUNT] + minussixteens[-COUNT:]: print('%s: %s=%d' % answer) # The next two questions are about values of 5 fives = list((c for c in calculations if len(c[0]) == 5)) # Sort from highest value to lowest fives = sorted(fives, key=lambda a: - a[2]) print('Find the highest value 5 letter word you can.') for answer in fives[:COUNT]: print('%s: %s=%d' % answer) print('Find the lowest value 5 letter word you can.') for answer in fives[-COUNT:]: print('%s: %s=%d' % answer)

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux