This code asks for letters and a number of letters per word and generates all possible permutations. Then compares those permutations with an English dictionary and creates a list with all the words that match with the dictionary. Finally, it prints the list on a new terminal. The problem is that when words are long (about 10 letters each) I run out of memory. Any suggestions to improve this code and to try to solve the memory problem?
EDIT: my aim is to get 'real' words after typing some letters (e.g input: wxtisneo; letters_per_word: 3; output: one, two, six...)
import os
import itertools
import string
import sys
from sets import Set
def check_files():
if 'all_combinations_list.txt' in os.listdir('/tmp'):
os.remove('/tmp/real_words.txt')
def factorial_formula(v):
a = 1
if v < 0:
return 0
elif v == 0:
return 1
else:
for i in range(2, v+1):
a = a*i
return a
def combinations_formula():
w = len(split_letters)
x = factorial_formula(w)
y = (w - number_input)
z = factorial_formula(y)
total = x / z
return total
def possible_existing_words():
dictionary = [i.strip() for i in open('/usr/share/dict/american-english').readlines()]
raw_all_combinations = list(itertools.permutations(split_letters, number_input))
all_combinations = [''.join(word) for word in raw_all_combinations]
real = set(all_combinations).intersection(dictionary)
real_2 = list(real)
output_file = open('/tmp/real_words.txt', 'w')
with open('/tmp/real_words.txt', 'w') as out:
for e in real_2:
separated_words = str(e)
print >>out, separated_words
os.system("gnome-terminal -e 'bash -c \"cat /tmp/real_words.txt; exec bash\"'")
print ''' FINISHED
'''
if __name__ == "__main__":
os.system('clear')
check_files()
letter_input = raw_input(' Type in letters: ')
number_input = int(raw_input(' Letters per word: '))
split_letters = list(letter_input)
letter_input
number_input
if ' ' in split_letters:
print '''
ERROR: White space typed
'''
sys.exit()
elif len(split_letters) < number_input:
print '''
ERROR: More letters in word than typed
'''
sys.exit()
print '''
Creating %s different combinations...''' % combinations_formula()
print ' Detecting dictionary matches...'
possible_existing_words()
sys.exit()