比较字符串字符与Python字典

2024-09-28 01:29:24 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在做作业,有点卡住了。寻找一些帮助来解决这个问题。我正在尝试一个函数,它接受用户输入的两个值:杂志和赎金。如果赎金中的字符可以在杂志中找到,我想返回它是真的,否则如果赎金字符串不能在杂志中找到字符串返回假。ransom被拆分成一个字典{key,vaue},例如用户输入:

杂志:你好

输入赎金:你好

{'h':1,'e':1,'l':2,'o':1}

{'h':1,'e':1,'l':1,'o':1}

它应该返回true,但返回false,因为它不计算“hello”中的第二个“l”。我做错什么了?你知道吗

def compare(magazine, ransom):
matches = {}
for ch in ransom:
    if ch in magazine:
        if ch in matches:
            matches[ch] += 1
        else:
            matches[ch] = 1

if ransom in matches:
    return True
else:
    return False

Tags: 函数字符串用户inreturnifch字符
1条回答
网友
1楼 · 发布于 2024-09-28 01:29:24

if ransom in matches:

首先,这个比较似乎是错误的,ransem应该是一个由用户输入的字符串,matches应该是一个字典。你知道吗

在代码中:

ransom: 'hello'
matches: {'h': 1, 'e': 1, 'l': 2, 'o': 1}

所以你的条件是:

if 'hello' in {'h': 1, 'e': 1, 'l': 2, 'o': 1}:
    # this line will not be executed

应该是这样的:

if 'h' in {'h': 1, 'e': 1, 'l': 2, 'o': 1}:
    # this line will be executed

比较这一点的好方法:

# 1. Processing ransom 
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
# 2. Processing magazine
{'h': 2, 'e': 3, 'l': 2, 'o': 1}
# 3. Comparing each character and counts of both one by one in a for-loop

ransom is split into a dictionary {key, vaue}

注:这种假设可能是错误的。字典比较将忽略字符串的顺序,而比较字符将不按顺序逐个计数。你知道吗

# Those examples could give unexpected answers
compare('hello there', 'olleh')
compare('hello there', 'olleeeh')

相关问题 更多 >

    热门问题