Skip to content

Latest commit

 

History

History
199 lines (160 loc) · 5.22 KB

File metadata and controls

199 lines (160 loc) · 5.22 KB

1. Random and Time Modules

Python comes with a rich set of built-in libraries. Two of the most commonly used modules for handling probabilities and system timings are random and time.


1. The random Module

The random module provides tools to generate pseudo-random numbers and make random selections from collections.

A. Generating Random Floats: random.random()

Returns a random floating-point number in the range [0.0, 1.0).

Input:

import random

# Generate a float between 0.0 and 1.0
print("Random float:", random.random())

Output:

Random float: 0.3745401188473625

B. Generating Random Integers: random.randint(a, b)

Returns a random integer $N$ such that $a \le N \le b$ (both limits are inclusive).

Input:

# Roll a 6-sided die
die_roll = random.randint(1, 6)
print("Die roll:", die_roll)

Output:

Die roll: 5

C. Making Random Selections: random.choice(seq)

Returns a random element from a non-empty sequence (like a list or tuple).

Input:

fruits = ["apple", "banana", "cherry", "date"]
picked_fruit = random.choice(fruits)
print("Randomly picked fruit:", picked_fruit)

Output:

Randomly picked fruit: banana

D. Shuffling in Place: random.shuffle(list)

Shuffles the elements of a list in place (mutates the list).

Input:

cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(cards)
print("Shuffled cards:", cards)

Output:

Shuffled cards: ['Queen', 'Jack', 'Ace', 'King']

E. Random Floating-Point between Limits: random.uniform(a, b)

Returns a random floating-point number $N$ such that $a \le N \le b$.

Input:

# Generate a float between 12.0 and 20.0
print("Random uniform float:", random.uniform(12, 20))

Output:

Random uniform float: 15.823489

F. Multiple Choices with Replacement: random.choices(seq, k)

Returns a list of size k containing elements chosen from the sequence, with replacement (meaning elements can repeat).

Input:

colors = ["red", "blue", "green"]
# Choose 5 colors (elements can be duplicated!)
picked_colors = random.choices(colors, k=5)
print("Choices output:", picked_colors)

Output:

Choices output: ['blue', 'red', 'blue', 'green', 'blue']

2. The time Module

The time module provides functions for working with time-related tasks.

A. Unix Epoch Time: time.time()

Returns the current system time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC).

Input:

import time

epoch_time = time.time()
print("Seconds since Epoch:", epoch_time)

Output:

Seconds since Epoch: 1782555600.0

B. Execution Delay: time.sleep(seconds)

Suspends execution of the current thread for the given number of seconds.

Input:

print("Starting...")
time.sleep(2)  # Pauses execution for exactly 2 seconds
print("Completed after 2 seconds delay!")

Output:

Starting...
Completed after 2 seconds delay!

C. Precision Performance Timing: time.perf_counter()

If you want to measure exactly how long a block of code takes to run (benchmarking), do NOT use time.time(). It has low resolution and can be affected by system clock adjustments.

Instead, use time.perf_counter(), which provides a high-resolution, monotonic timer (a clock that never goes backwards).

Input:

start_time = time.perf_counter()

# Let's run a loop to benchmark it
sum_val = 0
for i in range(1000000):
    sum_val += i

end_time = time.perf_counter()
execution_time = end_time - start_time

print(f"Loop completed in: {execution_time:.6f} seconds")

Output:

Loop completed in: 0.053412 seconds

3. Practical Application: Password Generator

Let's combine random selections (random.choices()), shuffling (random.shuffle()), and integer generation (random.randint()) to construct a secure password generator.

Program Logic:

  1. Prompts the user to enter their name.
  2. Selects 4 random letters from their name.
  3. Selects 2 random special characters from a list.
  4. Shuffles the combined set of characters to make it unpredictable.
  5. Capitalizes the first letter of the shuffled characters.
  6. Appends a random 5-digit security number (between 11111 and 99999) to form the final password.

Input:

import random

# 1. Input name
name = "python"
spe_chars = ['!', '@', '#', '^', '&', '*']

# 2. Gather components
sample1 = random.choices(name, k=4) + random.choices(spe_chars, k=2)

# 3. Shuffle components in-place
random.shuffle(sample1)

# 4. Join and title-case (capitalize first letter)
shuffled_str = ''.join(sample1).title()

# 5. Append random 5-digit number
password = shuffled_str + str(random.randint(11111, 99999))
print("Generated Password:", password)

Output:

Generated Password: Y!Pt*h24589