Last active
September 1, 2020 00:46
-
-
Save JonathonReinhart/fc68eb3e754b5466b9d526a99d8bf9f2 to your computer and use it in GitHub Desktop.
Python 2.7, 3 compatible random seeding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import random | |
import sys | |
class CompatibleRandom(random.Random): | |
# Inspired by https://stackoverflow.com/a/55800424/119527 | |
def seed(self, a): | |
if sys.version_info >= (3, 2): | |
super(CompatibleRandom, self).seed(a, version=1) | |
else: | |
# Python 2.7 or <3.2 | |
super(CompatibleRandom, self).seed(a) | |
def randrange(self, lo, hi): | |
if sys.version_info >= (3, 2): | |
return int(self.random() * hi) + lo | |
else: | |
return super(CompatibleRandom, self).randrange(lo, hi) | |
print("Python version:", '.'.join(str(x) for x in sys.version_info[0:3])) | |
r = CompatibleRandom('this is my seed') | |
print([r.randint(0, 10) for _ in range(10)]) | |
print("") |
Author
JonathonReinhart
commented
Sep 1, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment