Checking strings against each other (Anagrams)

后端 未结 23 1876
忘了有多久
忘了有多久 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 10:55

    def anagram(a,b):
    x=[]
    y=[]
    for i in a:
        if i!=' ': # This will ignore the spaces in the sentence
            x+=[i] # Adds only letters into a list and ignore the spaces
    for i in b:
        if i!=' ':
            y+=[i]
    if len(x)==len(y): # if length of two lists are not same, They are not anagrams anyway. So it directly returns False.
        for i in range(len(x)):
            for j in range(len(y)):
                if x[i].lower()==y[j].lower(): 
                    y.pop(j) # If the letter matched between first and second list, that letter is poped from that list.
                    break
        return len(y)==0 # If the given sentences are anagrams, all the letters are poped out from the second list and function returns True(as the lenght of the second list is 0. If not, function will return False.
    return False
    

    anagram(a,b)

提交回复
热议问题