首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数来比较单词,解决Python中的单词游戏。

函数来比较单词,解决Python中的单词游戏。
EN

Stack Overflow用户
提问于 2022-09-09 11:12:20
回答 1查看 66关注 0票数 -1

我试图找到/编写一个函数来比较Python程序中解决单词谜题游戏中的两个单词。游戏的目标是使用一组9个字母创建尽可能多的单词,单词可以在4到9个字母之间(单词是原始9个字母的字谜,但不必是9个字母长)。这组9个字母作为字符串从用户中读取。基本上,函数需要检查单词列表(txt文件,转换为字符串列表)中的单词是否是用户输入的字谜,如果是,则将单词打印到屏幕上。

我尝试过python ()函数,但是它没有工作,因为它没有考虑到用户输入中字符的频率(例如:如果用户输入只包含两个A,则如果包含两个以上的A,则不应该打印word )。

EN

回答 1

Stack Overflow用户

发布于 2022-09-09 12:00:14

你可以用这样的东西:

代码语言:javascript
复制
# Prints all the anagrams
def check(letters, word):
    if(sorted(letters) <= sorted(word)):
        print(word)
# NOTE: 'letters' is the user input. As this function is going to be called a lot of times, user input should be sorted outside this function.
代码语言:javascript
复制
# Cabs: True
check('aabbcccss', 'cabs')
# Array: False (two A's needed and two R's needed)
check('aryqwetyu', 'array')

如果您想知道用户输入中没有包含的每个单词的字母,可以使用计数器:https://docs.python.org/3/library/collections.html#collections.Counter.subtract

代码语言:javascript
复制
from collections import Counter

# Prints the letters included in the word, but not included in the user's input
def check(letters, word):
    print(f'{letters} - {word}')
    c = Counter(letters)
    w = Counter(word)
    c.subtract(w)
    for k,v in dict(c).items():
        if v < 0:
            print(f'{-v} {k}\'s missing.')
    print('--------')
代码语言:javascript
复制
# cabs - aabbcccss
# --------
check('aabbcccss', 'cabs')
# array - aryqwetyu
# 1 a's missing.
# 1 r's missing.
# --------
check('aryqwetyu', 'array')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73661265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档