Skip to content

Random selection and shuffling [ref]

Problem

  • Draw an integer from 0 through 9 using randrange.
  • Draw an integer from 3 through 7.
  • Draw an even integer from 0 through 8.
  • Choose one element from [10, 20, 30].
  • Shuffle [1, 2, 3, 4] in place and verify its members are unchanged.
  • Draw a Fisher-Yates swap index from i = 1 through 3 for a length-4 list.

Python solution

import random

x = random.randrange(10)
0 <= x < 10  # True

x = random.randrange(3, 8)
3 <= x <= 7  # True

x = random.randrange(0, 10, 2)
x in {0, 2, 4, 6, 8}  # True

random.choice([10, 20, 30]) in {10, 20, 30}  # True

items = [1, 2, 3, 4]
random.shuffle(items)
sorted(items)  # [1, 2, 3, 4]

i, n = 1, 4
j = random.randrange(i, n)
1 <= j < 4  # True