1

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
1
  • ransom in matches checks if a whole word ransom is in keys belonging to the dictionary {'h': 1, 'o': 1, 'l': 2, 'e': 1}. somethin in dictionary is going to return True only if you provide some string which is a key in provided dict. Commented Feb 11, 2017 at 1:00

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.