Python Random Data Generation Exercise 2
Python Random Data Generation Exercise 2
Exercise
Prepared by Dr. Esmat Mohamed
This Python exercise will help you to practice random data generation techniques. This exercise
question focuses on generating random numbers, choices, and samples using the random module
and secrets module.
10 questions.
The solution is provided at the end of each question.
When you complete each question, you will be more familiar with random data generation
techniques in Python.
Refer to the following tutorials to solve the exercise.
Table of contents
Exercise 1: Generate 3 random integers between 100 and 999 which is divisible by 5
Exercise 2: Random Lottery Pick. Generate 100 random lottery tickets and pick two lucky
tickets from it as a winner.
Exercise 3: Generate 6 digit random secure OTP
Exercise 4: Pick a random character from a given String
Exercise 5: Generate random String of length 5
Exercise 6: Generate a random Password which meets the following conditions
Exercise 7: Calculate multiplication of two random float numbers
Exercise 8: Generate random secure token of 64 bytes and random URL
Exercise 9: Roll dice in such a way that every time you get the same number
Exercise 10: Generate a random date between given start and end dates
1
Exercise 1: Generate 3 random integers between 100
and 999 which is divisible by 5
Reference article for help: Python get a random number within a range
Show Solution
import random
print("Generating 3 random integer number between 100 and 999 divisible by 5")
for num in range(3):
print(random.randrange(100, 999, 5), end=', ')
Show Solution
import random
lottery_tickets_list = []
print("creating 100 random lottery tickets")
# to get 100 ticket
for i in range(100):
# ticket number must be 10 digit (1000000000, 9999999999)
lottery_tickets_list.append(random.randrange(1000000000, 9999999999))
# pick 2 luck tickets
winners = random.sample(lottery_tickets_list, 2)
print("Lucky 2 lottery tickets are", winners)
2
Exercise 3: Generate 6 digit random secure OTP
Reference article for help:
import secrets
Show Solution
import random
name = 'pynative'
char = random.choice(name)
print("random char is ", char)
Show Solution
3
import random
import string
def randomString(stringLength):
"""Generate a random string of 5 charcters"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(stringLength))
Run
Show Solution
import random
import string
def randomPassword():
randomSource = string.ascii_letters + string.digits + string.punctuation
password = random.sample(randomSource, 6)
password += random.sample(string.ascii_uppercase, 2)
password += random.choice(string.digits)
password += random.choice(string.punctuation)
passwordList = list(password)
random.SystemRandom().shuffle(passwordList)
password = ''.join(passwordList)
return password
Run
4
First random float number must be between 0.1 and 1
Second random float number must be between 9.5 and 99.5
Reference article for help: Generate a random float number between a float range
Show Solution
Show Solution
import secrets
Run
import random
dice = [1, 2, 3, 4, 5, 6]
print("Randomly selecting same number of a dice")
for i in range(5):
random.seed(25)
print(random.choice(dice))
Run
5
Exercise 10: Generate a random date between given
start and end dates
Show Solution
import random
import time
Run
Free coding exercises and quizzes cover Python basics, data structure, data
analytics, and more.
Quizzes
Comments
1. Mohammad says
JULY 5, 2022 AT 9:24 AM
Q7:
import random
num1 = random.random()
REPLY
7
2. alcebytes says
JANUARY 3, 2022 AT 10:23 AM
import datetime
import random
datas = []
datas.append(data.strftime('%d-%m-%Y'))
print(*random.sample(datas, 1))
date_generated('03-12-2021','03-01-2022')
# saída
03-01-2022
REPLY
3. Bill says
NOVEMBER 27, 2021 AT 9:19 AM
8
This solution would never have a 0 as the first digit. So piecing together strings of
0-9’s is more accurate and chances of a dup are almost 0.
REPLY
4. cub8 says
JULY 17, 2021 AT 4:27 PM
import datetime
import random
return randomDate
startDate = datetime.date(2016, 1, 1)
REPLY
9
5. Ali says
JULY 19, 2019 AT 1:05 AM
I think I may have found a simpler solution for Q10 as yours was difficult to
follow:
def random_dates(start_date,end_date):
start_date = start_date.split('-')
end_date = end_date.split('-'))
random_day = random.randint(int(start_date[1]),int(end_date[1]))
random_month = random.randint(int(start_date[0]),int(end_date[0]))
print ('Date = ' + str(random_month) + ' - ' + str(random_day) + ' - ' + '2019')
REPLY
6. Vitaliy says
JUNE 23, 2019 AT 9:59 PM
Q5
print("".join(random.choices(string.ascii_letters, k=5)))
REPLY
10
import random, datetime as dt
start_date = dt.date(2019, 1, 1)
r = random.randint(0, delta)
REPLY
Q6 – Hmm. I hadn’t come across the shuffle function, so rather than code one
myself, I arrived at this alternative solution. It is obviously less efficient than your
answer, but given the scale of the problem the timing difference is not of
practical significance.
pw = ''
uc = 0
11
dg = 0
sp = 0
z = secrets.choice(s)
if z in string.ascii_uppercase: uc += 1
elif z in string.digits: dg += 1
elif z in string.punctuation: sp += 1
pw += z
if len(pw) == 10:
pw = ''
uc = dg = sp = 0
print(pw)
REPLY
num = 0
upper_let = 0
special_char = 0
while True:
12
random_password = ''.join(random.choice(string.ascii_letters + string.digits +
string.punctuation ) for i in range(10))
if item.isupper():
upper_let += 1
if item.isnumeric():
num += 1
special_char += 1
break
REPLY
Q5 – badly worded. “String must be the combination of the UPPER case and
lower case letters only. No numbers and a special symbol.”
Thus can only be interpreted as requiring a string comprised of letters (any case –
or arguably a mix of cases) plus a special symbol. (A slightly more difficult
problem which I addressed.)
I suggest re-wording it as “The string must contain only upper and/or lower case
alphabetic characters..” There is no need for your second sentence.
REPLY
13
Q2 – Sorry, but I’m afraid your solution is incorrect: it does not preclude duplicate
ticket numbers being generated. For example, substituting smaller values into
your solution for demonstration purposes:
import random
lottery_tickets_list = []
for i in range(10):
lottery_tickets_list.append(random.randrange(10, 20))
print(lottery_tickets_list)
My solution uses a set rather than a list to achieve the correct result:
import random
tickets = set()
tickets.add(random.randrange(1000000000, 10000000000))
print('Drum roll...')
winners = random.sample(tickets, 2)
which outputs
Drum roll…
and the lucky winners are numbers:
14
8975225689 and 1386699143
Note also the use of 10000000000 as the top of the range value rather than your
9999999999 because the end-point for the range is exclusive. (The same
comment applies to Q1, although this does not affect the outcome.)
REPLY
o vahlo says
OCTOBER 23, 2020 AT 12:29 PM
Hi, I believe your conclusion about the original solution is correct but your code could
be simplified as well. This code has done the trick for me:
import random
winners = random.sample(tickets, 2)
print('Winners are:',winners)
I believe as random.sample generates unique choices it can be used for the tickets as
well.
REPLY
Igor says
JULY 25, 2022 AT 4:45 PM
tickets = []
15
tickets_amount = 100
counter = 0
while True:
tickets.append(ticket)
counter += 1
if counter == tickets_amount:
break
REPLY
16