0

I want to generate a unique random integer for the variable SEED. This code is part of a bigger script that is going to run multiple times and output each time, so feeding SEED with a non-duplicate random integer is important. Also, I tried random.sample and such that return lists/sequence not an integer, but this is not the case here because of the following line using torch.

SEED = random.randint(1, 1000)
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True

3 Answers3

3

You can also use time.time():

import time
SEED = int(time.time())

This is technically unique since it'll be a different timestamp every time you run the code.

enzo
  • 9,861
  • 3
  • 15
  • 38
1

As an ultimate solution cast UUID to long integer from here:

import uuid
uuid.uuid4().int & (1<<64)-1
9518405196747027403L
Digoya
  • 121
  • 3
1

Perhaps this is a little too brute-force, but randomly popping integers out of a list of integers seems to work:

min_seed = 1
max_seed = 1000
seed_list = [*range(min_seed, max_seed+1)]

n_repetitions = 300  # or whatever, as long as n_repetitions < len(seed_list)
for repetition in range(0, n_repetitions):
    seed = seed_list.pop(random.randint(min_seed,len(seed_list)))

Since the integers get popped out of the list as they're used as seeds, there won't be repeats.

DomasAquinas
  • 331
  • 1
  • 7
  • Lengthy but functional but that's all that matters! Thanks! – Mahan Agha Zahedi Jun 25 '21 at 18:56
  • Why the list comprehension instead of just `list(range(...))`? – Mark Ransom Jun 25 '21 at 21:47
  • No real reason, just cranking out code. :^) I prefer the comprehension just because it conveys a bit more intention, at least to me - it reads as "I'm building a list" rather than "I want this other thing to be a list." – DomasAquinas Jun 25 '21 at 23:44
  • For what it's worth, `timeit` is telling me that `list(range(...))` is considerably faster. For 10,000 repetitions of each, the comprehension takes 0.198 sec, and `list(range(...))` 0.0855 sec. So there, a counterargument against my original way! – DomasAquinas Jun 25 '21 at 23:50
  • Update - `timeit` reveals a yet speedier way! `[range(...)]` clocks in at 0.00366 sec for 10,000 repetitions! I like that one... I'll edit it into the answer. Thanks for inspiring the hunt, @MarkRansom! – DomasAquinas Jun 26 '21 at 02:21
  • 1
    `[range(a, b)]` creates a list with length 1, but `list(range(a, b))` creates a list with length b - 1 - a. – enzo Jun 26 '21 at 02:27
  • @enzo that means the `pop` won't work on a list built that way. Good catch. – Mark Ransom Jun 26 '21 at 02:34
  • @enzo - thanks! Forgot the unpacking. It's slower than the wrong version (rats), but still the fastest I've tried (0.0775 sec). Ought to be `[*range(...)]`. Ugh, typos... ;^) – DomasAquinas Jun 26 '21 at 02:46