将整数转换为随机但可确定的可重复选择

时间:2016-12-21 05:26:19

标签: python random hashlib

如何将无符号整数(表示用户ID)转换为随机查找但实际上是确定性可重复的选择?必须以相同的概率选择选择(不管输入整数的分布如何)。例如,如果我有3个选项,即[0, 1, 2],则用户ID 123可以总是随机分配选项2,而用户ID 234可以始终被分配选项1.

需要跨语言和跨平台的算法再现性。除非有更好的方法,否则我倾向于使用哈希函数和模数。这就是我所拥有的:

>>> num_choices = 3
>>> id_num = 123
>>> int(hashlib.sha256(str(id_num).encode()).hexdigest(), 16) % num_choices
2

我正在使用最新稳定的Python 3.请注意,这个问题与convert a string to random but deterministically repeatable uniform probability的相关问题相似但不完全相同。

4 个答案:

答案 0 :(得分:7)

使用hash和modulo

import hashlib

def id_to_choice(id_num, num_choices):
    id_bytes = id_num.to_bytes((id_num.bit_length() + 7) // 8, 'big')
    id_hash = hashlib.sha512(id_bytes)
    id_hash_int = int.from_bytes(id_hash.digest(), 'big')  # Uses explicit byteorder for system-agnostic reproducibility
    choice = id_hash_int % num_choices  # Use with small num_choices only
    return choice

>>> id_to_choice(123, 3)
0
>>> id_to_choice(456, 3)
1

注意:

  • 内置 hash 不能使用方法,因为它可以保留输入 分发,例如与hash(123)。或者,它可以返回重新启动Python时不同的值,例如与hash('123')

  • 为了将int转换为字节,bytes(id_num)可以正常工作,但由于返回空字节数组而效率极低,因此不能使用它。使用int.to_bytes会更好。使用str(id_num).encode()有效但浪费了几个字节。

  • 不可否认,使用modulo并不能提供完全一致的概率[1] [2],但这不应该对此应用程序产生太大偏差,因为id_hash_int预计会非常大假设num_choices很小。

使用随机

random模块可以与id_num一起用作种子,同时解决围绕thread safety和连续性的问题。以这种方式使用randrange与对种子进行哈希处理并采用模数进行比较和简单。

通过这种方法,跨语言的可重复性不仅是一个问题,而且Python的多个未来版本的可重复性也可能是一个问题。因此不建议这样做。

import random

def id_to_choice(id_num, num_choices):
    localrandom = random.Random(id_num)
    choice = localrandom.randrange(num_choices)
    return choice

>>> id_to_choice(123, 3)
0
>>> id_to_choice(456, 3)
2

答案 1 :(得分:0)

另一种方法是加密用户ID。如果保持加密密钥相同,则每个输入编号将加密到不同的输出编号,直到您使用的密码的块大小。 DES使用覆盖ID 000000到18446744073709551615的64位块。这将为用户ID提供随机出现的替换,保证不会给两个不同的用户ID提供相同的“随机”数字,因为加密是一对一的排列块值。

答案 2 :(得分:0)

我道歉我没有Python实现,但我确实在Java中有非常清晰,可读和不言而喻的实现,应该很容易以最小的努力转换为Python。以下产生长可预测的均匀分布序列,覆盖除零以外的所有范围

XorShift http://www.arklyffe.com/main/2010/08/29/xorshift-pseudorandom-number-generator

public int nextQuickInt(int number) {
    number ^= number << 11;
    number ^= number >>> 7;
    number ^= number << 16;
    return number;
}

public short nextQuickShort(short number) {
    number ^= number << 11;
    number ^= number >>> 5;
    number ^= number << 3;
    return number;
}

public long nextQuickLong(long number) {
    number ^= number << 21;
    number ^= number >>> 35;
    number ^= number << 4;
    return number;
}

XorShift128Plus (需要在使用前将state0和state1重新种子化为非零值,http://xoroshiro.di.unimi.it/xorshift128plus.c

public class XorShift128Plus {

private long state0, state1; // One of these shouldn't be zero

public long nextLong() {
    long state1 = this.state0;
    long state0 = this.state0 = this.state1;
    state1 ^= state1 << 23;
    return (this.state1 = state1 ^ state0 ^ (state1 >> 18) ^ (state0 >> 5)) + state0;
}

public void reseed(...) {
    this.state0 = ...;
    this.state1 = ...;
}

}

XorOshiro128Plus http://xoroshiro.di.unimi.it/

public class XorOshiro128Plus {

private long state0, state1; // One of these shouldn't be zero

public long nextLong() {
    long state0 = this.state0;
    long state1 = this.state1;
    long result = state0 + state1;
    state1 ^= state0;
    this.state0 = Long.rotateLeft(state0, 55) ^ state1 ^ (state1 << 14);
    this.state1 = Long.rotateLeft(state1, 36);
    return result;
}

public void reseed() {

}

}

SplitMix64 http://xoroshiro.di.unimi.it/splitmix64.c

public class SplitMix64 {

private long state;

public long nextLong() {
    long result = (state += 0x9E3779B97F4A7C15L);
    result = (result ^ (result >> 30)) * 0xBF58476D1CE4E5B9L;
    result = (result ^ (result >> 27)) * 0x94D049BB133111EBL;
    return result ^ (result >> 31);
}

public void reseed() {
    this.state = ...;
}
}

XorShift1024Mult http://xoroshiro.di.unimi.it/xorshift1024star.c)或 Pcg64_32 http://www.pcg-random.org/http://www.pcg-random.org/download.html

答案 3 :(得分:-1)

最简单的方法是通过多个选项来模user_id

choice = user_id % number_of_options

它非常简单快捷。但是,如果您了解user_id,则可以猜测算法。

此外,伪随机序列可以从random种子用户常数(例如user_id)获得:

>>> import random
>>> def generate_random_value(user_id):
...     random.seed(user_id)
...     return random.randint(1, 10000)
...
>>> [generate_random_value(x) for x in range(20)]
[6312, 2202, 927, 3899, 3868, 4186, 9402, 5306, 3715, 7586, 9362, 7412, 7776, 4244, 1751, 3424, 5924, 8553, 2970, 709]
>>> [generate_random_value(x) for x in range(20)]
[6312, 2202, 927, 3899, 3868, 4186, 9402, 5306, 3715, 7586, 9362, 7412, 7776, 4244, 1751, 3424, 5924, 8553, 2970, 709]
>>>