在Android实现上运行时,为什么Python哈希函数没有给出相同的值? [英] Why doesn't Python hash function give the same values when run on Android implementation?

查看:90
本文介绍了在Android实现上运行时,为什么Python哈希函数没有给出相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信hash()函数在所有python解释器中的工作原理都是相同的.但是,当我使用适用于Android的python 在移动设备上运行它时,情况有所不同.对于散列字符串和数字,我得到相同的散列值,但是当我对内置数据类型进行散列时,散列值会有所不同.

I believed that hash() function works the same in all python interpreters. But it differs when I run it on my mobile using python for android. I get same hash value for hashing strings and numbers but when I hash built-in data types the hash value differs.

PC Python解释器(Python 2.7.3)

>>> hash(int)
31585118
>>> hash("hello sl4a")
1532079858
>>> hash(101)
101

移动Python解释器(Python 2.6.2)

>>> hash(int)
-2146549248
>>> hash("hello sl4a")
1532079858
>>> hash(101)
101

任何人都可以告诉我这是一个错误还是我误解了一些东西.

Can any one tell me is it a bug or I misunderstood something.

推荐答案

对于旧python(至少是我的Python 2.7),看来

for old python (at least, my Python 2.7), it seems that

hash(<some type>) = id(<type>) / 16

,对于CPython,id()是内存中的地址- http://docs.python.org/2/library/functions.html#id

and for CPython id() is the address in memory - http://docs.python.org/2/library/functions.html#id

>>> id(int) / hash(int)                                                     
16                                                                              
>>> id(int) % hash(int)                                                 
0                                                                               

所以我的猜测是Android端口对内存地址有一些奇怪的约定吗?

so my guess is that the Android port has some strange convention for memory addresses?

总而言之,由于函数位于不同的地址,因此类型(和其他内置函数)的哈希值在安装过程中会有所不同.

anyway, given the above, hashes for types (and other built-ins i guess) will differ across installs because functions are at different addresses.

相反,值的哈希值(我认为您指的是非内部对象")(在添加随机对象之前)是根据值的哈希值计算出来的,因此很可能是可重复的.

in contrast, hashes for values (what i think you mean by "non-internal objects") (before the random stuff was added) are calculated from their values and so likely repeatable.

PS,但至少还有一个CPython折皱:

PS but there's at least one more CPython wrinkle:

>>> for i in range(-1000,1000):
...     if hash(i) != i: print(i)
...
-1

在某处有一个答案来解释那个...

there's an answer here somewhere explaining that one...

这篇关于在Android实现上运行时,为什么Python哈希函数没有给出相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆