Trying to come up with python anagram function

后端 未结 7 2011
梦谈多话
梦谈多话 2021-01-23 14:02

What I\'m trying to do is if I have a list like:

[\"lime\", \"mile\", \"liem\", \"tag\", \"gat\", \"goat\", \"math\"]

I want to write a functio

7条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 14:17

    Checks two given strings if they're anagrams or not. Those strings may include spaces, numbers or special characters

    #First of all define a function that counts the number of alphabets in a string. It'll be used as a final condition to check for anagrams
    def count_alpha(text):
        text = text.lower()
        count = 0
        i = 97    #ASCII code range from 'a' to 'z' is 97 to 122
        while i < 123:
            if chr(i) in text:
                count += text.count(chr(i))
            i += 1
        return count
    text1 = input('Enter your First Word: ')
    text2 = input('Enter your Second Word: ')
    #replace all the spaces with empty strings and make the string lower case 
    text1 = text1.replace(' ','').lower()
    text2 = text2.replace(' ','').lower()
    i = 97
    while i < 123:
        #check if an alphabet count in both strings is the same.
        if text1.count(chr(i)) == text2.count(chr(i)):
            #replace all the alphabets with spaces
            text1 = text1.replace(chr(i),' ')
            text2 = text2.replace(chr(i),' ')
        i += 1  
    #since all the alphabets have been replaced by spaces. There's no alphabet left(if they had the same number of particular alphabets)
    if count_alpha(text1) == 0 and count_alpha(text2) == 0:
        print('They are anagrams')
    else: print('They are not anagrams')
    

    So here's your code. Enjoy!

提交回复
热议问题