Programs
Weekly Wages
hours = input('Enter Hours separated by spaces:')
wage = int(input('Enter Hourly Wage:'))
hours = hours.split() #hours.split(",")
week_hours = [int(x) for x in hours]
total_hrs = sum(week_hours)
if total_hrs <= 40:
tot_wages = total_hrs * wage
else:
overtime = total_hrs - 40
tot_wages = 40 * wage + overtime * wage * 1.5
print('Total Wages:', tot_wages)
Removing Duplicates
L1 = [3, 5, 7, 9, 3, 6, 5, 2, 3, 7, 10]
res = []
for element in L1:
if element not in res:
res.append(element)
print(res)
even ,odd
nums = [4, 8, 3, 5, 10, 7, 2, 9, 13, 6]
odd = [x for x in nums if x % 2 != 0]
even = [x for x in nums if x % 2 == 0]
print('Odd:', odd)
print('Even:', even)
Palindrome
lst = [5, 4, 3, 3, 4, 5]
rev = lst[::-1]
if lst == rev:
print('Yes Palindrome')
else:
print('Not Plaindrome')
Rotate list
lst = [1, 2, 3, 4, 5, 6]
n = int(input('Enter Number of Rotations:'))
rotated = lst[n:] + lst[:n]
print('Rotated List:', rotated)
Shuffle a List
import random as rd
lst = [1, 2, 3, 4, 5, 6]
rd.shuffle(lst)
print('Shuffled List:', lst)
Python random Module Explained with Examples
The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method:
Basic Random Number Generation
1. random.random()
Returns a random float between 0.0 and 1.0
python
import random
# Example 1: Basic random float
print(random.random()) # e.g., 0.5488135039273248
# Example 2: Using in a calculation
probability = random.random()
if probability > 0.7:
print("High probability event")
# Example 3: Scaling the result
scaled = random.random() * 100
print(f"Scaled value: {scaled}")
2. random.uniform(a, b)
Returns a random float between a and b
python
# Example 1: Random temperature between 15.0 and 25.0
temp = random.uniform(15.0, 25.0)
print(f"Temperature: {temp:.1f}°C")
# Example 2: Random coordinate in 2D space
x = random.uniform(-10, 10)
y = random.uniform(-10, 10)
print(f"Coordinate: ({x:.2f}, {y:.2f})")
# Example 3: Random price between 9.99 and 99.99
price = random.uniform(9.99, 99.99)
print(f"Price: ${price:.2f}")
3. random.randint(a, b)
Returns a random integer between a and b (inclusive)
python
# Example 1: Dice roll
dice = random.randint(1, 6)
print(f"You rolled a {dice}")
# Example 2: Random age between 18 and 65
age = random.randint(18, 65)
print(f"Random age: {age}")
# Example 3: Lottery number between 1 and 49
lottery = random.randint(1, 49)
print(f"Lottery number: {lottery}")
Sequence Operations
4. random.choice(seq)
Returns a random element from a non-empty sequence
python
colors = ['red', 'green', 'blue', 'yellow', 'black']
# Example 1: Random color selection
print(f"Today's color: {random.choice(colors)}")
# Example 2: Random direction
directions = ['north', 'south', 'east', 'west']
print(f"Go {random.choice(directions)}")
# Example 3: Random playing card
cards = ['Ace', '2', '3', 'King', 'Queen', 'Jack']
print(f"You drew: {random.choice(cards)}")
5. random.choices(population, weights=None, k=1)
Returns a k-sized list of elements chosen with replacement
python
# Example 1: Multiple random colors with weights
print(random.choices(colors, weights=[10, 5, 5, 3, 1], k=3))
# Example 2: Simulating dice rolls
print(f"5 dice rolls: {random.choices(range(1,7), k=5)}")
# Example 3: Lottery numbers (with possible duplicates)
print(f"Lottery numbers: {random.choices(range(1,50), k=6)}")
6. random.sample(population, k)
Returns a k-length list of unique elements chosen without replacement
python
# Example 1: Lottery numbers (no duplicates)
print(f"Unique lottery numbers: {random.sample(range(1,50), 6)}")
# Example 2: Random team selection
players = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
team = random.sample(players, 2)
print(f"Team members: {team}")
# Example 3: Random password characters
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'
password = ''.join(random.sample(chars, 8))
print(f"Random password: {password}")
7. random.shuffle(x)
Shuffles a sequence in place
python
# Example 1: Shuffling a deck of cards
deck = list(range(1, 53))
random.shuffle(deck)
print(f"Shuffled deck: {deck[:5]}...")
# Example 2: Shuffling a quiz question order
questions = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
random.shuffle(questions)
print(f"Question order: {questions}")
# Example 3: Shuffling a playlist
songs = ['Song1', 'Song2', 'Song3', 'Song4', 'Song5']
random.shuffle(songs)
print(f"Playlist order: {songs}")
List Permutation
import itertools as it
lst = ['A', 'B', 'C', 'D']
perms = it.permutations(lst, r=2)
perm_list = list(perms)
print('Permutations')
for t in perm_list:
print(t)
Mean – Median – Mode
import statistics as st
lst = [6, 8, 4, 9, 3, 10, 8, 11, 5, 7, 8, 4, 2]
mean = st.mean(lst)
median = st.median(lst)
mode = st.mode(lst)
print('Mean:', mean)
print('Median:', median)
print('Mode:', mode)
Python statistics Module Explained with Examples
The statistics module provides functions for mathematical statistics calculations on numeric data. It’s part of Python’s standard library and is useful for basic statistical operations.
Importing the Module
python
import statistics
Measures of Central Tendency
1. statistics.mean(data)
Calculates the arithmetic mean (average) of data.
python
# Example 1: Basic mean calculation
grades = [85, 90, 78, 92, 88]
avg_grade = statistics.mean(grades)
print(f"Average grade: {avg_grade}") # Average grade: 86.6
# Example 2: Mean of temperatures
temps = [22.5, 23.0, 21.8, 24.2, 22.0]
avg_temp = statistics.mean(temps)
print(f"Average temperature: {avg_temp:.1f}°C") # Average temperature: 22.7°C
# Example 3: Mean with empty data (raises error)
try:
print(statistics.mean([]))
except statistics.StatisticsError as e:
print(f"Error: {e}") # Error: mean requires at least one data point
2. statistics.median(data)
Calculates the median (middle value) of data.
python
# Example 1: Basic median with odd number of elements
salaries = [45000, 52000, 48000, 62000, 55000]
median_salary = statistics.median(salaries)
print(f"Median salary: ${median_salary}") # Median salary: $52000
# Example 2: Median with even number of elements
house_prices = [325000, 285000, 410000, 380000]
median_price = statistics.median(house_prices)
print(f"Median house price: ${median_price}") # Median house price: $352500.0
# Example 3: Median with unsorted data
test_scores = [78, 85, 92, 85, 90]
median_score = statistics.median(test_scores)
print(f"Median test score: {median_score}") # Median test score: 85
3. statistics.mode(data)
Returns the single most common data point (mode).
python
# Example 1: Basic mode calculation
colors = ['red', 'blue', 'blue', 'green', 'red', 'blue']
common_color = statistics.mode(colors)
print(f"Most common color: {common_color}") # Most common color: blue
# Example 2: Mode of numeric data
dice_rolls = [1, 2, 3, 4, 4, 4, 5, 6]
common_roll = statistics.mode(dice_rolls)
print(f"Most common dice roll: {common_roll}") # Most common dice roll: 4
# Example 3: No unique mode (raises error)
try:
numbers = [1, 2, 2, 3, 3]
print(statistics.mode(numbers))
except statistics.StatisticsError as e:
print(f"Error: {e}") # Error: no unique mode; found 2 equally common values
4. statistics.median_low() and statistics.median_high()
Alternative median calculations for even-sized datasets.
python
# Example 1: median_low vs median_high
values = [1, 3, 5, 7]
print(f"Low median: {statistics.median_low(values)}") # Low median: 3
print(f"High median: {statistics.median_high(values)}") # High median: 5
# Example 2: Comparing with regular median
print(f"Regular median: {statistics.median(values)}") # Regular median: 4.0
# Example 3: With odd-sized dataset (all medians same)
odd_values = [1, 3, 5]
print(f"All medians same: {statistics.median(odd_values) == statistics.median_low(odd_values) == statistics.median_high(odd_values)}")
# All medians same: True
Measures of Spread
5. statistics.stdev(data, xbar=None)
Calculates the sample standard deviation.
python
# Example 1: Basic standard deviation
heights = [170, 175, 168, 172, 180]
std_dev = statistics.stdev(heights)
print(f"Standard deviation of heights: {std_dev:.2f} cm") # ~4.15 cm
# Example 2: Comparing two datasets
group1 = [85, 90, 78, 92, 88]
group2 = [70, 95, 82, 93, 85]
print(f"Group 1 stddev: {statistics.stdev(group1):.2f}") # ~5.50
print(f"Group 2 stddev: {statistics.stdev(group2):.2f}") # ~9.19
# Example 3: With pre-calculated mean
temps = [22.5, 23.0, 21.8, 24.2, 22.0]
mean_temp = statistics.mean(temps)
std_temp = statistics.stdev(temps, mean_temp)
print(f"Temperature stddev: {std_temp:.2f}°C") # ~0.92°C
6. statistics.variance(data, xbar=None)
Calculates the sample variance.
python
# Example 1: Basic variance
returns = [0.05, 0.02, -0.01, 0.03, 0.01]
var = statistics.variance(returns)
print(f"Variance of returns: {var:.6f}") # ~0.000567
# Example 2: Variance vs standard deviation
data = [10, 12, 14, 16, 18]
print(f"Variance: {statistics.variance(data)}") # 10.0
print(f"Stddev: {statistics.stdev(data)}") # 3.162...
# Example 3: Financial application
portfolio = [15000, 18200, 17500, 19100, 16800]
print(f"Portfolio variance: {statistics.variance(portfolio):.2f}")
# Portfolio variance: 16937000.00
7. statistics.quantiles(data, *, n=4)
Divides data into intervals with equal probability.
python
# Example 1: Quartiles (default)
scores = [65, 72, 78, 81, 85, 88, 92, 95]
quartiles = statistics.quantiles(scores)
print(f"Quartiles: {quartiles}") # [72.75, 83.0, 89.0]
# Example 2: Deciles (n=10)
deciles = statistics.quantiles(scores, n=10)
print(f"First decile: {deciles[0]:.1f}") # First decile: 68.4
# Example 3: Percentiles (n=100)
percentiles = statistics.quantiles(scores, n=100)
print(f"90th percentile: {percentiles[89]:.1f}") # 90th percentile: 93.8
Advanced Statistics
8. statistics.correlation(x, y)
Calculates Pearson’s correlation coefficient.
python
# Example 1: Positive correlation
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
print(f"Correlation: {statistics.correlation(x, y)}") # 1.0
# Example 2: Negative correlation
a = [10, 8, 6, 4, 2]
b = [1, 2, 3, 4, 5]
print(f"Correlation: {statistics.correlation(a, b)}") # -1.0
# Example 3: No correlation
c = [1, 2, 3, 4, 5]
d = [5, 1, 4, 2, 3]
print(f"Correlation: {statistics.correlation(c, d):.2f}") # ~-0.30
9. statistics.linear_regression(x, y)
Calculates a linear regression.
python
# Example 1: Perfect linear relationship
x = [1, 2, 3, 4, 5]
y = [3, 5, 7, 9, 11]
slope, intercept = statistics.linear_regression(x, y)
print(f"y = {slope:.2f}x + {intercept:.2f}") # y = 2.00x + 1.00
# Example 2: Predicting values
study_hours = [2, 4, 6, 8, 10]
test_scores = [65, 80, 85, 90, 95]
slope, intercept = statistics.linear_regression(study_hours, test_scores)
predicted = slope * 7 + intercept
print(f"Predicted score for 7 hours: {predicted:.1f}") # ~87.5
# Example 3: With proportional relationship
a = [10, 20, 30, 40, 50]
b = [5, 10, 15, 20, 25]
slope, intercept = statistics.linear_regression(a, b)
print(f"Slope: {slope:.2f}, Intercept: {intercept:.2f}") # Slope: 0.50, Intercept: 0.00
Handling Data
10. statistics.harmonic_mean(data)
Calculates the harmonic mean.
python
# Example 1: Speed calculation
speeds = [60, 40] # 60 km/h one way, 40 km/h return
h_mean = statistics.harmonic_mean(speeds)
print(f"Average speed: {h_mean:.1f} km/h") # 48.0 km/h
# Example 2: Financial ratios
ratios = [1.2, 1.5, 2.0]
print(f"Harmonic mean of ratios: {statistics.harmonic_mean(ratios):.2f}") # ~1.43
# Example 3: Electrical resistance
resistances = [10, 20, 30] # Parallel resistors
total_r = statistics.harmonic_mean(resistances) / len(resistances)
print(f"Total resistance: {total_r:.2f} ohms") # 5.45 ohms
11. statistics.geometric_mean(data)
Calculates the geometric mean.
python
# Example 1: Growth rates
growth_rates = [1.1, 1.2, 1.15] # 10%, 20%, 15% growth
g_mean = statistics.geometric_mean(growth_rates)
print(f"Average growth rate: {(g_mean-1)*100:.2f}%") # ~14.89%
# Example 2: Investment returns
returns = [1.05, 1.02, 0.98, 1.10] # 5%, 2%, -2%, 10%
print(f"Geometric mean return: {statistics.geometric_mean(returns):.4f}") # ~1.0366
# Example 3: Aspect ratios
ratios = [16/9, 4/3, 1/1]
print(f"Average aspect ratio: {statistics.geometric_mean(ratios):.2f}") # ~1.33
Multimodal Data
12. statistics.multimode(data)
Returns a list of the most frequently occurring values.
python
# Example 1: Multiple modes
grades = ['A', 'B', 'A', 'C', 'B', 'B']
print(f"Most common grades: {statistics.multimode(grades)}") # ['B']
# Example 2: Multiple modes
colors = ['red', 'blue', 'blue', 'green', 'red']
print(f"Most common colors: {statistics.multimode(colors)}") # ['red', 'blue']
# Example 3: All unique (no mode)
unique = [1, 2, 3, 4]
print(f"Multimode of unique values: {statistics.multimode(unique)}") # [1, 2, 3, 4]
Working with Fractions
13. statistics.fmean(data)
Faster floating-point arithmetic mean.
python
# Example 1: Basic fmean
values = [0.1, 0.2, 0.3, 0.4]
print(f"Floating-point mean: {statistics.fmean(values)}") # 0.25
# Example 2: Large dataset
big_data = range(1, 1000001)
print(f"Mean of big data: {statistics.fmean(big_data)}") # 500000.5
# Example 3: Mixed types
mixed = [1, 2.5, 3, 4.75]
print(f"Mean of mixed types: {statistics.fmean(mixed)}") # 2.8125
14. statistics.pstdev(data, mu=None) and statistics.pvariance(data, mu=None)
Population standard deviation and variance.
python
# Example 1: Population vs sample
data = [10, 12, 14, 16, 18]
print(f"Sample variance: {statistics.variance(data)}") # 10.0
print(f"Population variance: {statistics.pvariance(data)}") # 8.0
# Example 2: With known mean
mu = statistics.mean(data)
print(f"Population stddev: {statistics.pstdev(data, mu)}") # ~2.828
# Example 3: Complete population
ages = [22, 23, 22, 25, 23] # All employees
print(f"Population variance of ages: {statistics.pvariance(ages):.2f}") # 1.36
The statistics module is particularly useful for basic statistical analysis without requiring external dependencies like NumPy. For more advanced statistical operations, consider libraries like NumPy, SciPy, or pandas.
Find Longest List
lists = [[1, 2, 3], [1, 1, 1, 1, 1], [2, 2, 3, 3]]
max_list = max(lists, key=length)
print(‘Longest List:’, max_list)
1. max() – Find the largest item
python
# Basic usage numbers = [3, 1, 4, 1, 5, 9, 2] print(max(numbers)) # Output: 9 # With key function words = ["apple", "banana", "cherry"] print(max(words, key=len)) # Output: "banana" # With multiple iterables print(max(5, 10, 15)) # Output: 15
2. min() – Find the smallest item (counterpart to max)
python
print(min(numbers)) # Output: 1 print(min(words, key=len)) # Output: "apple" print(min(5, 10, 15)) # Output: 5
3. sorted() – Return sorted list (often used with max/min)
python
# Get top 3 values print(sorted(numbers, reverse=True)[:3]) # Output: [9, 5, 4] # With key function print(sorted(words, key=len, reverse=True)) # Output: ['banana', 'apple', 'cherry']
4. reversed() – Reverse iterator (useful with max/min)
python
# Get max in reversed order print(max(reversed(numbers))) # Output: 2 (last item is max when reversed)
5. heapq.nlargest()/nsmallest() – Efficient for large datasets
python
import heapq # Get 3 largest numbers print(heapq.nlargest(3, numbers)) # Output: [9, 5, 4] # With key function print(heapq.nsmallest(2, words, key=len)) # Output: ['apple', 'cherry']
6. all() – Check if all items are truthy (often used with max conditions)
python
# Check if all numbers are below threshold print(all(x < 10 for x in numbers)) # Output: True
7. any() – Check if any item is truthy (often used with min conditions)
python
# Check if any number exceeds threshold print(any(x > 5 for x in numbers)) # Output: True
8. sum() – Sum of items (often combined with max/min)
python
# Sum of top 3 numbers print(sum(sorted(numbers, reverse=True)[:3])) # Output: 18
9. map() – Apply function (often used with max key)
python
# Using map instead of key function print(max(words, key=lambda x: len(x))) # Equivalent to: print(max(map(len, words))) # Output: 6 (just the length)
10. filter() – Filter items (often before max/min)
python
# Get max even number print(max(filter(lambda x: x % 2 == 0, numbers))) # Output: 4
11. zip() – Combine iterables (for multi-criteria max)
python
# Find word with max length and highest ASCII value lengths = map(len, words) ascii_sums = [sum(ord(c) for c in w) for w in words] print(words[max(zip(lengths, ascii_sums, range(len(words))))[2]]) # Output: "banana"
12. enumerate() – Add counter (to get index of max)
python
# Get index of maximum value
max_index = max(enumerate(numbers), key=lambda x: x[1])[0]
print(f"Max value {numbers[max_index]} at index {max_index}") # Output: Max value 9 at index 5
These built-ins are particularly powerful when combined:
python
# Most common word (using max with count) words = ["apple", "banana", "apple", "cherry", "banana", "apple"] print(max(set(words), key=words.count)) # Output: "apple" # Longest word containing 'a' print(max([w for w in words if 'a' in w], key=len)) # Output: "banana"