In my program I'm trying to include a random place generator, and instead of saving each place that's generated (for people to explore) I'd rather just reuse the seed that I used to generate the place to begin with, though this could conflict with other parts of my code. Is there a way that I can seed random within the scope of the def? Or at the very least in the scope of the file? If it's not possible with the stdlib random is it possible with a separate one? I'm using python 3.8 by the way.
Asked
Active
Viewed 48 times
-2
-
@kol I really don't know honestly, it seems like they're downvoting more because I'm not experienced enough to know about the solution (despite that being the reason I'm asking here, as I can assure you I did search for it). – TheArchStarch Jul 21 '20 at 13:29
-
could you show some code? maybe the downvotes were because nobody can reproduce your problems without any code... – Dorian Jul 21 '20 at 13:40
-
@kol, StackOverflow askers are expected to show effort to figure out the answer themselves. A simple google search of "python random number seed" pointed to [this page](https://docs.python.org/3/library/random.html), which says _"The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state."_ – Pranav Hosangadi Jul 21 '20 at 17:41
-
@kol https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users – Pranav Hosangadi Jul 21 '20 at 22:08
-
@kol, then I suggest you take the [tour] again. _"Don't ask about...Questions you haven't tried to find an answer for (show your work!)"_ This _is_ a place where programmers help other programmers solve programming problems. If you haven't tried solving it yourself before you ask on SO, you're asking people to do it for you, not for them to help you do it. – Pranav Hosangadi Jul 22 '20 at 14:33
1 Answers
3
You can use random.seed
or create a new Random
object based on a specific seed. Eg:
>>> from random import Random
>>> randomizer = Random(123)
>>> randomizer.randint(1, 100)
7
>>> randomizer.randint(1, 100)
35
>>> randomizer.randint(1, 100)
12
I can do this again with the same seed and it'll create the same set of random numbers.
>>> randomizer = Random(123)
>>> randomizer.randint(1, 100)
7
>>> randomizer.randint(1, 100)
35
>>> randomizer.randint(1, 100)
12
>>> randomizer = Random(123)
>>> randomizer.randint(1, 100)
7
>>> randomizer.randint(1, 100)
35
>>> randomizer.randint(1, 100)
12
>>> randomizer = Random(123)
>>> randomizer.randint(1, 100)
7
>>> randomizer.randint(1, 100)
35
>>> randomizer.randint(1, 100)
12
See the Python random module for more details.

Ken Kinder
- 12,654
- 6
- 50
- 70