Reputation: 533
I'm trying to complete a python project that basically takes an input and goes through a list of valid scrabble words and determines which of those words can be made given the input.
The first part was somewhat easy, but the part that actually matters is giving me issues.
Here's what I have so far:
import argparse
import sys
"""
Step 1: Get input from the user
"""
parser = argparse.ArgumentParser()
parser.add_argument("rack", type=str, help = "letters on the rack (no spaces)")
args = parser.parse_args()
rack = args.rack
rack = rack.upper()
rack = sorted(rack)
"""
Step 2: Open the sowpods.txt file, read the contents and turn it into a list
"""
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
file = "sowpods.txt"
length = file_len(file)
file = open("sowpods.txt", 'r')
file_list = list(file)
for i in range(length):
value = file_list[i]
value = value.rstrip('\n')
file_list[i] = value
"""
Step 3: Find valid words
"""
#for x in range(len(file_list)):
for x in range(82980,83000):
tmp = rack
test = file_list[x]
pos = []
if len(test) > len(tmp):
break
else:
for y in range(len(test)):
letter = test[y]
if letter in tmp[y:(len(tmp))]:
pos.append(letter)
print(pos)
I'm sure it's very messy as I haven't programmed in a while, but I just want to figure out the part where the program checks for validity. Right now, the loop goes through a range where I know there are words that can be made from the rack but I'm stuck. I've looked at this post on some help, but to be honest, I'm not really sure what's going on.
I may be going a little over my head here, but I'd still like to figure this out.
Upvotes: 0
Views: 3670
Reputation: 142166
The easiest way to check if words are valid is to use a collections.Counter
. You take the occurrences of each letter in the rack, and the occurrences of each letter for each scrabble word then take the difference. If there's nothing left of the scrabble word after removing the letters from the rack, then you can make the scrabble word.
Example code (use the dictionary provided instead of a system one):
from collections import Counter
with open('/usr/share/dict/words') as fin:
lines = (word.strip().upper() for word in fin)
words = [(word, Counter(word)) for word in lines]
rack = Counter('AEDTUMS')
for scrabble_word, letter_count in words:
# Using length here to limit output for example purposes
if len(scrabble_word) >= 6 and not (letter_count - rack):
print(scrabble_word)
Will give you:
MEDUSA
AMUSED
SAUTED
Upvotes: 2