2017-02-11 304 views
1

当前正在进行分配并且有点卡住。寻求一些帮助来解决这个问题。我试图尝试一个函数,该函数需要用户输入的杂志和赎金两个值。如果可以在杂志中找到赎金中的字符,我想返回它,否则如果在杂志字符串中找不到赎金字符串,则返回false。赎被分成一个字典{键,vaue}因此,例如,用户输入:将字符串的字符与字典进行比较python

输入杂志:你好

输入赎:你好

{ '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 
+0

'赎在matches'检查是否全词赎是在属于字典'密钥{ 'H':1, 'O':1, 'L':2, 'E':1} '。字典中的“somethin”只有在提供字符串时才会返回“True”,这是提供的字典中的一个关键字。 – MaLiN2223

回答

1

如果赎金比赛:

首先,这种比较似乎是错误的,赎金被认为是其通过用户输入的字符串相匹配,应该是一本字典。

在您的代码:

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 

赎金被分成字典{键,vaue}

注:这个假设的方式可能是错误的。字典比较将忽略字符串的顺序,并且比较字符一个接一个地计数而没有顺序。

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