Checking strings against each other (Anagrams)

后端 未结 23 1977
忘了有多久
忘了有多久 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:13

    To check if two strings are anagrams of each other using dictionaries: Note : Even Number, special characters can be used as an input

    def anagram(s):
        string_list = []
        for ch in s.lower():
            string_list.append(ch)
    
        string_dict = {}
        for ch in string_list:
            if ch not in string_dict:
                string_dict[ch] = 1
            else:
                string_dict[ch] = string_dict[ch] + 1
    
        return string_dict
    
    
    
    s1 = "master"
    s2 = "stream"
    
    a = anagram(s1)
    b = anagram(s2)
    
    if a == b:
        print "Anagram"
    else:
        print "Not Anagram"
    

提交回复
热议问题