【问题标题】:How to check if a word can be created from the letters in a list?如何检查是否可以从列表中的字母创建单词?
【发布时间】:2021-01-15 09:44:21
【问题描述】:

我正在尝试做一些类似拼字游戏的事情。

letters = ['s','w','r','a']
line_of_dic= ['s','w','r','a','a']


# printing original lists
print("Original list : " + str(line_of_dic))
print("Original sub list : " + str(letters))

# using all() to
# check subset of list
flag = 0
if (all(x in line_of_dic for x in letters)):
    flag = 1

# printing result
if (flag):
    print("Yes, the word can be created")
else:
    print("No, the word cant be.")

这是我无法修复的部分代码,无法创建单词,但打印的是 yes。是否可以检查所有字母是否都在line_of_dic 中,但是如果元素加倍或加倍来检查呢?另外,可以不用花哨的库吗?

【问题讨论】:

  • 你说的是什么意思,但是如果元素加倍或加倍来检查这个
  • without fancy libraries - 你可以使用内置的python模块吗?
  • 我的意思是在这个例子中 dic 行中的单词不能从上面的字母中创建,但这里的输出是它可以。
  • @MauriceMeyer OP 希望仅在 line_of_dic 中的每个字符的相同计数出现在 letters 时才返回 Yes。他们希望能够从letters 构建line_of_dic 的内容。
  • @wwii 是的,我可以使用它们

标签: python string list char


【解决方案1】:

您需要计算每个单词中每个字符的个数,然后比较这些值。你可以用字典来做到这一点。

ltrs = {}
lod = {}

for char in letters:
    ltrs[char] = ltrs.get(char,0) + 1

for char in line_of_dic:
    lod[char] = lod.get(char,0) + 1

然后你可以看看每个字符是否足够组成单词。

In [3]: ltrs
Out[3]: {'a': 1, 'r': 1, 's': 1, 'w': 1}

In [4]: lod
Out[4]: {'a': 2, 'r': 1, 's': 1, 'w': 1}

collections.Counter 可以为你制作那些字典。

import collections
ltrs = collections.Counter(letters)
lod = collections.Counter(line_of_dic)

In [6]: ltrs
Out[6]: Counter({'a': 1, 'r': 1, 's': 1, 'w': 1})

In [7]: lod
Out[7]: Counter({'a': 2, 'r': 1, 's': 1, 'w': 1})

减去Counters就可以看是否够了。

In [31]: lod-ltrs
Out[31]: Counter({'a': 1})

lodltrs 多一个'a'

【讨论】:

    【解决方案2】:

    这可以通过比较每个字母的数量在一行中完成:

    flag = 0
    if all(line_of_dic.count(char) == letters.count(char) for char in line_of_dic):
        flag = 1
    

    不是检查字母是否存在,而是检查计数是否匹配。

    【讨论】:

    • 很好的解决方案,感谢您的帮助
    【解决方案3】:

    您可以使用字典结构。要从列表创建字典,您可以编写一个简单的代码:

    letterDict = {}
    lineDict = {}
    
    for item in letters:
        if item not in letterDict:
            letterDict[item] = 1
        else:
            letterDict[item] += 1
            
    for item in line_of_dic:
        if item not in lineDict:
            lineDict[item] = 1
        else:
            lineDict[item] += 1
    

    在那之后,您可以简单地比较两个字典:

    if letterDict == lineDict:
        print("Yes, the word can be created")
    else:
        print("No, the word cant be.")
    

    【讨论】:

    • 感谢您的解决方案
    猜你喜欢
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多