Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the random.seed function in python work for words? What number is it converted to?

I realized that if I choose

random.seed("hello world!")

it actually works, i.e. it does not give me any error and it works like a normal seed; So for example choosing

random.seed("hello world!")
random.choices([1,2,3,4,5,6,7], k = 10)

keeps giving me the same output; But it would be actually interesting, to what number a string is converted to??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code in random.py looks like this:


# more code here

# Note there is a entirely different algorithm for "version 1"

elif version == 2 and isinstance(a, (str, bytes, bytearray)):
    if isinstance(a, str):
        a = a.encode()
    seed = int.from_bytes(a + _sha512(a).digest())

# some more irrelevant conditions

super().seed(seed)

So basically the number will be the "input string + sha512 of the input string" interpreted as one very big integer. Python integers have no max value so this always works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading