Skip to content

Instantly share code, notes, and snippets.

@IgorZyktin
Created September 26, 2021 11:21
Show Gist options
  • Save IgorZyktin/554c79204b66f76a92b552f94b04cc29 to your computer and use it in GitHub Desktop.
Save IgorZyktin/554c79204b66f76a92b552f94b04cc29 to your computer and use it in GitHub Desktop.
import random
my_set = set(range(100))
my_list = list(range(100))
N = 10
ATTEMPTS = 5
print('\nVariant 1: using generator')
for _ in range(ATTEMPTS):
gen = iter(my_set)
sample = [next(gen) for _ in range(N)]
print(sample)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print('\nVariant 2: using mutation')
for _ in range(ATTEMPTS):
sample = []
while len(sample) < N:
element = my_set.pop()
sample.append(element)
my_set.add(element)
print(sample)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
# [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
# [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
print('\nVariant 3: using list')
for _ in range(ATTEMPTS):
sample = random.sample(my_list, N)
print(sample)
# [40, 43, 92, 89, 41, 63, 22, 76, 64, 21]
# [36, 2, 86, 45, 46, 23, 20, 69, 21, 79]
# [60, 47, 34, 50, 98, 32, 79, 92, 89, 99]
# [34, 66, 1, 97, 54, 45, 11, 57, 73, 21]
# [87, 86, 26, 54, 16, 2, 58, 96, 88, 31]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment