Mastering Python's random Module ๐ฒ
Mastering Python's random Module ๐ฒ
The random module provides versatile tools for generating random numbers, shuffling sequences, sampling, and more. It's widely used for testing, simulations, and probabilistic operations.
1. Generating Random Numbers: uniform, randint, random
import random
print(random.random()) # float between 0.0 and 1.0
print(random.uniform(10, 20)) # float between 10 and 20
print(random.randint(1, 6)) # integer between 1 and 6
2. Fixing the Seed for Reproducibility
import random
random.seed(123)
print([random.randint(1, 100) for _ in range(5)]) # same results every time
3. Shuffling and Sampling Lists
import random
arr = list(range(1, 11))
random.shuffle(arr) # shuffle list randomly
print(arr)
sample = random.sample(arr, 3) # select 3 unique elements
print(sample)
4. Weighted and Simple Random Choices
import random
choices = ['Rock', 'Paper', 'Scissors']
print(random.choice(choices)) # single random choice
weighted = random.choices(choices, weights=[1, 2, 1], k=5)
print(weighted) # 'Paper' more likely chosen due to higher weight
Summary
- Use
random(),uniform(),randint()for varied random numbers. - Ensure reproducibility with
seed(). shuffle()andsample()help randomize or extract from lists.choice()andchoices(weights)offer simple and weighted selection.
Comments
Post a Comment