我可以做些什么来加速拼写欺骗的代码?

时间:2017-11-28 14:17:13

标签: python json

我正在创建一个接受7个字母的python脚本,并返回最高得分词以及所有其他可能的词。目前它有一些“循环循环”和其他会减慢过程的事情。

import json
#open file and read the words, output as a list

def load_words():
    try:
        filename = "dictionary_2.json"
        with open(filename,"r") as english_dictionary:
            valid_words = json.load(english_dictionary)
            return valid_words

    except Exception as e:
        return str(e)

#make dictionary shorter as there will be maximum 7 letters
def quick():
    s = []
    for word in load_words():
        if len(word)<7:
            s.append(word)
    return s


# takes letters from user and creates all combinations of the letters
def scrabble_input(a):
    l=[]
    for i in range(len(a)):
        if a[i] not in l:
            l.append(a[i])
        for s in scrabble_input(a[:i] + a[i + 1:]):
            if (a[i] + s) not in l:
                l.append(a[i] + s)

    return l

#finds all words that can be made with the input by matching combo's to the dictionary and returns them
def word_check(A):
    words_in_dictionary = quick()
    for word in scrabble_input(A):
        if word in words_in_dictionary:
            yield word


#gives each word a score
def values(input):
    # scrabble values
    score = {"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}
    word_total = 0
    for word in word_check(input):
        for i in word:
            word_total = word_total + score[i.lower()]
        yield (word_total, str(word))
        word_total = 0

#prints the tuples that have (scrabble score, word used)
def print_words(a):
    for i in values(a):
        print i

#final line to run, prints answer
def answer(a):
    print ('Your highest score is', max(values(a))[0], ', and below are all possible words:')
    print_words(a)

answer(input("Enter your 7 letters"))

我删除了一些for循环并尝试通过将其限制为最多7个字母单词来使我发现的json字典更短。我想我最初可以这样做,所以每次运行脚本时都不需要这样做。关于如何加快速度的其他任何提示?

0 个答案:

没有答案