为什么Python2中的某些代码确定性和Python 3中的非确定性?

Bio*_*ett 22 python string bioinformatics non-deterministic python-3.x

我正在尝试编写一个脚本来计算所有可能的模糊字符串匹配匹配到一个短字符串,或'kmer',并且在Python 2.7.X中工作的相同代码给了我一个非确定性的答案与Python 3.3 .X,我无法弄清楚为什么.

我在我的代码中遍历字典,itertools.product和itertools.combinations,但我迭代完所有这些完成而没有中断或继续.另外,我将所有结果存储在一个单独的字典中,而不是我正在迭代的字典中.简而言之 - 我没有犯任何明显的错误,为什么Python2和Python3之间的行为有所不同?

示例,稍微简化的代码如下:

import itertools

def find_best_fuzzy_kmer( kmers ):
    for kmer, value in kmers.items():
        for similar_kmer in permute_string( kmer, m ):
            # Tabulate Kmer

def permute_string( query, m ):
    query_list = list(query)
    output = set() # hold output
    for i in range(m+1):
        # pre-calculate the possible combinations of new bases
        base_combinations = list(itertools.product('AGCT', repeat=i))
        # for each combination `idx` in idxs, replace str[idx]
        for positions in itertools.combinations(range(len(query_list)), i):
            for bases in base_combinations:
                # Generate Permutations and add to output
    return output
Run Code Online (Sandbox Code Playgroud)

Tim*_*ers 34

如果通过"非确定性"表示字典键出现的顺序(当您在字典上进行迭代时)从运行变为运行,并且字典键是字符串,请说明.然后我可以帮忙.但到目前为止你还没有说过这些;-)

假设这是问题,这里有一个小程序:

d = dict((L, i) for i, L in enumerate('abcd'))
print(d)
Run Code Online (Sandbox Code Playgroud)

并且在Python 3.3.2下运行4的输出:

{'d': 3, 'a': 0, 'c': 2, 'b': 1}
{'d': 3, 'b': 1, 'c': 2, 'a': 0}
{'d': 3, 'a': 0, 'b': 1, 'c': 2}
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
Run Code Online (Sandbox Code Playgroud)

从这部分python -h输出中暗示了原因:

Other environment variables:
...
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
   to seed the hashes of str, bytes and datetime objects.  It can also be
   set to an integer in the range [0,4294967295] to get hash values with a
   predictable seed.
Run Code Online (Sandbox Code Playgroud)

这是一个半生不熟的"安全修复程序",旨在帮助防止基于构造旨在激发二次时行为的字典输入的DOS攻击."random"是Python3中的默认值.

您可以通过将envar PYTHONHASHSEED设置为整数来关闭它(您的选择 - 如果您不在乎,则选择0).然后使用字符串键迭代dict将在运行时以相同的顺序生成它们.

正如@AlcariTheMad在评论中所说,你可以在Python 2下启用 Python3默认行为python -R ....

  • @thefourtheye,"控制"主要是虚幻的 - 关于dict迭代顺序仍然没有*定义*.所有这些技巧供应都是一致的交叉运行顺序,前提是dict在运行中以完全相同的方式构建(相同的键插入和删除序列). (5认同)
  • 并且,它可能不言而喻,但哈希随机化也适用于`set`对象. (2认同)