Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program in Python to generate any random five prime numbers between 100 to 150 in a Series
To generate five random prime numbers between 100 and 150 using a Pandas Series, we need to first identify all prime numbers in this range, then randomly select five of them.
Solution
We will follow these steps −
Create a function to check if a number is prime
Find all prime numbers between 100 and 150
Use
random.sample()to select 5 random primesConvert the result to a Pandas Series
Example
Let us see the implementation to generate random prime numbers −
import pandas as pd
import random
def is_prime(num):
"""Check if a number is prime"""
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
# Find all prime numbers between 100 and 150
primes = []
for i in range(100, 151):
if is_prime(i):
primes.append(i)
print("All primes between 100-150:", primes)
# Select 5 random prime numbers
random_primes = random.sample(primes, 5)
rand_series = pd.Series(random_primes)
print("\nRandom 5 prime numbers:")
print(rand_series)
The output will show 5 randomly selected prime numbers −
All primes between 100-150: [101, 103, 107, 109, 113, 127, 131, 137, 139, 149] Random 5 prime numbers: 0 149 1 103 2 137 3 127 4 109 dtype: int64
Alternative Approach Using List Comprehension
Here's a more concise version using list comprehension −
import pandas as pd
import random
def is_prime(num):
return num > 1 and all(num % i != 0 for i in range(2, int(num ** 0.5) + 1))
# Find primes using list comprehension
primes = [num for num in range(100, 151) if is_prime(num)]
# Create Series with 5 random primes
rand_series = pd.Series(random.sample(primes, 5))
print(rand_series)
0 113 1 131 2 101 3 139 4 103 dtype: int64
How It Works
The is_prime() function efficiently checks primality by testing divisibility only up to the square root of the number. The random.sample() function ensures we get 5 unique random selections from our prime list.
Conclusion
This approach efficiently finds all primes between 100-150, then randomly selects five using random.sample(). The optimized prime checking function makes the solution both readable and performant.
