Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

Python Map Integer to Another "Random" Integer without Random

Suppose I am given an input integer in the range 0 to 10000. I would like a one to one function that maps this integer to another seemingly random integer in the same range. Essentially, I want something like this:

import random
random.seed(0)
out = list(range(10001))
random.shuffle(out)
mapper = {ii:oo for ii, oo in enumerate(out)}

>>> mapper[0]
6853
>>> mapper[1]
3631
>>> mapper[3]
421

The only problem is that this Python code gets executed thousands of times per frame, so I don't want to shuffle the list each time because that slows it down too much. But I don't have any global storage where the list can be computed once and accessed each frame (I'm using a Python effector in Cinema 4D, so the whole python script gets executed for every single clone). So I need another faster solution that can get what I'm looking for.

I assume there is some much more efficient mathematical function I could use instead that would get me a very similar result, essentially just taking an integer and mapping it to another pseudo random integer in a given range, while producing the same result each time the script is run. Any ideas?

question from:https://stackoverflow.com/questions/66055968/python-map-integer-to-another-random-integer-without-random

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

random.randint is what is right for you, you can create a generator from it if you need:

import random
def random_integer(lower_bound, higher_bound):
  while True:
    yield random.randint(lower_bound, higher_bound)

int_gen = iter(random_integer(0, 10001))

# And then use it:

>>> next(int_gen)
6853
>>> next(int_gen)
9883
>>> next(int_gen)
7782
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...