1

This is a follow up to my question posted here

import random

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

l_new = random.choices(l, k=30)
print(l_new)

random.choice generates a new list using values from l. I would like to create the same output each time by fixing the seed of random.choice.

Suggestions will be really helpful.

Output obtained: Run1:

[33.3, 33.3, 33.3, 33.3, 55.5, 11.1, 11.1, 55.5, 22.2, 11.1, 33.3, 11.1, 55.5, 22.2, 33.3, 22.2, 22.2, 33.3, 55.5, 11.1, 11.1, 55.5, 11.1, 33.3, 11.1, 33.3, 33.3, 22.2, 33.3, 11.1]

Run2:

[22.2, 11.1, 33.3, 55.5, 33.3, 22.2, 33.3, 11.1, 22.2, 11.1, 11.1, 33.3, 33.3, 22.2, 33.3, 22.2, 11.1, 11.1, 55.5, 55.5, 33.3, 11.1, 55.5, 22.2, 33.3, 33.3, 55.5, 22.2, 22.2, 33.3]

Expected:

Run1:

[22.2, 11.1, 33.3, 55.5, 33.3, 22.2, 33.3, 11.1, 22.2, 11.1, 11.1, 33.3, 33.3, 22.2, 33.3, 22.2, 11.1, 11.1, 55.5, 55.5, 33.3, 11.1, 55.5, 22.2, 33.3, 33.3, 55.5, 22.2, 22.2, 33.3]

Run2:

[22.2, 11.1, 33.3, 55.5, 33.3, 22.2, 33.3, 11.1, 22.2, 11.1, 11.1, 33.3, 33.3, 22.2, 33.3, 22.2, 11.1, 11.1, 55.5, 55.5, 33.3, 11.1, 55.5, 22.2, 33.3, 33.3, 55.5, 22.2, 22.2, 33.3]
Natasha
  • 1,111
  • 5
  • 28
  • 66
  • `random.seed(n)` should have the intended effect I think. If you add it before your code – MoonMist Oct 09 '20 at 09:09
  • 1
    Can you clarify what your problem is? To set the random seed, there is literally a function called ``random.seed``. Did you use it? – MisterMiyagi Oct 09 '20 at 09:11

1 Answers1

2

You can use random.seed()

import random

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]
random.seed(1)

l_new = random.choices(l, k=30)
print(l_new)

OUTPUT Run 1:

[55.5, 55.5, 11.1, 11.1, 22.2, 33.3, 33.3, 33.3, 33.3, 33.3, 33.3, 22.2, 11.1, 11.1, 33.3, 55.5, 55.5, 33.3, 11.1, 33.3, 11.1, 11.1, 11.1, 33.3, 11.1, 55.5, 33.3, 33.3, 22.2, 11.1]

OUTPUT Run 2:

[55.5, 55.5, 11.1, 11.1, 22.2, 33.3, 33.3, 33.3, 33.3, 33.3, 33.3, 22.2, 11.1, 11.1, 33.3, 55.5, 55.5, 33.3, 11.1, 33.3, 11.1, 11.1, 11.1, 33.3, 11.1, 55.5, 33.3, 33.3, 22.2, 11.1]

This code will always generate the same result each run.


In case you use numpy there is numpy.random.seeed()

import numpy

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

numpy.random.seed(1)
l_new = list(numpy.random.choice(l, size=30))
print(l_new)

OUTPUT Run 1:

[33.3, 11.1, 33.3, 11.1, 55.5, 22.2, 11.1, 33.3, 55.5, 11.1, 11.1, 22.2, 33.3, 55.5, 33.3, 33.3, 22.2, 22.2, 33.3, 33.3, 22.2, 33.3, 33.3, 33.3, 11.1, 33.3, 33.3, 33.3, 33.3, 22.2]

OUTPUT Run 2:

[33.3, 11.1, 33.3, 11.1, 55.5, 22.2, 11.1, 33.3, 55.5, 11.1, 11.1, 22.2, 33.3, 55.5, 33.3, 33.3, 22.2, 22.2, 33.3, 33.3, 22.2, 33.3, 33.3, 33.3, 11.1, 33.3, 33.3, 33.3, 33.3, 22.2]
Carlo Zanocco
  • 1,967
  • 4
  • 18
  • 31