我正在努力调试Python的有效方法,以及因此缺乏理解和优化。
我正在用Python编写一个Scrabble游戏作为一个实验,我怀疑我这一切都错了。也就是说,我无法理解如何处理空白区块(由下面的问号表示)。我把代码弄糟如下:
import itertools
import string
rack = 'rstlena??'
blank_count = rack.count('?')
letters = rack.split(',')
word_set = set()
if blank_count > 0:
rack = rack.replace('?', '')
if blank_count == 1:
for l in string.ascii_lowercase:
letters.append(rack + l)
elif blank_count == 2:
for l in string.ascii_lowercase:
letters.append(rack + l + l)
for l_combo in rack:
for i in range(3, 9):
for permutation in itertools.permutations(l_combo, i):
word_to_check = ''.join(permutation)
if word_to_check in word_list: # word_list is some dictionary
word_set.add(word_to_check)
...
当有一个空白时它起作用,但有两个它只是添加相同的字母并产生不希望的结果(显然)。
我提前为你让我畏缩的丑陋代码道歉。
答案 0 :(得分:0)
这应该有效,而且速度可以接受。我试着评论棘手的部分,不要犹豫,问你是否有一些你不理解的代码。
import itertools
import string
import numpy as np
#takes a list of words as input ['door', 'chair', 'wall'], and returns the words alphabetically sorted [['door', 'door'], ['achir', 'chair'], ['allw', 'wall']]
def sortWordList(word_list):
return np.array([["".join(sorted(word)), word] for word in word_list])
#recursive function to get all unordered n-letter subsets of `letters`, without repetition. NLetterSubsets(2, "fly") == ["fl", "fy", "ly"]; NLetterSubsets(2, "foo") == ["fo", "fo", "oo"]
def NLetterSubsets(n, letters):
if n == len(letters):
return [letters]
if n > len(letters) or len(letters) == 0:
return []
return [letters[0] + x for x in NLetterSubsets(n-1, letters[1:])] + NLetterSubsets(n, letters[1:])
#loads word_list from a newline-separated file
def loadWordList(filename):
with open(filename, 'r') as f:
return [line.rstrip('\n') for line in f]
word_list = loadWordList('words.txt')
word_list = sortWordList(word_list)
print(word_list)
rack = 'trackable'
blank_count = rack.count('?')
if blank_count:
rack = rack.replace('?','')
word_set = set()
#possible letters is the list of all possible values taken by the blank(s)
possibleLetters = ['']
if blank_count >= 1:
possibleLetters += [l for l in string.ascii_lowercase]
if blank_count == 2:
possibleLetters += [l+m for l in string.ascii_lowercase for m in string.ascii_lowercase]
for blanks in possibleLetters:
for i in range(3-len(blanks), 9-len(blanks)):
#gets a subset of letters from rack, to which we will add the blank values to form a word of length in range(3,9)
for setOfLetter in NLetterSubsets(i-blank_count, rack):
sortedWordToSearchFor = ''.join(sorted(setOfLetter + blanks))
#if the sorted list of letters we have is also present in the word_set, then take the associated word
for index in np.where(word_list[:,0] == sortedWordToSearchFor)[0]:
word_set.add(word_list[index][1])
print(word_set)