拼字游戏作弊:在Python中将通配符评分为零

时间:2019-02-16 11:36:19

标签: python

我是python世界的新手,我编写了一个带有两个通配符(*和?)的scrabble finder代码。在给单词评分时,我想将通配符的字母评分为零,但似乎不起作用。我想知道这里缺少什么。

当您查看“#将分数和有效单词添加到空列表”之后的行时,如果该单词中的字母不在机架中,我尝试进行编码,因此我删除了该字母,这样我只能对其他得分非通配符的字符,并且与机架中的字母匹配。例如,如果我的架子上有B *,而单词是BO,那么我想删除O并仅对B评分,以便可以将通配符评分为零。

但是结果不是我期望的。

import sys

if len(sys.argv) < 2:
    print("no rack error.")
    exit(1)

rack = sys.argv[1]
rack_low = rack.lower()

# Turn the words in the sowpods.txt file into a Python list.
with open("sowpods.txt","r") as infile:
    raw_input = infile.readlines()
    data = [datum.strip('\n') for datum in raw_input]

# Find all of the valid sowpods words that can be made
# up of the letters in the rack.
valid_words = []

# Call each word in the sowpods.txt
for word in data:
    # Change word to lowercase not to fail due to case.
    word_low = word.lower()
    candidate = True
    rack_letters = list(rack_low)
    # Iterate each letter in the word and check if the letter is in the
    # Scrabble rack. If used once in the rack, remove the letter from the rack.
    # If there's no letter in the rack, skip the letter.
    for letter in word_low:
        if letter in rack_letters:
            rack_letters.remove(letter)
        elif '*' in rack_letters:
            rack_letters.remove('*')
        elif '?' in rack_letters:
            rack_letters.remove('?')
        else:
            candidate = False
    if candidate == True:
        # Add score and valid word to the empty list 
        total = 0
        for letter in word_low:
            if letter not in rack_letters:
                word_strip = word_low.strip(letter)
                for letter in word_strip:
                    total += scores[letter]

        valid_words.append([total, word_low])

2 个答案:

答案 0 :(得分:0)

总计分数时,您使用的是单词列表中的单词,而不是输入的单词:

total=0
for letter in word_low:
    ...

相反,它应该是:

total=0
for letter in rack_low:
    ...

此外,您无需循环并删除末尾带有Strip的字母。 您可以拥有:

total = 0
for letter in rack_low:
    if letter not in rack_letters:
        try:
            total += scores[letter]
        except KeyError: # If letter is * or ? then a KeyError occurs
            pass

valid_words.append([total, word_low])

答案 1 :(得分:0)

我的回答将略有不同,希望可以加快整个过程。我们将从标准库中导入另一个函数-排列-然后通过根据机架的长度(或传递的任何参数)修整总可能的单词列表来找到可能的结果。

我已经发表了评论。

import sys
from itertools import permutations # So we can get our permutations from all the letters.

if len(sys.argv) < 2:
    print("no rack error.")
    exit(1)

rack = sys.argv[1]
rack_low = rack.lower()


# Turn the words in the sowpods.txt file into a Python list.
txt_path = r'C:\\\\\sowpods.txt'
with open(txt_path,'r') as infile:
    raw_input = infile.readlines()
    # Added .lower() here.
    data = [i.strip('\n').lower() for i in raw_input]

## Sample rack of 7 letters with wildcard character.
sample_rack = 'jrnyoj?'

# Remove any non-alphabetic characters (i.e. - wildcards)
# We're using the isalpha() method.
clean_rack = ''.join([i for i in sample_rack if i.isalpha()])

# Trim word list to the letter count in the rack.
# (You can skip this part, but it might make producing results a little quicker.)
trimmed_data = [i for i in data if len(i) <= len(clean_rack)]


# Create all permutations from the letters in the rack
# We'll iterate over a count from 2 to the length of the rack
# so that we get all relevant permutations.
all_permutations = list()
for i in range(2, len(clean_rack) + 1):
    all_permutations.extend(list(map(''.join, permutations(clean_rack, i))))


# We'll use set().intersection() to help speed the discovery process.
valid_words = list(set(all_permutations).intersection(set(trimmed_data)))


# Print sorted list of results to check.
print(f'Valid words for a rack containing letters \'{sample_rack}\' are:\n\t* ' + '\n\t* '.join(sorted(valid_words)))

我们的输出如下:

Valid words for a rack containing letters 'jrnyoj?' are:
    * jo
    * jor
    * joy
    * no
    * nor
    * noy
    * ny
    * on
    * ony
    * or
    * oy
    * yo
    * yon

如果您想验证结果是否确实在sowpods.txt文件中,则只需按要查找的单词的索引位置对sowpods.txt列表进行索引:

trimmed_data[trimmed_data.index('jor')]