目前正在做作业,有点卡住了。寻找一些帮助来解决这个问题。我正在尝试一个函数,它接受用户输入的两个值:杂志和赎金。如果赎金中的字符可以在杂志中找到,我想返回它是真的,否则如果赎金字符串不能在杂志中找到字符串返回假。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
首先,这个比较似乎是错误的,ransem应该是一个由用户输入的字符串,matches应该是一个字典。你知道吗
在代码中:
所以你的条件是:
应该是这样的:
比较这一点的好方法:
注:这种假设可能是错误的。字典比较将忽略字符串的顺序,而比较字符将不按顺序逐个计数。你知道吗
相关问题 更多 >
编程相关推荐