Lab Experiments and Solutions - Algorithmic thinking with Python KTU S1 2024 scheme
LAB Experiments:
1. Simple desktop calculator using Python. Only the five basic arithmetic operators.
2. Create, concatenate, and print a string and access a sub-string from a given string.
3. Familiarize time and date in various formats (Eg. “Thu Jul 11 10:26:23 IST 2024”).
4. Write a program to create, append, and remove elements in lists.( using Numpy array also)
5. Program to find the largest of three numbers.
6. Convert temperature values back and forth between Celsius (c), and Fahrenheit (f). [Formula: °C = (°F - 32) × 5/9]
7. Program to construct patterns of stars (*), using a nested for loop.
8. A program that prints prime numbers less than N.
9. Program to find the factorial of a number using Recursion.
10. Recursive function to add two positive numbers.
11. Recursive function to multiply two positive numbers.
12. Recursive function to find the greatest common divisor of two positive numbers.
13. A program that accepts the lengths of three sides of a triangle as inputs. The program should output whether or not the triangle is a right triangle (Recall from the Pythagorean Theorem that in a right triangle, the square of one side equals the sum of the squares of the other two sides). Implement using functions.
14. Program to define a module to find Fibonacci Numbers and import the module to another program.
15. Program to check whether the given number is a valid mobile number or not using functions.
Rules:
1. Every number should contain exactly 10 digits.
2. The first digit should be 7 or 8 or 9
16. Input two lists from the user. Merge these lists into a third list such that in the merged list, all even numbers occur first followed by odd numbers. Both the even numbers and odd numbers should be in sorted order.
17. Write a program to play a sticks game in which there are 16 sticks. Two players take turns to play the game. Each player picks one set of sticks (needn’t be adjacent) during his turn. A set contains 1, 2, or 3 sticks. The player who takes the last stick is the loser. The number of sticks in the set is to be input.
18. Suppose you're on a game show, and you are given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what is behind the doors, opens another door, say No. 3, which has a goat. He then asks, "Do you want to pick door No. 2?"Is it to your advantage to switch your choice?
Solutions
1. Simple desktop calculator using Python. Only the five basic arithmetic operators.
# Simple Desktop Calculator in Python ( using if-elif)
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
choice = input("Enter choice (1/2/3/4/5): ")
if choice in ['1', '2', '3', '4', '5']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
elif choice == '5':
result = num1 % num2
print(f"{num1} % {num2} = {result}")
else:
print("Invalid input. Please select a valid operation.")
Below is the same simple calculator code rewritten using Python's
match
statement (available in Python 3.10 and later). This replaces the earlier if-elif
structure with a match-case
structure.# Simple Desktop Calculator in Python (Using match-case)
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
choice = input("Enter choice (1/2/3/4/5): ")
if choice in ['1', '2', '3', '4', '5']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
match choice:
case '1':
result = num1 + num2
print(f"{num1} + {num2} = {result}")
case '2':
result = num1 - num2
print(f"{num1} - {num2} = {result}")
case '3':
result = num1 * num2
print(f"{num1} * {num2} = {result}")
case '4':
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error! Division by zero.")
case '5':
result = num1 % num2
print(f"{num1} % {num2} = {result}")
else:
print("Invalid input. Please select a valid operation.")
2.Create, concatenate, and print a string and access a sub-string from a given string.
# Read a string from the user
user_string = input("Enter a string: ")
# Create another string
additional_string = " - This is an additional string."
# Concatenate the two strings
concatenated_string = user_string + additional_string
# Print the concatenated string
print("Concatenated String:", concatenated_string)
# Access and print a substring from the user's string
# Example: Let's extract the first 5 characters from the user's string
substring = user_string[:5]
print("Substring (first 5 characters):", substring)
Note: Try various indexing and slicing refer string section in the blog
3.Familiarize time and date in various formats (Eg. “Thu Jul 11 10:26:23 IST 2024”).
Refer blog : date and time in python
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date and time to match the required format
formatted_date = now.strftime("%a %b %d %H:%M:%S IST %Y")
# Print the formatted date
print(formatted_date)
4.Write a program to create, append, and remove elements in lists.( using Numpy array also)
# 1. Creating a List
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)
# 2. Appending Elements to the List
# Appending a single element
my_list.append(60)
print("List after appending 60:", my_list)
# Appending multiple elements (using extend to add multiple elements)
my_list.extend([70, 80, 90])
print("List after appending [70, 80, 90]:", my_list)
# 3. Removing Elements from the List
# Removing an element by value
my_list.remove(30) # Removes the first occurrence of 30
print("List after removing the element 30:", my_list)
# Removing an element by index (using pop)
removed_element = my_list.pop(0) # Removes the element at index 0
print(f"List after removing the element at index 0 ({removed_element}):", my_list)
# Removing multiple elements by slicing
del my_list[0:2] # Removes the first two elements
print("List after removing the first two elements:", my_list)
##############################################################
import numpy as np
# 1. Creating a NumPy array
# Create a NumPy array (which is similar to a list in Python)
array = np.array([10, 20, 30, 40, 50])
print("Original Array:", array)
# 2. Appending Elements to the List
# NumPy doesn't have an append method like Python lists, but we can use np.append
# Appending a single element
array = np.append(array, 60)
print("Array after appending 60:", array)
# Appending multiple elements
array = np.append(array, [70, 80, 90])
print("Array after appending [70, 80, 90]:", array)
# 3. Removing Elements from the List
# NumPy doesn't have a remove method like Python lists, but we can use np.delete
# Removing an element by index
array = np.delete(array, 2) # Removes the element at index 2 (30 in this case)
print("Array after removing the element at index 2:", array)
# Removing multiple elements by indices
array = np.delete(array, [0, 1]) # Removes elements at index 0 and 1
print("Array after removing elements at indices 0 and 1:", array)
5.Program to find the largest of three numbers.
# Input three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Determine the largest number
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
# Print the largest number
print("The largest number is:", largest)
6.Convert temperature values back and forth between Celsius (C), and Fahrenheit (F). [Formula: °C = (°F - 32) × 5/9]
print("\nTemperature Conversion:")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
choice = input("Enter your choice (1/2): ")
if choice == '1':
# Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")
elif choice == '2':
# Convert Fahrenheit to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit}°F is equal to {celsius}°C")
else:
print("Invalid choice. Please enter 1 or 2")
7.Program to construct patterns of stars (*), using a nested for loop.
1.Square Pattern:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
2.Right-Angled Triangle Pattern:
*
* *
* * *
* * * *
* * * * *
3.Pyramid Pattern:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
# 1. Square Pattern
size = 5
print("Square Pattern:")
for i in range(size):
for j in range(size):
print('*', end=' ')
print()
print() # Add an empty line for separation
# 2. Right-Angled Triangle Pattern
print("Right-Angled Triangle Pattern:")
for i in range(1, size + 1):
for j in range(i):
print('*', end=' ')
print()
print() # Add an empty line for separation
# 3. Pyramid Pattern
print("Pyramid Pattern:")
for i in range(size):
# Print leading spaces
for j in range(size - i - 1):
print(' ', end=' ')
# Print stars
for k in range(2 * i + 1):
print('*', end=' ')
print()
8. A program that prints prime numbers less than N.
n = int(input("Enter a range: "))
print(f"Prime numbers less than {n}:")
# Iterate through all numbers from 2 to n-1
for num in range(2, n):
is_prime = True
# Check if num is divisible by any number from 2 to sqrt(num)
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
# Print num if it is prime
if is_prime:
print(num, end=' ')
9.Program to find the factorial of a number using Recursion.
# Recursive function to calculate factorial
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1)
# Input the number
number = int(input("Enter a number: "))
# Calculate factorial
result = factorial(number)
# Print the result
print(f"The factorial of {number} is {result}")
10. Recursive function to add two positive numbers.
# Recursive function to add two positive numbers
def add_positive_numbers(a, b):
# Base case: if one of the numbers is zero
if b == 0:
return a
# Recursive case: increment a and decrement b
return add_positive_numbers(a + 1, b - 1)
# Input two positive numbers
num1 = int(input("Enter the first positive number: "))
num2 = int(input("Enter the second positive number: "))
# Ensure both numbers are positive
if num1 < 0 or num2 < 0:
print("Both numbers must be positive.")
else:
# Calculate the sum using recursion
result = add_positive_numbers(num1, num2)
# Print the result
print(f"The sum of {num1} and {num2} is {result}")
11.Recursive function to multiply two positive numbers.
# Recursive function to multiply two numbers
def multiply(a, b):
# Base case: if one of the numbers is zero
if b == 0:
return 0
# Recursive case: multiply by adding a to the result of multiplying a with (b - 1)
return a + multiply(a, b - 1)
# Input two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calculate the product using recursion
result = multiply(num1, num2)
# Print the result
print(f"The product of {num1} and {num2} is {result}")
12. Recursive function to find the greatest common divisor of two positive numbers.(Euclid's Algorithm)
# Recursive function to find GCD using Euclid's algorithm
def gcd(a, b):
# Base case: if b is 0, gcd is a
if b == 0:
return a
# Recursive case: call gcd with b and a % b
return gcd(b, a % b)
# Input two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calculate the GCD using recursion
result = gcd(num1, num2)
# Print the result
print(f"The GCD of {num1} and {num2} is {result}")
def gcd(a, b):
# Base case: if b is 0, gcd is a
if b == 0:
return a
# Recursive case: call gcd with b and a % b
return gcd(b, a % b)
# Input two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
# Calculate the GCD using recursion
result = gcd(num1, num2)
# Print the result
print(f"The GCD of {num1} and {num2} is {result}")
13. A program that accepts the lengths of three sides of a triangle as
inputs. The program should output whether or not the triangle is a right
triangle (Recall from the Pythagorean Theorem that in a right triangle,
the square of one side equals the sum of the squares of the other two
sides). Implement using functions.
# Function to check if the given sides form a right triangle
def is_right_triangle(a, b, c):
# Sort the sides to ensure that c is the largest side
sides = sorted([a, b, c])
# Apply the Pythagorean Theorem
return sides[2] ** 2 == sides[0] ** 2 + sides[1] ** 2
# Input lengths of the three sides of the triangle
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
# Check if the sides form a right triangle
if is_right_triangle(side1, side2, side3):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
def is_right_triangle(a, b, c):
# Sort the sides to ensure that c is the largest side
sides = sorted([a, b, c])
# Apply the Pythagorean Theorem
return sides[2] ** 2 == sides[0] ** 2 + sides[1] ** 2
# Input lengths of the three sides of the triangle
side1 = float(input("Enter the length of the first side: "))
side2 = float(input("Enter the length of the second side: "))
side3 = float(input("Enter the length of the third side: "))
# Check if the sides form a right triangle
if is_right_triangle(side1, side2, side3):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
14. Program to define a module to find Fibonacci Numbers and import the module to another program.
fib.py # module
# Function to return the nth Fibonacci number
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
###############
import fib
# Input: Number of terms in the Fibonacci series
n= int(input("Enter the number of terms in the Fibonacci series: "))
# Print the Fibonacci series
for i in range(n):
print(fib.fibonacci(i), end=" ")
print(fib.fibonacci(i), end=" ")
15. Program to check whether the given number is a valid mobile number or not using functions.
Rules:
1. Every number should contain exactly 10 digits.
2. The first digit should be 7 or 8 or 9
# Function to check if the given number is a valid mobile number
def is_valid_mobile_number(number):
# Check if the number contains exactly 10 digits
if len(number) == 10 and number.isdigit():
# Check if the first digit is 7, 8, or 9
if number[0] in ['7', '8', '9']:
return True
return False
# Input: Mobile number as a string
mobile_number = input("Enter the mobile number: ")
# Check if the mobile number is valid
if is_valid_mobile_number(mobile_number):
print("The mobile number is valid.")
else:
print("The mobile number is not valid.")
def is_valid_mobile_number(number):
# Check if the number contains exactly 10 digits
if len(number) == 10 and number.isdigit():
# Check if the first digit is 7, 8, or 9
if number[0] in ['7', '8', '9']:
return True
return False
# Input: Mobile number as a string
mobile_number = input("Enter the mobile number: ")
# Check if the mobile number is valid
if is_valid_mobile_number(mobile_number):
print("The mobile number is valid.")
else:
print("The mobile number is not valid.")
16.
Input two lists from the user. Merge these lists into a third list such
that in the merged list, all even numbers occur first followed by odd
numbers. Both the even numbers and odd numbers should be in sorted
order.
# Input: Two lists from the user
list1 = list(map(int, input("Enter the elements of the first list separated by spaces: ").split()))
list2 = list(map(int, input("Enter the elements of the second list separated by spaces: ").split()))
# Merge the two lists
merged_list = list1 + list2
# Sort the merged list with a custom key:
# - First, sort by whether the number is even (even numbers come first)
# - Then sort by the number itself for the even and odd parts
sorted_list = sorted(merged_list, key=lambda x: (x % 2, x))
# Print the resulting list
print("Merged and sorted list with even numbers first, followed by odd numbers:")
print(sorted_list)
list1 = list(map(int, input("Enter the elements of the first list separated by spaces: ").split()))
list2 = list(map(int, input("Enter the elements of the second list separated by spaces: ").split()))
# Merge the two lists
merged_list = list1 + list2
# Sort the merged list with a custom key:
# - First, sort by whether the number is even (even numbers come first)
# - Then sort by the number itself for the even and odd parts
sorted_list = sorted(merged_list, key=lambda x: (x % 2, x))
# Print the resulting list
print("Merged and sorted list with even numbers first, followed by odd numbers:")
print(sorted_list)
17. Write a program to play a sticks game in which there are 16 sticks. Two players take turns to play the game. Each player picks one set of sticks (needn’t be adjacent) during his turn. A set contains 1, 2, or 3 sticks. The player who takes the last stick is the loser. The number of sticks in the set is to be input.
# Initial number of sticks
total_sticks = 16
# Game loop
while total_sticks > 0:
# Player 1's turn
print(f"There are {total_sticks} sticks left.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))
# Validate player 1's choice
while player1_choice < 1 or player1_choice > 3 or player1_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))
# Subtract the chosen number of sticks
total_sticks -= player1_choice
# Check if player 1 loses
if total_sticks == 0:
print("Player 1 has taken the last stick. Player 1 loses!")
break
# Player 2's turn
print(f"There are {total_sticks} sticks left.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))
# Validate player 2's choice
while player2_choice < 1 or player2_choice > 3 or player2_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))
# Subtract the chosen number of sticks
total_sticks -= player2_choice
# Check if player 2 loses
if total_sticks == 0:
print("Player 2 has taken the last stick. Player 2 loses!")
break
total_sticks = 16
# Game loop
while total_sticks > 0:
# Player 1's turn
print(f"There are {total_sticks} sticks left.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))
# Validate player 1's choice
while player1_choice < 1 or player1_choice > 3 or player1_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player1_choice = int(input("Player 1, pick 1, 2, or 3 sticks: "))
# Subtract the chosen number of sticks
total_sticks -= player1_choice
# Check if player 1 loses
if total_sticks == 0:
print("Player 1 has taken the last stick. Player 1 loses!")
break
# Player 2's turn
print(f"There are {total_sticks} sticks left.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))
# Validate player 2's choice
while player2_choice < 1 or player2_choice > 3 or player2_choice > total_sticks:
print("Invalid choice. You can only pick 1, 2, or 3 sticks.")
player2_choice = int(input("Player 2, pick 1, 2, or 3 sticks: "))
# Subtract the chosen number of sticks
total_sticks -= player2_choice
# Check if player 2 loses
if total_sticks == 0:
print("Player 2 has taken the last stick. Player 2 loses!")
break
18. Suppose you're on a game show, and you are given the choice of three
doors: Behind one door is a car; behind the others, goats. You pick a
door, say No. 1, and the host, who knows what is behind the doors, opens
another door, say No. 3, which has a goat. He then asks, "Do you want
to pick door No. 2?"Is it to your advantage to switch your choice?
import random
# Function to simulate the Monty Hall problem
def monty_hall_simulation(num_trials):
stay_wins = 0
switch_wins = 0
for _ in range(num_trials):
# Randomly place the car behind one of the three doors
doors = [0, 0, 0]
car_position = random.randint(0, 2)
doors[car_position] = 1
# Player makes an initial choice
player_choice = random.randint(0, 2)
# Host opens one of the remaining doors with a goat
remaining_doors = [i for i in range(3) if i != player_choice and doors[i] == 0]
door_opened_by_host = random.choice(remaining_doors)
# Determine the door the player can switch to
switch_choice = [i for i in range(3) if i != player_choice and i != door_opened_by_host][0]
# If the player stays with the initial choice
if doors[player_choice] == 1:
stay_wins += 1
# If the player switches to the other door
if doors[switch_choice] == 1:
switch_wins += 1
return stay_wins, switch_wins
# Number of trials to simulate
num_trials = 10000
# Simulate the Monty Hall problem
stay_wins, switch_wins = monty_hall_simulation(num_trials)
# Print the results
print(f"Out of {num_trials} trials:")
print(f"Staying with the initial choice won {stay_wins} times ({(stay_wins/num_trials)*100:.2f}%).")
print(f"Switching to the other door won {switch_wins} times ({(switch_wins/num_trials)*100:.2f}%).")
# Function to simulate the Monty Hall problem
def monty_hall_simulation(num_trials):
stay_wins = 0
switch_wins = 0
for _ in range(num_trials):
# Randomly place the car behind one of the three doors
doors = [0, 0, 0]
car_position = random.randint(0, 2)
doors[car_position] = 1
# Player makes an initial choice
player_choice = random.randint(0, 2)
# Host opens one of the remaining doors with a goat
remaining_doors = [i for i in range(3) if i != player_choice and doors[i] == 0]
door_opened_by_host = random.choice(remaining_doors)
# Determine the door the player can switch to
switch_choice = [i for i in range(3) if i != player_choice and i != door_opened_by_host][0]
# If the player stays with the initial choice
if doors[player_choice] == 1:
stay_wins += 1
# If the player switches to the other door
if doors[switch_choice] == 1:
switch_wins += 1
return stay_wins, switch_wins
# Number of trials to simulate
num_trials = 10000
# Simulate the Monty Hall problem
stay_wins, switch_wins = monty_hall_simulation(num_trials)
# Print the results
print(f"Out of {num_trials} trials:")
print(f"Staying with the initial choice won {stay_wins} times ({(stay_wins/num_trials)*100:.2f}%).")
print(f"Switching to the other door won {switch_wins} times ({(switch_wins/num_trials)*100:.2f}%).")
Comments
Post a Comment