gpt4 book ai didi

python - C 到 Python 字谜

转载 作者:太空宇宙 更新时间:2023-11-04 05:07:45 27 4
gpt4 key购买 nike

我正在尝试学习 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 中完成的?

最佳答案

Specifically, how is the line str1_count[str2[i] - 'a']++ done in Python?

事实并非如此。 Python 有 dict 来处理这样的事情。

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

虽然 collections.defaultdict 通常用于处理新 key 的情况。

str1_count = collections.defaultdict(int)

关于python - C 到 Python 字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11286555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com