【问题标题】:check an entered word by a user can be made from a given list of letters?检查用户输入的单词是否可以从给定的字母列表中生成?
【发布时间】:2020-11-18 16:38:14
【问题描述】:

我用它随机打印了一个包含 7 个字母的列表。

import random

Tiles = open("tiles", "r")
Tiles = Tiles.readlines()
listoftiles = []
for x in Tiles:
listoftiles.append(x.split()[0])
for i in range (0,7):
mytiles = []
mytiles += random.choice(listoftiles)
print(mytiles)

outputs:
['E']
['X']
['W']
['X']
['O']
['W']
['I']

然后,变量“单词”允许用户使用上面给定的字母输入单词,这些字母是 [E,X,W,X,O,W,I]

word = input("Enter word: ")

output:
Enter word: "..."

我需要创建一个接受两个参数“word & tile”的函数,然后该函数检查该词是否可以用上面给定的字母组成。如果单词可以使用字母组成,则输出应该为真,如果单词不能使用字母组成,则输出应该为假。到目前为止,这是我能够做到的:

def checker(word,mytiles):
    for letters in word.split():
    if letters in mytiles == word:
        print("This word can be made")
        return True
print("This word cannot be made")
return False

输出:the complier doesn't run the code

更重要的是,这是我想添加的一个功能,以完成我正在为一个项目制作的拼字游戏。

【问题讨论】:

  • 注意缩进
  • 您的问题得到解答了吗?
  • 解释器报什么错误??
  • 我的编译器没有返回输出,可能是代码或我的编译器有问题
  • 当我试图运行代码时,写在 cmets.编译器没有计算输出似乎是有道理的。 def checker(word,mytiles): for letter in word: found = False for tile in mytiles: if letter == tile: found = True mytiles.remove(tile) break if found == False: return False return True

标签: python arrays list function


【解决方案1】:

您最好的方法是循环目标单词的每个字母,并使用另一个嵌套循环检查该字母是否存在于您可用的图块中。如果是,则将其从图块中删除,否则立即返回 false,因为即使缺少一个字母也无法完成单词。如果您在磁贴中搜索字母但磁贴为空,您仍然返回 false,因为您没有更多可用的磁贴。

这里:

def checker(word, tiles):
    for letter in word:
        found = False
        for tile in tiles:
            if letter == tile:
                found = True
                tiles.remove(tile)
                break
        if found == False:
            return False
    return True

如果 word 是字符串或列表,并且 tiles 是字符列表,则此代码将起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 2021-10-23
    相关资源
    最近更新 更多