Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Last active September 1, 2020 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathonReinhart/fc68eb3e754b5466b9d526a99d8bf9f2 to your computer and use it in GitHub Desktop.
Save JonathonReinhart/fc68eb3e754b5466b9d526a99d8bf9f2 to your computer and use it in GitHub Desktop.
Python 2.7, 3 compatible random seeding
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("")
@JonathonReinhart
Copy link
Author

Python version: 2.7.16
[1, 4, 9, 0, 0, 7, 6, 4, 1, 8]

Python version: 3.7.3
[1, 4, 9, 0, 0, 7, 6, 4, 1, 8]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment