将分数添加到循环函数中

3

这是我参加一次面试时需要重新制作华尔街拼写比赛的谜题。每个谜题包含七个不同的字母(第一个是关键字母),按照以下规则尽可能多地提出单词。

  • 所有单词都是有效的英语单词。
  • 单词包含关键字母。
  • 单词不包含七个字母之外的任何字母。
  • 可以重复使用字母,包括关键字母。

例子

输入:

  • wordlist = ['apple','pleas','please']
  • puzzels = ['aelwxyz','aelpxyz','aelpsxy','saelpxy','xaelpsy'] 期望输出:
  • [0,1,3,2,0]

解释

  • 单词列表中没有任何单词可以从谜题 0 中的字母组成
  • 仅有的一个"apple"可以用于谜题 2
  • 所有三个单词都可以用于谜题 3
  • "pleas" 和 "please" 可以用于谜题 3,因为 "apple" 没有关键字母 S
  • 没有单词可以用于谜题 4,因为没有单词有关键字母 X

因此,我用了 75 分钟来解决它,取得了一定的成果,但无法找到一个关键步骤。我无法使分数正确显示,只能手动排序单词列表。我尝试添加一些计数器,但无法让它们正常工作。


test_list = ["apple","pleas","please"]
puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]
puzzles_list = ["a","e","l","p","s","x","y"]




def check_words(letters,words):
    i = 1
    score = 0
    letters = list(letters)
    for word in words:
        if all(x in set(letters) for x in word) and letters[0] in word:
            #this checks if the word contains any letter from the word and the first letter(aka key letter)
            print("test passed")
            score +=1
            print(word,letters,i)
            print(score)
            return 
            #here we have to add a value to a counter to show for that set of letters how many words it can spell. 
            if all(x in set(word) for x in letters):
                #only if the puzzle and the word match exactly aka apple would have to only have a,p,l,e in the test
                print(word,letters)
            else:
                return
        else:
            print("no matching letters and or not matching key letter.")
            return

def spelling_bee_solutions(wordlist,puzzles):
    for puzzle in puzzles:
        puzzle = list(puzzle)
        check_words(puzzle,wordlist)



# check_words(puzzles_list,test_list)

spelling_bee_solutions(test_list,puzzles)

我本想将分数添加到字典中或追加到列表中,但时间不够。我主要只是想看看真正的解决方案会是什么。

到目前为止,它只是在打印输出。

no matching letters and or not matching key letter.
test passed
apple ['a', 'e', 'l', 'p', 'x', 'y', 'z'] 1
1
test passed
apple ['a', 'e', 'l', 'p', 's', 'x', 'y'] 1
1
no matching letters and or not matching key letter.
no matching letters and or not matching key letter.

嗨,欢迎来到 Stack Overflow。你能否提供一个 [mcve] 给我们? - pythonic833
嘿,感谢@pythonic833的欢迎。我正在处理最小示例,但解决方案已经在我添加之前发布了。 - Brogan Stich
1个回答

1
你可以使用列表推导式将每个谜题映射到一个生成器表达式的总和,该表达式迭代单词列表并输出1(如果谜题中的字符集是单词中字符集的超集,并且谜题中的第一个字符在单词中):
[sum(set(p) >= set(w) and p[0] in w for w in wordlist) for p in puzzles]

This returns:

[0, 1, 3, 2, 0]

你可以通过先将单词列表转换为字符集合列表来进一步优化它,这样集合转换就不必每次迭代都进行:
wordsets = list(map(set, wordlist))
[sum(w.issubset(p) and p[0] in w for w in wordsets) for p in puzzles]

1
哇,这让它变得如此简单。完全有效。我永远不会想到那个解决方案。我不知道你可以这样使用sum。谢谢! - Brogan Stich

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接