Checking strings against each other (Anagrams)

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

    Here's one typical assignment solution:

    def anagram(s1, s2):
    """ (str, str) -> bool
    
    Return True if s1 and s2 are anagrams
    
    >>> anagram(s1, s2)
    True
    """
        s1 = s1.replace(" ", "")
        s2 = s2.replace(" ", "")
    
        s1_new = list(s1)
        s2_new = list(s2)
    
        if len(s1_new) == len(s2_new):
            dupe_found = True
            while dupe_found:
                dupe_found = False
                for i in s1_new:
                    for j in s2_new:
                        if i == j:
                            s1_new.remove(i)
                            s2_new.remove(j)
                            dupe_found = True
                            break
                    break
        return s1_new == s2_new
    

提交回复
热议问题