0

我正在努力学习 Python。考虑一下 C 中的这个简单的字谜检查器:

bool are_anagrams(const char* str1, const char* str2)
{
  int str1_count[NUM_CHARS] = {0};
  int str2_count[NUM_CHARS] = {0};

  for(int i = 0; i < strlen(str1); i++)
  {
    str1_count[str1[i] - 'a']++;
  } 
  for(int i = 0; i < strlen(str2); i++)
  {
    str2_count[str2[i] - 'a']++;
  }

  for(int i = 0; i < NUM_CHARS; i++)
  {
    if(str1_count[i] != str2_count[i])
      { return false; }
  }

  return true;
}

具体来说,这行是如何str1_count[str2[i] - 'a']++在 Python 中完成的?

4

3 回答 3

5

具体来说,这行是如何str1_count[str2[i] - 'a']++在 Python 中完成的?

它不是。Pythondict可以处理这样的事情。

str1_count = {}
 ...
str1_count[char2] += 1

虽然collections.defaultdict通常用于处理它是新密钥的情况。

str1_count = collections.defaultdict(int)
于 2012-07-02T00:02:14.670 回答
3

考虑一下 Python 中的这个简单的字谜检查器

from collections import Counter
def are_anagrams(str1, str2):
    return Counter(str1) == Counter(str2)

您如何将其转换为C?(这使用与您的 C 版本相同的算法)

要回答您的问题,您必须使用ord()

str1_count[ord(str2[i]) - ord('a')]

看起来像 str1/str2 命名的错误

于 2012-07-02T00:18:35.933 回答
3

甚至更好,

def are_anagrams(s1, s2):
    return sorted(s1)==sorted(s2)

.

编辑:回应@gnibbler:

这是一个快速的运行时比较,其中 x 轴给出字符串长度;蓝色是你的功能,绿色是我的。在我看来,两者都非常线性。

图比较函数运行时间

于 2012-07-02T01:18:26.380 回答