how to improve performance to run faster (python) -
right now, program takes more 10mins lol try display possible words (if words in file) can created given letters. in file, has more 4000+ words how make program run faster using recursion, , not using libraries because i'm new it.
if user input letters: b d o s y
then possible words in file create:
b d boy boys
the code:
words = set() def found(word, file): ## reads through file , tries ## match given word in line. open(file, 'r') rf: line in rf.readlines(): if line.strip() == word: return true return false def scramble(r_letters, s_letters): ## output every possible combination of word. ## each recursive call moves letter ## r_letters (remaining letters) ## s_letters (scrambled letters) if s_letters: words.add(s_letters) in range(len(r_letters)): scramble(r_letters[:i] + r_letters[i+1:], s_letters + r_letters[i]) thesarus = input("enter name of file containing of words: ") letters = input("please enter letters separated space: ") word = ''.join(letters.split(' ')) scramble(word, '') ll = list(words) ll.sort() word in ll: if found(word, thesarus): print(word)
you program runs slow because algorithm inefficient. since require in question use recursion (to generate possible combinations), improve @ least in how search in file.
your code open file , search single word reading every word. extremely inefficient.
first solution comes mind read file once , save each word in set()
words_set = {line.strip() line in open('somefile')}
or (less concise)
words_set = set() open('somefile') fp: line in fp: words_set.add(line.strip())
then, do
if word in words_set: print(word)
i think there more efficient ways whole program, don't require recursion.
update
for sake of discussion, think may useful provide algorithm better.
your code generates possible combinations, if not part of dictionary, in addition inefficient search in file each word.
a better solution involves storing words in more efficient way, such easier tell if particular combination exists or not. example, don't want visit (in file) words composed characters not present in list provided user.
there data structure believe quite effective kind of problems: trie (or prefix tree). data structure can used store thesaurus file, in place of set suggested above.
then, instead of generating possible combinations of letters, visit tree possible letters find possible valid words.
so, example, if user enters h o m e x
, have no word starting x
in thesaurus, not generate permutations starting x
, such xe, xo, xh, xm, etc, saving large amount of computations.
Comments
Post a Comment