【问题标题】:Find characters of this word in another word Python在另一个单词 Python 中查找该单词的字符
【发布时间】:2014-11-16 03:32:13
【问题描述】:

我正在做一个猜字游戏。因此,如果我得到消息lime-tree。然后我想检查该单词中可能出现的单词。如果我猜到了limetreetimereel 或者甚至不是一个真实的词等等,那么它们都是true,因为它们是由这个词组成的。如何检查猜测的单词是否在该单词中?

已编辑

我忘了提到字母不能超过给定单词中指定的数量。

【问题讨论】:

  • 一定要用字典吗?
  • 是不是-也包含在gues中???
  • 不,它不需要字典,也不必包含 - 我输入是因为给定的单词不是没有 - 的单词。
  • @user3650234 检查你想要的代码
  • @user3650234,能否更清楚word中的字母是否可以重复使用?像eeeeee 仍然可以使用给定的单词lime-tree?我的答案是Not in given_word,而其他答案可能会返回True?

标签: python string dictionary compare character


【解决方案1】:

这是一个简单的
我使用了count,如果在 new_word 中计数更多的是一个字母,它将返回错误。或最后返回正确。

>>> def word_check(original,new_word):
...     for x in new_word:
...         if new_word.count(x) > original.count(x):
...             return "Wrong"
...     return "Correct"
... 
>>> word_check('lime-tree','trel')
'Correct'
>>> word_check('lime-tree','treeel')
'Correct'
>>> word_check('lime-tree','treeeel')
'Wrong'
>>> word_check('lime-tree','mile')
'Correct'
>>> word_check('lime-tree','miilet')
'Wrong'

【讨论】:

  • 不幸的是,这也不正确,考虑一下:word_check('lime-tree', 'eeeeeee'),将返回不正确的Correct
  • 如果想要长度大于 1 可以进行验证,使用 len function
  • 嗯...好点,我认为 OP 不清楚字母是否可以重复使用,我不这么认为,否则给定的单词可能只是 'lim-tre'跨度>
  • 太棒了!我认为你的方法比我的更干净!尽管我在创建的游戏中使用了类似的逻辑,因为我需要对应部分。好东西人:)
【解决方案2】:

您可以使用Counter,计算给定单词中的所有字母,并从要检查的单词中减去字母,如下所示:

from collections import Counter


def check_in_given_word(given_word, to_check):
    given_word_counter = Counter(given_word)
    word_counter = Counter(to_check)
    given_word_counter.subtract(word_counter)
    #if any -ve letter count is found, it is not in given_word
    if any([c < 0 for c in given_word_counter.values()]):
        # do whatever you want, or return False
        print "{} is NOT in {}".format(to_check, given_word)
    else:
        print "{} is in {}".format(to_check, given_word)
    # print the counter for your info
    print given_word_counter

示例用法:

check_in_given_word('lime-tree', 'tree')
tree is in lime-tree
Counter({'e': 1, 'i': 1, 'm': 1, '-': 1, 'l': 1, 'r': 0, 't': 0})

check_in_given_word('lime-tree', 'reel')
reel is in lime-tree
Counter({'e': 1, 'i': 1, 'm': 1, '-': 1, 't': 1, 'l': 0, 'r': 0})

check_in_given_word('lime-tree', 'hello')
hello is NOT in lime-tree
Counter({'e': 2, 'i': 1, 'm': 1, '-': 1, 'r': 1, 't': 1, 'l': -1, 'o': -1, 'h': -1})

check_in_given_word('lime-tree', 'reeeeel')
reeeeel is NOT in lime-tree
Counter({'i': 1, 'm': 1, '-': 1, 't': 1, 'l': 0, 'r': 0, 'e': -2})

如您所见,所有字母都应该是 +ve 值。如果发现任何负值,则要检查的单词不在您给定的单词中。

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多