You are on page 1of 22

Q.42.

Write a python program to calculate multiplication of two


random float numbers ¶
In [2]: import random

def multiply_random_floats():
# Generate two random float numbers between 0 and 1
num1 = random.random()
num2 = random.random()

# Calculate the product
result = num1 * num2

return result
multiply_random_floats()

Out[2]: 0.2343729461350695

Q.43. Create a python program to demonstrate rolling a dice in


such a way that every time one get the same number
In [2]: 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))

Randomly selecting same number of a dice


4
4
4
4
4
Q. 44. "Write a python program to generate a series of random
integers between 1 and 6 and count how often each appears. See
how close each approaches to 1/6 of the total."
In [4]: # Roll a 6- sided dice and see how fair it is.
from random import randint
NUMROLLS = 1000000
def rollDice ( ):
# Create an list of 6 zeros :
counts = [0] * 6
for i in range ( NUMROLLS ):
# Record each roll in counts list :
roll = randint (1 , 6)
counts [ roll -1] += 1
return counts
def printResults ( counts ) :
# Compute and print expected probability :
oneSixth = 1/6
print (" 1/6 = " , round ( oneSixth , 6) )
# Print header line :
print ( " Roll \ tCount \ tProbability \ tDifference " )
# See how close the actual values were to the
# expected probability of 1/6.
for i in range ( 1, 7 ):
count = counts [i -1]
prob = count / NUMROLLS
diff = (( prob - oneSixth ) / oneSixth ) * 100.0
print (i , count , prob , round ( diff , 2) , sep ="\t" )
def main () :
counts = rollDice ()
printResults ( counts )
main ()

1/6 = 0.166667
Roll \ tCount \ tProbability \ tDifference
1 166461 0.166461 -0.12
2 166429 0.166429 -0.14
3 166520 0.16652 -0.09
4 166467 0.166467 -0.12
5 166994 0.166994 0.2
6 167129 0.167129 0.28
Q. 45. Write a python program to find how many times do you have
to flip a coin to get k heads in a row?
In [4]: import random

def flip_coin():
return random.choice(['H', 'T']) # 'H' for Heads, 'T' for Tails

def find_k_heads_in_row(k):
flips_count = 0
consecutive_heads = 0

while consecutive_heads < k:
flip_result = flip_coin()
flips_count += 1

if flip_result == 'H':
consecutive_heads += 1
else:
consecutive_heads = 0

return flips_count


k_heads = 3 # You can adjust the value of k as desired.

flips_needed = find_k_heads_in_row(k_heads)
print(f"To get {k_heads} consecutive heads in a row, you need to flip the coin {flips_needed} times.")

To get 3 consecutive heads in a row, you need to flip the coin 3 times.

Q. 46. Implement a guessing game program by generating a


random integer between 1 and 99. Accept guesses from
the user until he or she guesses the number or exceeds the allowed number of guesses. It should be possible to guess the number in
no more than 7 guesses The program should behave as follows: 1 If the user guesses the number congratulate him or her and stop
In [6]: import random

def generate_random_number():
return random.randint(1, 99)

def get_user_guess():
while True:
try:
guess = int(input("Enter your guess (between 1 and 99): "))
return guess
except ValueError:
print("Invalid input! Please enter a valid integer.")

def play_guessing_game():
random_number = generate_random_number()
max_guesses = 7
num_guesses = 0

print("Welcome to the guessing game!")
print("You have 7 guesses to find the number.")

while num_guesses < max_guesses:
num_guesses += 1
user_guess = get_user_guess()

if user_guess == random_number:
print(f"Congratulations! You guessed the number ({random_number}) correctly in {num_guesses} guess
break
elif user_guess < random_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")

if num_guesses == max_guesses:
print(f"Sorry, you have exceeded the maximum number of guesses ({max_guesses}). The number was {random


play_guessing_game()

Welcome to the guessing game!
You have 7 guesses to find the number.
Enter your guess (between 1 and 99): 56
Too high! Try again.
Enter your guess (between 1 and 99): 23
Too low! Try again.
Enter your guess (between 1 and 99): 45
Too high! Try again.
Enter your guess (between 1 and 99): 34
Too low! Try again.
Enter your guess (between 1 and 99): 40
Too high! Try again.
Enter your guess (between 1 and 99): 38
Too high! Try again.
Enter your guess (between 1 and 99): 37
Congratulations! You guessed the number (37) correctly in 7 guesses!
Sorry, you have exceeded the maximum number of guesses (7). The number was 37.

Q. 47. Write a python program to generate a Random Maze.


In [4]: import random

def create_empty_maze(rows, cols):
return [["#" for _ in range(cols)] for _ in range(rows)]

def get_neighbours(cell, rows, cols):
row, col = cell
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
neighbours = []

for dr, dc in directions:


nr, nc = row + dr, col + dc
if 0 <= nr < rows and 0 <= nc < cols:
neighbours.append((nr, nc))

return neighbours

def recursive_backtracking(row, col, maze, visited):
visited[row][col] = True
neighbours = get_neighbours((row, col), len(maze), len(maze[0]))
random.shuffle(neighbours)

for nr, nc in neighbours:
if not visited[nr][nc]:
if nr == row:
maze[row][max(col, nc)] = " "
else:
maze[max(row, nr)][col] = " "
recursive_backtracking(nr, nc, maze, visited)

def generate_random_maze(rows, cols):
maze = create_empty_maze(rows, cols)
visited = [[False for _ in range(cols)] for _ in range(rows)]

start_row, start_col = random.randint(0, rows - 1), random.randint(0, cols - 1)
recursive_backtracking(start_row, start_col, maze, visited)

return maze

def print_maze(maze):
for row in maze:
print("".join(row))

maze_rows = 11 # You can adjust the number of rows and columns as desired.
maze_cols = 11
maze = generate_random_maze(maze_rows, maze_cols)
print_maze(maze)

# # # #
#
# # #
# #
##
# # #
# # #
# #

# #

Q. 48. Write a python program to generate a Random sentence


using articles, nouns, verbs and adverbs.
In [7]: import random

def generate_random_sentence():
articles = ["the", "a", "an"]
nouns = ["dog", "cat", "bird", "house", "car", "tree", "book", "computer", "flower"]
verbs = ["jumped", "ran", "slept", "ate", "read", "wrote", "played", "swam", "drove"]
adverbs = ["quickly", "slowly", "loudly", "quietly", "eagerly", "carefully"]

sentence = f"{random.choice(articles).capitalize()} {random.choice(nouns)} "
sentence += f"{random.choice(verbs)} {random.choice(adverbs)}."

return sentence


random_sentence = generate_random_sentence()
print(random_sentence)

The house slept loudly.

Q. 49. Write a program to create Random Binary Tree Generation


In [8]: import random


class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

def generate_random_binary_tree(size):
if size == 0:
return None

# Choose random sizes for left and right subtrees
left_size = random.randint(0, size-1)
right_size = size - 1 - left_size

# Generate left and right subtrees recursively
left_subtree = generate_random_binary_tree(left_size)
right_subtree = generate_random_binary_tree(right_size)

# Create new node with random value
root = Node(random.randint(0, 100))

# Assign left and right subtrees to children
root.left = left_subtree
root.right = right_subtree

return root


def print_tree(node, level=0):
if node is not None:
print_tree(node.right, level + 1)
print(" " * 4 * level + "->", node.value)
print_tree(node.left, level + 1)


tree = generate_random_binary_tree(5)
print_tree(tree)

-> 86
-> 81
-> 52
-> 88
-> 43

Q. 50. Write a program to create Random Password Strength


Checker.
In [17]: import random

def generate_random_password(length=10):
characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+=<>?/[]{},.;:"
password = ""

for _ in range(length):
password += random.choice(characters)

return password

def check_password_strength(password):
strength = 0

if any(char.isdigit() for char in password):
strength += 1

if any(char.isupper() for char in password):
strength += 1

if any(char.islower() for char in password):
strength += 1

if any(char in "!@#$%^&*()_-+=<>?/[]{},.;:" for char in password):
strength += 1

return strength


password_length = 12 # You can adjust the password length as desired.
password = generate_random_password(password_length)

print("Generated Password:", password)

password_strength = check_password_strength(password)

print("Password Strength:")
print("Weak" if password_strength <= 2 else "Moderate" if password_strength == 3 else "Strong")

Generated Password: @Zz{Jch$_MQf
Password Strength:
Moderate

Q. 51. Write a guess a number game program using random


module.
In [18]: import random

def guess_the_number():
secret_number = random.randint(1, 100)
attempts = 0

print("Welcome to the Guess the Number game!")
print("I have chosen a number between 1 and 100. Can you guess it?")

while True:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
continue

attempts += 1

if user_guess == secret_number:
print(f"Congratulations! You guessed the number {secret_number} correctly in {attempts} attempts!"
break
elif user_guess < secret_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")

guess_the_number()

Welcome to the Guess the Number game!
I have chosen a number between 1 and 100. Can you guess it?
Enter your guess: 23
Too low! Try again.
Enter your guess: 45
Too low! Try again.
Enter your guess: 89
Too low! Try again.
Enter your guess: 99
Too high! Try again.
Enter your guess: 93
Too high! Try again.
Enter your guess: 92
Too high! Try again.
Enter your guess: 90
Congratulations! You guessed the number 90 correctly in 7 attempts!

Q. 52. Write a program to shuffle a given deck of cards randomly.


In [1]: import random

def create_deck():
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]

deck = [(rank, suit) for rank in ranks for suit in suits]
return deck

def shuffle_deck(deck):
random.shuffle(deck)


deck = create_deck()
print("Original Deck:")
for card in deck:
print(f"{card[0]} of {card[1]}")

shuffle_deck(deck)

print("\nShuffled Deck:")
for card in deck:
print(f"{card[0]} of {card[1]}")

Original Deck:
2 of Hearts
2 of Diamonds
2 of Clubs
2 of Spades
3 of Hearts
3 of Diamonds
3 of Clubs
3 of Spades
4 of Hearts
4 of Diamonds
4 of Clubs
4 of Spades
5 of Hearts
5 of Diamonds
5 of Clubs
5 of Spades
6 of Hearts
6 of Diamonds
6 f Cl b

Q. 53. Write a python program to create rock paper scissor game


using random module. also provided in notes
In [2]: import random

def get_user_choice():
while True:
user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
if user_choice in ["rock", "paper", "scissors"]:
return user_choice
else:
print("Invalid choice! Please enter rock, paper, or scissors.")

def get_computer_choice():
choices = ["rock", "paper", "scissors"]
return random.choice(choices)

def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "It's a tie!"
elif (
(user_choice == "rock" and computer_choice == "scissors") or
(user_choice == "paper" and computer_choice == "rock") or
(user_choice == "scissors" and computer_choice == "paper")
):
return "Congratulations! You win!"
else:
return "You lose! Better luck next time."


print("Welcome to Rock-Paper-Scissors Game!")
user_choice = get_user_choice()
computer_choice = get_computer_choice()

print(f"\nYou chose: {user_choice}")
print(f"Computer chose: {computer_choice}")

result = determine_winner(user_choice, computer_choice)
print(result)

Welcome to Rock-Paper-Scissors Game!
Enter your choice (rock, paper, or scissors): rock

You chose: rock


Computer chose: rock
It's a tie!

In [ ]: ​

You might also like