DEV Community

Discussion on: Algorithms Problem Solving: Ransom Note

Collapse
rpalo profile image
Ryan Palo

Have you heard about the collections module in the standard library? It's got a class called Counter available that is really useful in situations like this. Check out the docs

from collections import Counter

def can_build_ransom_note(message, magazine):
    needed_letters = Counter(message)
    available_letters = Counter(magazine)

    for letter, count in needed_letters.items():
        if available_letters[letter] < count:
            return False

    return True
Collapse
teekay profile image
TK Author

I didn't know about this Counter class. It is awesome! But my idea with this whole algorithm series is to try to implement the algorithm without help from built-in methods or classes. Just the default data structures.

Thanks for the note! I really liked this class.

Collapse
rpalo profile image
Ryan Palo

That makes sense. Thanks for sharing!