Checking strings against each other (Anagrams)

后端 未结 23 1871
忘了有多久
忘了有多久 2020-11-30 10:55

The assignment is to write a program that accepts two groups of words from the user and then prints a \"True\" statement if the two are anagrams (or at least if all the lett

23条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 11:22

    You can use the magic Counter from collections library. From documentation:

    It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values

    So, you can initialize a Counter object with a string (a iterable) and compare with another Counter from a string

    from collections import Counter
    
    def is_anagram(str1, str2):
       return Counter(str1) == Counter(str2)
    

提交回复
热议问题