python - 使用python在c++中实现逻辑,如何?

标签 python c++

我想使用 python 在 C++ 中实现以下逻辑。

struct hash_string ///
{
    hash_string() {}

    uint32_t operator ()(const std::string &text) const
    {
        //std::cout << text << std::endl;
        static const uint32_t primes[16] =
        {
            0x01EE5DB9, 0x491408C3, 0x0465FB69, 0x421F0141,
            0x2E7D036B, 0x2D41C7B9, 0x58C0EF0D, 0x7B15A53B,
            0x7C9D3761, 0x5ABB9B0B, 0x24109367, 0x5A5B741F,
            0x6B9F12E9, 0x71BA7809, 0x081F69CD, 0x4D9B740B,
        };

        //std::cout << text.size() << std::endl;
        uint32_t sum = 0;
        for (size_t i = 0; i != text.size(); i ++) {
            sum += primes[i & 15] * (unsigned char)text[i];
            //std::cout << text[i] <<std::endl;
            // std::cout << (unsigned char)text[i] << std::endl;
        }
        return sum;
    }
};

python版本是这样的,还没有完成,因为我还没有找到将文本转换为unsigned char的方法。所以,请帮忙!

# -*- coding: utf-8 -*-

text = u'连衣裙女韩范'

primes = [0x01EE5DB9, 0x491408C3, 0x0465FB69, 0x421F0141,
                0x2E7D036B, 0x2D41C7B9, 0x58C0EF0D, 0x7B15A53B,
                0x7C9D3761, 0x5ABB9B0B, 0x24109367, 0x5A5B741F,
                0x6B9F12E9, 0x71BA7809, 0x081F69CD, 0x4D9B740B]

//*text[i] does not work (of course), but how to mimic the logic above
rand = [primes[i & 15]***text[i]** for i in range(len(text))]

print rand

sum_agg = sum(rand)

print sum_agg

以text=u'连衣裙女韩范'为例,c++版本的text.size()返回18,sum为2422173716,而在python中,我不知道如何使它成为18。

至少作为开始,文本大小的相等性是必不可少的。

最佳答案

因为您使用的是 unicode,为了精确复制,您需要将 text 转换为一系列字节(C++ 中的字符)。

bytes_ = text.encode("utf8") 
# when iterated over this will yield ints (in python 3)
# or single character strings in python 2

你应该使用更多的 pythonic 习语来迭代一对序列

pairs = zip(bytes_, primes)

如果 bytes_ 比素数长怎么办?使用 itertools.cycle

from itertools import cycle
pairs = zip(bytes_, cycle(primes))

一起:

from itertools import cycle

text = u'连衣裙女韩范'

primes = [0x01EE5DB9, 0x491408C3, 0x0465FB69, 0x421F0141,
                0x2E7D036B, 0x2D41C7B9, 0x58C0EF0D, 0x7B15A53B,
                0x7C9D3761, 0x5ABB9B0B, 0x24109367, 0x5A5B741F,
                0x6B9F12E9, 0x71BA7809, 0x081F69CD, 0x4D9B740B]

# if python 3
rand = [byte * prime for byte, prime in zip(text.encode("utf8"), cycle(primes))]
# else if python 2 (use ord to convert single character string to int)
rand = [ord(byte) * prime for byte, prime in zip(text.encode("utf8"), cycle(primes))]
hash_ = sum(rand)

关于python - 使用python在c++中实现逻辑,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33540418/

相关文章:

python - 对两个 NumPy 数组中的正元素和负元素求和

python - 在文本中使用类的随机实例

c++ - 使用 TypedEq() 匹配类型 std::vector<std::vector>

c++ - 通过 C++ 从 PKCS7 (CMS) 获取详细信息

python - 如何将 pandas 数据框合并到现有的 reportlab 表中?

python - 如何取消 BERT 代币的代币化?

python - 如何使用 Iron python 加载 DLL?

c++ - 在 C++ String 中寻找一种好方法来查找关键字,而相邻字符不是 a-z

c++ - 我应该把空基类放在哪里?

c++ - 限制辅助监视器中的窗口最大大小