python中两个字符串的Anagram测试

2024-05-09 01:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是:

Write a function named test_for_anagrams that receives two strings as parameters, both of which consist of alphabetic characters and returns True if the two strings are anagrams, False otherwise. Two strings are anagrams if one string can be constructed by rearranging the characters in the other string using all the characters in the original string exactly once. For example, the strings "Orchestra" and "Carthorse" are anagrams because each one can be constructed by rearranging the characters in the other one using all the characters in one of them exactly once. Note that capitalization does not matter here i.e. a lower case character can be considered the same as an upper case character.

我的代码:

def test_for_anagrams (str_1, str_2):
    str_1 = str_1.lower()
    str_2 = str_2.lower()
    print(len(str_1), len(str_2))
    count = 0
    if (len(str_1) != len(str_2)):
        return (False)
    else:
        for i in range(0, len(str_1)):
            for j in range(0, len(str_2)):
                if(str_1[i] == str_2[j]):
                    count += 1
        if (count == len(str_1)):
            return (True)
        else:
            return (False)


#Main Program
str_1 = input("Enter a string 1: ")
str_2 = input("Enter a string 2: ")
result = test_for_anagrams (str_1, str_2)
print (result)

这里的问题是当我以OrchestraCarthorse的形式输入字符串时,结果是False。字符串The eyesThey see也是一样。任何帮助都将不胜感激。在


Tags: oftheintestfalseforstringlen
3条回答

问题是您只需检查字符串中是否存在任何字符匹配,然后递增计数器。您不计算已与另一个匹配的字符。这就是为什么以下项目也会失败:

>>> test_for_anagrams('aa', 'aa')
False

即使字符串是等于(因此也是一个anagram),也要将第一个字符串的每个a与另一个字符串的每个a相匹配,因此有一个4的计数,结果是False。在

一般来说,您应该统计每个字符的出现次数,并确保每个字符在每个字符串中出现的频率相同。您可以使用^{}对象来计算字符数。然后,您只需检查每个字符串的计数是否相同,这可以通过比较counter对象(只是字典)轻松完成:

^{pr2}$
>>> test_for_anagrams('Orchestra', 'Carthorse')
True
>>> test_for_anagrams('aa', 'aa')
True
>>> test_for_anagrams('bar', 'baz')
False

我是python新手,如果我错了请原谅

我相信这可以用另一种方法来完成:对给定的字符串进行排序,然后进行比较。在

def anagram(a, b):
  # string to list
  str1 = list(a.lower())
  str2 = list(b.lower())

  #sort list
  str1.sort()
  str2.sort()

  #join list back to string
  str1 = ''.join(str1)
  str2 = ''.join(str2)

  return str1 == str2

print(anagram('Orchestra', 'Carthorse'))

为了完整性:如果只是导入Counter并完成这个练习并不符合练习的精神,那么您可以使用普通字典来计算字母。在

def test_for_anagrams(str_1, str_2):
    counter1 = {}
    for c in str_1.lower():
        counter1[c] = counter1.get(c, 0) + 1
    counter2 = {}
    for c in str_2.lower():
        counter2[c] = counter2.get(c, 0) + 1

    # print statements so you can see what's going on,
    # comment out/remove at will
    print(counter1)
    print(counter2)

    return counter1 == counter2

演示:

^{pr2}$

输出:

{' ': 1, 'e': 3, 'h': 1, 's': 1, 't': 1, 'y': 1}
{' ': 1, 'e': 3, 'h': 1, 's': 1, 't': 1, 'y': 1}
True
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
True
{'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
{'a': 1, 'c': 1, 'e': 1, 'h': 1, 'o': 1, 's': 1, 'r': 2, 't': 1}
False

相关问题 更多 >