Generate nandom number without importing anything [duplicate]

Solution 1:

Random and pseudorandom generators will ultimately rely on some kind of module, if only to get a seed needed to produce pseudorandom numbers. One common example of a seed is time.time found in the time module, though it's not necessarily a good one. The only way without a module is to choose a fixed seed, but then only a fixed sequence of numbers is possible.

Besides the seed, there is the algorithm. One popular choice is the linear congruential generator (LCG). This algorithm is appropriate for learning purposes; however, LCGs are far from perfect and should not be used in security applications or serious simulations. See this answer: How to sync a PRNG between C#/Unity and Python?

There are two more things involved in the solution: generating a random integer, and choosing a random item from a list.

  • Generating a random integer in [0, n); that is, building RNDINTEXC(n). For that, see Melissa O'Neill's page.
  • Choosing a random item from a list, doing list[RNDINTEXC(len(list))].

Solution 2:

If you don't want to use random module, you can use time module to generate pseudorandom integers.

import time

def get_random_number(upper_limit):
    _timestamp = time.time()
    _timestamp = int(_timestamp*1000000)
    return _timestamp % upper_limit

def get_item_from_list(_list):
    choice = get_random_number(len(_list))
    assert choice < len(_list), "Index should be less than length of list"
    return _list[choice]

print(get_item_from_list([10, 20, 13, 24, "ABS", "DEF"]))

You can use this to generate random items from a list.