HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Solver for Jumble puzzle

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
solverjumblepuzzlefor

Problem

Here is my first attempt to solve Jumble puzzle:

import argparse
from itertools import permutations

parser = argparse.ArgumentParser(description='Solver for Jumble')
parser.add_argument('jumbledwords', nargs='+',
                    help='One or more jumbled words')
argv = parser.parse_args()

# http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt
words = [line.rstrip() for line in open('wordsEn.txt')]
for jumbledword in argv.jumbledwords:
    perms = set([''.join(p) for p in permutations(jumbledword)])
    legalwords = [word for word in perms if word in words]
    # print(len(perms))
    print(jumbledword, legalwords)


Any suggestions for improvement?

Solution

Close what you open

words = [line.rstrip() for line in open('wordsEn.txt')]


Here you opened a file but you did not close it! In fact I suggest to use with that will handle closing automagically.

with open('wordsEn.txt') as f:
    words = [line.rstrip() for line in f.read()]


Let the user change the file

You should let the user input as an optional arg his own filename, I may have my own wordlist that is not called exactly: 'wordsEn.txt', the dafault file should be None (You read directly from the webpage).

set built-in operations

If you change the below line to be:

words = set([line.rstrip() for line in f.read().splitlines()])


You can then use set intersection:

legalwords = perms & words


To enhance both clarity and performance.

Allowing long words

The complexity of finding all the permutations of a word is O(N!): for a mere 20 characters word that means 2.432 * 10**18 combinations, I suggest comparing the sorted words for better efficiency if you need to run the script with long words.

Code Snippets

words = [line.rstrip() for line in open('wordsEn.txt')]
with open('wordsEn.txt') as f:
    words = [line.rstrip() for line in f.read()]
words = set([line.rstrip() for line in f.read().splitlines()])
legalwords = perms & words

Context

StackExchange Code Review Q#91496, answer score: 5

Revisions (0)

No revisions yet.