Python - Practice Problems
Python - Practice Problems
P42) From a pack of 14 cards, having numbers 1 to 10 alongwith Jack, King, Queen, Ace; choose two
cards. Find the percent of times King and Queen both gets chosen for 10000 simulations.
import random
no_of_sims = 10000
for i in range(no_of_sims):
choice = random.sample(cards, 4)
while True:
ch = random.choice(scores)
ball += 1
if ch == 'OUT':
print("\nYou are OUT!!!")
print(f"Your score is {score} in {ball} balls")
break
else:
score += ch
print(f"\nYou have scored {ch}")
print(f"TOTAL SCORE: {score}")
if next_ball == 'N':
print("\nYou have forfeited")
print(f"Your score is {score} in {ball} balls")
break
P44) Two players roll two dices simultaneously, and the player with higher number wins. Perform the
simulation.
import random
player1_roll = random.randrange(1, 7)
player2_roll = random.randrange(1, 7)
P45) For 10000 simulations, let dices roll simultaneously, and calculate the percentage for which the
sum of two dice scores comes as 6.
import random
num_simulations = 10000
success_count = 0
for _ in range(num_simulations):
dice_roll_one = random.randrange(1, 7)
dice_roll_two = random.randrange(1, 7)
dice_roll = dice_roll_two + dice_roll_one
if dice_roll == 6:
success_count += 1
for letter in x:
if letter.upper() == 'I':
nos.append(1)
elif letter.upper() == 'V':
nos.append(5)
elif letter.upper() == 'X':
nos.append(10)
elif letter.upper() == 'L':
nos.append(50)
elif letter.upper() == 'C':
nos.append(100)
elif letter.upper() == 'D':
nos.append(500)
elif letter.upper() == 'M':
nos.append(1000)
res = 0
for i in range(len(nos)):
if i == len(nos) - 1:
res = res + nos[i]
print(res)
# Example list
input_list = [1, 2, 3, 4, 5, 1, 2, 1, 1, 7, 8, 3]
counted_numbers = []
unique_count = 0
seen_values = []
combinations = []
for item in list1:
if item in list2:
combinations.append(item)
print("All unique combinations:")
for combination in combinations:
print(combination)
P50) Write a program to calculate the sum of series up to n term. For example, if n =5 the series will
become 2 + 22 + 222 + 2222 + 22222 = 24690
n = int(input("Enter the value of n: "))
series_sum = 0
term = 2
for i in range(n):
series_sum += term
term = (term * 10) + 2
P51) Write a program to calculate the sum of the first n terms of the harmonic series: 1 + 1/2 + 1/3 +
1/4 + ... 1/n
n = int(input("Enter the value of n: "))
total_sum = 0
P52) Write a program to calculate the sum of the first n terms of the alternating series: 1 - 2 + 3 - 4 +
... – n
n = int(input("Enter the value of n: "))
total_sum = 0
for i in range(1, n + 1):
if i % 2 == 0:
total_sum -= i
else:
total_sum += i
P53) Write a program to calculate the sum of the square roots of the natural numbers up to the n-th
term: √1 + √2 + √3 + ... + √n
print(f"Sum of the first {n} terms of the square root series: {total_sum}")
P54) Generate 3 random integers between 1 and N which is divisible by 5.
import random