I want to set my random seed "creatively". That is something like np.random.seed(42) and people who read "The Hitchhiker's Guide to the Galaxy" will get the joke.
However I want to be able to start the random seed with a string, e.g. a citation.
That is something like np.random.seed(str_to_int("I like cake")), for this I need a function, that attributes integers to strings.
I'm willing to allow only letters (if necessarily lowercase letters) in my strings, if this makes the task easier. The function doesn't necessarily be random, but something else than the constant 0 function would be nice.
As it turns out, in Python 3 at least, the seed function can be seeded from a string.
In Python 2, you can take a CRC of a string, then use this as a seed.
You can use the hash() function to convert a string to an integer:
print(hash("tata"))
Output:
2314062222093390636
This is an integer that can be used to seed with an int.
As The UNIX Man pointed out, random.seed(..) can take a str directly.
From comments by @The Unix Man: the python hash uses randomization, different runs of the same program lead to different hashes: more on it to be read at
https://docs.python.org/3.3/using/cmdline.html
and param -R (wich is kept for compatibility - python 3.3+ has randomization enabled by default).
Bottom line:
dont use hash() for different runs of the same program, its salted - and will lead to different hashes between runs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With