Nik Ackermann
Nik Ackermann

Reputation: 639

Comparing a string's characters to a dictionary python

Currently working on an assignment and a little stuck. Looking for some assistance to approach this. I'm trying to try a function that takes two values a magazine and a ransom which are input by a user. If the characters in the ransom can be found in the magazine I want to return that it is true otherwise if the ransom string cannot be found in the magazine string return false. ransom is split into a dictionary {key, vaue} so for example the user enters:

Enter magazine: hello there

Enter ransom: hello

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

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

This should return true but it returns false because it does not count the second 'l' in 'hello'. What am I doing wrong?

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

Upvotes: 1

Views: 345

Answers (1)

Kir Chou
Kir Chou

Reputation: 3080

if ransom in matches:

First of all, this comparison seems wrong, ransom is supposed to be a string which is inputted by an user, matches is supposed to be a dictionary.

In your code:

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

So your if-condition will be like:

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

It should be like:

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

A good way to compare this:

# 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}

Note: the way of this assumption could be wrong. Dictionary comparison will ignore order of string, and comparing characters counts one by one without order.

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

Upvotes: 1

Related Questions