0% found this document useful (0 votes)
2K views43 pages

ALGORITHMIC_THINKING_WITH_PYTHON_LAB_MANUAL[1] (1)

Uploaded by

lolgautham21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views43 pages

ALGORITHMIC_THINKING_WITH_PYTHON_LAB_MANUAL[1] (1)

Uploaded by

lolgautham21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

EXPERIMENTS

EXP EXPERIMENT NAME


NO
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 lists in Python using NumPy.
5 Program to find the largest of three numbers.
6 Convert temperature values back and forth between Celsius (c), and Fahrenheit (f).
[Formula: c/5 = f-32/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?
EXP
NO EXPERIMENT NAME PAGE NO

1 DESKTOP CALCULATOR USING ARITHMETIC OPERATORS 6


2 STRING OPERATIONS 8
3 FAMILIARIZING TIME AND DATE FORMATS 10
4 LIST OPERATIONS 12
5 FINDING THE LARGEST NUMBER 15
6 TEMPERATURE CONVERSION 17
7 PATTERN CONSTRUCTION 19
8 PRINTING PRIME NUMBERS 22
9 FACTORIAL OF A NUMBER USING RECURSION 24
10 RECURSIVE FUNCTION TO ADD TWO POSITIVE NUMBERS 26
11 RECURSIVE FUNCTION TO MULTIPLY TWO POSITIVE 28
NUMBERS
12 GREATEST COMMON DIVISOR OF TWO POSITIVE 30
NUMBERS
13 IMPLEMENT PYTHAGOREAN THEOREM USING FUNCTIONS 32
14 FIBONACCI SERIES 34
15 CHECK THE VALIDITY OF A MOBILE NUMBER 37
16 MERGING AND SORTING TWO LISTS WITH EVEN NUMBERS 39
FIRST AND ODD NUMBERS LAST
17 TWO-PLAYER STICK GAME: AVOID TAKING THE LAST 41
STICK!
18 MONTY HALL PROBLEM SIMULATION: STAY OR SWITCH? 44
EXPERIMENT NO: 1

DESKTOP CALCULATOR USING ARITHMETIC OPERATORS

AIM:

To write a Python program to develop simple desktop calculator(Only the five basic arithmetic
operators.)

ALGORITHM:

Step 1: Start

Step 2: Initialise a,b

Step 3: Sum=a+b

Step 4: Print Sum

Step 5: Diff=a-b

Step 6: Print Diff

Step 7: Product=a*b

Step 8: Print Product

Step 9: Division=a/b

Step 10: Print Division

Step 11: Modulus=a%b

Step 12: Print Modulus

Step 13: Stop

PROGRAM:

# Demonstrating arithmetic operations in Python

# Define numbers

a = 10

b=3

c=5

# Addition

Sum = a + b
print("Addition: a + b =", Sum)

# Subtraction

Diff = a-b

print("Subtraction: a - b =", Diff)

# Product

Product = a * b

print("Product: a * b =", Product)

# Division

Div = a / b

print("Division: a / b =", Div)

# Modulus

Modulus = a % b

print("Modulus: a % b =", Modulus)

OUTPUT:

RESULT:

The program was executed successfully and output was verified.


EXPERIMENT NO: 2

STRING OPERATIONS

AIM:

To create, concatenate, and print a string and access a sub-string from a given string.

ALGORITHM:

Step 1: Start

Step 2: Initialise str1 and str2

Step 3: Concatenate str1 and str2 and store it in concatenated_str

Step 4: Print concatenated_str

Step 5: Initialise another string full_string

Step 6: Do various slicing operations on full_string

Step 7: Print all substrings

Step 8: Stop

PROGRAM:

# Create strings

str1 = "Hello"

str2 = "World"

# Concatenate strings

concatenated_str = str1 + " " + str2

print("Concatenated String:")

print(concatenated_str) # Output: Hello World

# Accessing substrings

# Example string

full_string = "Python programming is fun"

# Accessing a substring by slicing

substring1 = full_string[0:6] # Characters from index 0 to 5

substring2 = full_string[7:18] # Characters from index 7 to 17


substring3 = full_string[-3:] # Last 3 characters

substring4 = full_string[:6] # From the start to index 5

substring5 = full_string[7:] # From index 7 to the end

substring6 = full_string[::2] # Every 2nd character

print("\nSubstrings:")

print("Substring from index 0 to 5:", substring1) # Output: Python

print("Substring from index 7 to 17:", substring2) # Output: programming

print("Last 3 characters:", substring3) # Output: fun

print("Substring from start to index 5:", substring4) # Output: Python

print("Substring from index 7 to end:", substring5) # Output: programming is fun

print("Every 2nd character:", substring6) # Output: Pto rgamn sfn

OUTPUT:

RESULT:

The program was executed successfully and output was verified.


EXPERIMENT NO: 3

FAMILIARIZING TIME AND DATE FORMATS

AIM:

To familiarize time and date in various formats.

ALGORITHM:

Step 1: Start

Step 2: Import the datetime Module

Step 3: Use the datetime.now() method to fetch the current local date and time and store it in
variable now.

Step 4: Print the result in a variable now.

Step 5: Use strftime("%Y-%m-%d %H:%M:%S") to format the current time as Year-Month-


Day Hour:Minute:Second and store this formatted string in formatted_now_1.

Step 6: Use strftime("%d/%m/%Y %I:%M %p") to format as Day/Month/Year Hour:Minute


AM/PM and store this in formatted_now_2

Step 7: Use strftime("%A, %B %d, %Y %I:%M %p") to format as Weekday, Month Day, Year
Hour:Minute AM/PM and store this in formatted_now_3

Step 8: Print formatted_now_1, formatted_now_2, formatted_now_3

Step 9: Stop

PROGRAM

from datetime import datetime


# 1. Get the Current Date and Time
now = datetime.now()
print("Current Date and Time:", now)
# 2. Format Dates and Times
# Format using various directives
formatted_now_1 = now.strftime("%Y-%m-%d %H:%M:%S")
formatted_now_2 = now.strftime("%d/%m/%Y %I:%M %p")
formatted_now_3 = now.strftime("%A, %B %d, %Y %I:%M %p")
print("\nFormatted Date and Time:")
print("Format YYYY-MM-DD HH:MM:SS:", formatted_now_1)
print("Format DD/MM/YYYY HH:MM AM/PM:", formatted_now_2)
print("Format Weekday, Month DD, YYYY HH:MM AM/PM:", formatted_now_3)

OUTPUT

RESULT:

The program was executed successfully and output was verified.


EXPERIMENT 4

LIST OPERATIONS

AIM:

To write a program to create, append, and remove lists in Python using NumPy.

ALGORITHM:

Step 1: Start.

Step 2: Import NumPy Library.

Step 3: Create a NumPy array (1D List) and name it as array1.

Step 4: Append elements into array1 and print array1.

Step 5: Append more elements into array1 and print array1.

Step 6: Remove an element from array1 using index.

Step 7: Remove multiple elements from array1 using indices.

Step 8: Create a multi-dimensional array (2D List) and name it as array2.

Step 9: Append a new row into array2 and print array2.

Step 10: Remove a row from array2 and print array2.

Step 11: Append a new Column into array2 and print array2.

Step 12: Remove a column from array2 and print array2.

Step 13: Stop.

PROGRAM:

import numpy as np

# Creating a NumPy array (1D list)

array1 = np.array([1, 2, 3, 4, 5])

print("Original Array:", array1)

# Appending elements to the array

array1 = np.append(array1, [6, 7])

print("Array after appending elements:", array1)


# Appending multiple elements to the array

array1 = np.append(array1, [8, 9, 10])

print("Array after appending more elements:", array1)

# Removing elements from the array

# NumPy doesn't have a direct remove method, but you can use np.delete()

# Remove the element at index 2 (the value 3 in this case)

array1 = np.delete(array1, 2)

print("Array after removing element at index 2:", array1)

# Removing multiple elements by specifying their indices

# Remove the elements at indices 0 and 4

array1 = np.delete(array1, [0, 4])

print("Array after removing elements at indices 0 and 4:", array1)

# Creating a multi-dimensional array (2D list)

array2 = np.array([[1, 2, 3], [4, 5, 6]])

print("\nOriginal 2D Array:\n", array2)

# Appending a new row to the 2D array

new_row = np.array([[7, 8, 9]])

array2 = np.append(array2, new_row, axis=0)

print("2D Array after appending a new row:\n", array2)

# Removing a row from the 2D array

array2 = np.delete(array2, 1, axis=0)

print("2D Array after removing row at index 1:\n", array2)

# Appending a new column to the 2D array


new_column = np.array([[10], [11]])

array2 = np.append(array2, new_column, axis=1)

print("2D Array after appending a new column:\n", array2)

# Removing a column from the 2D array

array2 = np.delete(array2, 0, axis=1) # Remove the first column

print("2D Array after removing the first column:\n", array2)

OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 5

FINDING THE LARGEST NUMBER

AIM:

To write a program to find the largest of three numbers.

ALGORITHM:

Step 1: Start.

Step 2: Define a function find_largest(a, b, c) to take three numbers.

Step 3: Inside the function find_largest(a,b,c), do steps 4-8.

Step 4: Compare the three numbers.

Step 5: If a is greater than or equal to both b and c, set largest = a.

Step 6: Else if b is greater than or equal to both a and c, set largest = b.

Step 7: Else, set largest = c.

Step 8: Return the largest number.

Step 9: Initialize three numbers (num1, num2, num3).

Step 10: Call the function find_largest(num1, num2, num3) and store the result.

Step 11: Print the largest number.

Step 12: Stop.

PROGRAM:

# Function to find the largest of three numbers using if-else

def find_largest(a, b, c):

if a >= b and a >= c:

largest = a

elif b >= a and b >= c:

largest = b

else:

largest = c
return largest

# Example usage

num1 = 10

num2 = 25

num3 = 15

largest_num = find_largest(num1, num2, num3)

print(f"The largest number is: {largest_num}")

OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 6

TEMPERATURE CONVERSION

AIM:

To write a program to convert temperature values back and forth between Celsius (c), and
Fahrenheit (f). [Formula: c/5 = f-32/9]

ALGORITHM:

Step 1: Start.

Step 2: Define a function celsius_to_fahrenheit(celsius).

Step 3: Inside the function celsius_to_fahrenheit(celsius), do steps 4-6.

Step 4: Multiply celsius by 9/5.

Step 5: Add 32 to the result and store it in fahrenheit.

Step 6: Return the fahrenheit value.

Step 7: Define a function fahrenheit_to_celsius(fahrenheit).

Step 8: Inside the function fahrenheit_to_celsius(fahrenheit), do steps 9-12.

Step 9: Subtract 32 from fahrenheit.

Step 10: Multiply the result by 5/9 and store it in celsius.

Step 11: Return the celsius value.

Step 12: Initialize two variables temp_c and temp_f.

Step 13: Call the function celsius_to_fahrenheit(temp_c) and print the result.

Step 14: Call the function fahrenheit_to_celsius(temp_f) and print the result.

Step 15: Stop

PROGRAM:

# Function to convert Celsius to Fahrenheit

def celsius_to_fahrenheit(celsius):

fahrenheit = (celsius * 9/5) + 32

return fahrenheit
# Function to convert Fahrenheit to Celsius

def fahrenheit_to_celsius(fahrenheit):

celsius = (fahrenheit - 32) * 5/9

return celsius

# Example usage

temp_c = 25 # Celsius

temp_f = 77 # Fahrenheit

# Convert Celsius to Fahrenheit

converted_f = celsius_to_fahrenheit(temp_c)

print(f"{temp_c}°C is equal to {converted_f}°F")

# Convert Fahrenheit to Celsius

converted_c = fahrenheit_to_celsius(temp_f)

print(f"{temp_f}°F is equal to {converted_c}°C")

OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 7

PATTERN CONSTRUCTION

AIM:

To write a Program to construct patterns of stars (*), using a nested for loop.

ALGORITHM:

Case 1:

Step 1: Start.
Step 2: Define a function star_pattern(rows) to construct a right-angled triangle star
pattern.
Step 3: Inside the function star_pattern(rows), do steps 4-6.
Step 4: For i in the range from 1 to rows + 1, do steps 5-6.
Step 5: For j in the range from i, print a star without a newline.
Step 6: After printing stars in a row, move to the next line.
Step 7: Initialize the variable rows with the value 5.
Step 8: Call the function star_pattern(rows).
Step 9: Stop.

Case 2:

Step 1: Start.
Step 2: Define a function inverted_star_pattern(rows) to construct an inverted triangle
star pattern.
Step 3: Inside the function inverted_star_pattern(rows), do steps 4-6.
Step 4: For i in the range from rows to 0, do steps 5-6.
Step 5: For j in the range i, print a star without a newline.
Step 6: After printing stars in a row, move to the next line.
Step 7: Initialize the variable rows with a value .
Step 8: Call the function inverted_star_pattern(rows).
Step 9: Stop.

Case 3:

Step 1: Start.
Step 2: Define a function pyramid_star_pattern(rows) to construct a pyramid star pattern.
Step 3: Inside the function pyramid_star_pattern(rows), do steps 4-6.
Step 4: For i in the range from 1 to rows + 1, do steps 5-6.
Step 5: Print spaces followed by stars.

Step 6: Initialize the variable rows with a value.


Step 7: Call the function pyramid_star_pattern(rows).
Step 8: Stop.
PROGRAM:

Case 1:

# Function to construct a right-angled triangle star pattern

def star_pattern(rows):

for i in range(1, rows + 1): # Outer loop for each row

for j in range(i): # Inner loop for stars in each row

print("*", end="") # Print stars in a single line

print() # Move to the next line after printing stars in a row

# Example usage

rows = 5

star_pattern(rows)

Case 2:

def inverted_star_pattern(rows):

for i in range(rows, 0, -1): # Outer loop for each row (descending order)

for j in range(i): # Inner loop for stars in each row

print("*", end="")

print() # Move to the next line

# Example usage

rows = 5

inverted_star_pattern(rows)

Case 3:

def pyramid_star_pattern(rows):

for i in range(1, rows + 1):


print(" " * (rows - i) + "*" * (2 * i - 1)) # Print spaces followed by stars

# Example usage

rows = 5

pyramid_star_pattern(rows)

OUTPUT:

Case 1:

Case 2:

Case 3:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 8

PRINTING PRIME NUMBERS

AIM:

To write a program that prints prime numbers less than N.

ALGORITHM:

Step 1: Start.
Step 2: Define a function is_prime(num) to check if a number is prime.
Step 3: Inside the function is_prime(num), do steps 4-7.
Step 4: Check if num is less than 2.
Step 5: If num is less than 2, return False.
Step 6: For i in the range from 2 to square root of (num + 1), do steps 7-8.
Step 7: If num is divisible by i, return False.
Step 8: Return True.
Step 9: Define a function print_primes_less_than_20() where num=20.
Step 10: Inside the function print_primes_less_than_20(), do steps 11-13.
Step 11: For num in the range from 2 to 20, do steps 12-13.
Step 12: If is_prime(num) returns True, print num.
Step 13: Call the function print_primes_less_than_20().
Step 14: Print a message indicating the prime numbers less than 20.
Step 15: Stop.

PROGRAM:

# Function to check if a number is prime

def is_prime(num):

if num < 2:

return False

for i in range(2, int(num**0.5) + 1): # Check divisibility up to the square root of the
number

if num % i == 0:

return False

return True
# Function to print prime numbers less than 20

def print_primes_less_than_20():

for num in range(2, 20):

if is_prime(num):

print(num, end=" ")

# Example usage

print("Prime numbers less than 20 are:")

print_primes_less_than_20()

OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 9

FACTORIAL OF A NUMBER USING RECURSION

AIM:

To write a Program to find the factorial of a number using Recursion.

ALGORITHM:

Step 1: Start.

Step 2: Define a function factorial(n) to find the factorial of a number.

Step 3: Inside the function factorial(n), do steps 4-6.

Step 4: If n is equal to 0 or 1, return 1 (base case).

Step 5: Else, return n * factorial(n - 1) (recursive case).

Step 6: End function.

Step 7: Initialize a number num .

Step 8: Call the function factorial(num) and store the result in result.

Step 9: Print the factorial of num.

Step 10: Stop.

PROGRAM:

# Recursive function to find the factorial of a number

def factorial(n):

if n == 0 or n == 1: # Base case: factorial of 0 or 1 is 1

return 1

else:

return n * factorial(n - 1) # Recursive case

# Example usage

num = 5

result = factorial(num)
print(f"The factorial of {num} is: {result}")

OUTPUT:

RESULT:

The program was executed successfully and the output was verified
EXPERIMENT 10

RECURSIVE FUNCTION TO ADD TWO POSITIVE NUMBERS

AIM:

To write a Program add two positive numbers using recursive function.

ALGORITHM:

Step 1: Start.

Step 2: Define a function add_recursive(a, b) to add two positive numbers.

Step 3: Inside the function add_recursive(a, b), do steps 4-6.

Step 4: If b is equal to 0, return a (base case).

Step 5: Else, return add_recursive(a + 1, b - 1) (increment a, decrement b).

Step 6: End function.

Step 7: Initialize two numbers num1 and num2.

Step 8: Call the function add_recursive(num1, num2) and store the result in result.

Step 9: Print the result.

Step 10: Stop.

PROGRAM:

# Recursive function to add two positive numbers

def add_recursive(a, b):

if b == 0: # Base case: if b is 0, return a

return a

else:

return add_recursive(a + 1, b - 1) # Increment a, decrement b

# Example usage

num1 = 5

num2 = 3
result = add_recursive(num1, num2)

print(f"The sum of {num1} and {num2} is: {result}")

OUTPUT:

RESULT:

The program was executed successfully and the output was verified
EXPERIMENT 11

RECURSIVE FUNCTION TO MULTIPLY TWO POSITIVE NUMBERS

AIM:

To write a Program multiply two positive numbers.

ALGORITHM:

Step 1: Start.

Step 2: Define a function factorial(n) to find the factorial of a number.

Step 3: Inside the function factorial(n), do steps 4-6.

Step 4: If n is equal to 0 or 1, return 1 (base case).

Step 5: Else, return n * factorial(n - 1) (recursive case).

Step 6: End function.

Step 7: Initialize a number num .

Step 8: Call the function factorial(num) and store the result in result.

Step 9: Print the factorial of num.

Step 10: Stop.

PROGRAM:

# Recursive function to multiply two positive numbers

def multiply_recursive(a, b):

if b == 0: # Base case: any number multiplied by 0 is 0

return 0

else:

return a + multiply_recursive(a, b - 1) # Add 'a' recursively 'b' times

# Example usage

num1 = 5

num2 = 3
result = multiply_recursive(num1, num2)

print(f"The product of {num1} and {num2} is: {result}")

RESULT:

The program was executed successfully and the output was verified
EXPERIMENT NO: 12

GREATEST COMMON DIVISOR OF TWO POSITIVE NUMBERS

AIM:

To find the greatest common divisor of two positive numbers using recursion

ALGORITHM:

Step 1: Start.

Step 2: Define a function gcd_recursive(a, b) to find the GCD of two positive numbers.

Step 3: Inside the function gcd_recursive(a, b), do steps 4-6.

Step 4: If b is equal to 0, return a (base case).

Step 5: Else, return gcd_recursive(b, a % b) (recursive case).

Step 6: End function.

Step 7: Initialize two numbers num1 and num2.

Step 8: Call the function gcd_recursive(num1, num2) and store the result in result.

Step 9: Print the result .

Step 10: Stop.

PROGRAM:

# Recursive function to find the GCD of two positive numbers

def gcd_recursive(a, b):

if b == 0: # Base case: GCD(a, 0) is a

return a

else:

return gcd_recursive(b, a % b) # Recursive case: GCD(b, a % b)

# Example usage

num1 = 48

num2 = 18

result = gcd_recursive(num1, num2)


print(f"The GCD of {num1} and {num2} is: {result}")

OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT 13

IMPLEMENT PYTHAGOREAN THEOREM USING FUNCTIONS

AIM:

To write 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.

ALGORITHM:

Step 1: Start.

Step 2: Define a function is_right_triangle(a, b, c) to check if a triangle is a right triangle.

Step 3: Inside the function is_right_triangle(a, b, c), do steps 4-6.

Step 4: Sort the sides [a, b, c] and store the result in sides (with the largest side last).

Step 5: Use the Pythagorean Theorem to check if sides[0]^2 + sides[1]^2 is approximately equal
to sides[2]^2.

Step 6: Return the result (True or False).

Step 7: Define a function main() to get user input and check if the sides form a right triangle.

Step 8: Inside main(), do steps 9-13.

Step 9: Use a try block to get user input for a, b, and c (the lengths of the three sides).

Step 10: Call the function is_right_triangle(a, b, c) to check if the sides form a right triangle.

Step 11: If the function returns True, print "The triangle is a right triangle."

Step 12: Else, print "The triangle is not a right triangle."

Step 13: Use an except block to catch ValueError and print "Please enter valid numbers."

Step 14: Call main() if the program is run directly.

Step 15: Stop.

PROGRAM:

import math

# Function to check if a triangle is a right triangle

def is_right_triangle(a, b, c):

# Sort the sides to ensure the largest side is last


sides = sorted([a, b, c])

# Check the Pythagorean Theorem

return math.isclose(sides[0]**2 + sides[1]**2, sides[2]**2)

# Function to get user input and check for right triangle

def main():

try:

# Accept lengths of the three sides from the user

a = float(input("Enter the length of the first side: "))

b = float(input("Enter the length of the second side: "))

c = float(input("Enter the length of the third side: "))

# Check if the sides form a right triangle

if is_right_triangle(a, b, c):

print("The triangle is a right triangle.")

else:

print("The triangle is not a right triangle.")

except ValueError:

print("Please enter valid numbers.")

# Example usage

if name == " main ":

main()

OUTPUT

RESULT:

The program was executed successfully and the output was verified
EXPERIMENT NO: 14

FIBONACCI SERIES

AIM:

To define a module to find Fibonacci Numbers and import the module to another program.

ALGORITHM:

Algorithm for fibonacci_module.py

Step 1: Start the module

Step 2: Define the Function fibonacci(n):

Step 2.1: Input: n, the length of the Fibonacci sequence.

Step 2.2: Initialize two variables, a = 0 and b = 1.

Step 2.3: Create an empty list fib_sequence to store the Fibonacci numbers.

Step 3: Generate Fibonacci Numbers:

Step 3.1: Use a loop that runs n times.

Step 3.2: In each iteration, append a to the list.

Step 3.3: Update a and b to the next numbers in the sequence using a, b = b, a + b.

Step 4: Return the Fibonacci Sequence

Step 5: End module

Import and Use the Fibonacci Module in Another Program

Algorithm for main program.py

Step 1:Start

Step 2: Import the Fibonacci Function

Step 3: Input number of Fibonacci numbers to generate

Step 4: Call the imported fibonacci(n) function and store the result (a list of Fibonacci numbers)
in fib_sequence.

Step 5: Print the Fibonacci Sequence

Step 6: Stop
PROGRAM:

# fibonacci_module.py

def fibonacci(n):

"""

Return the Fibonacci sequence up to the n-th position.

:param n: The length of the Fibonacci sequence

:return: List containing the Fibonacci sequence

"""

fib_sequence = []

a, b = 0, 1

for _ in range(n):

fib_sequence.append(a)

a, b = b, a + b

return fib_sequence

# main_program.py

# Import the fibonacci function from the fibonacci_module

from fibonacci_module import fibonacci

# Get input from the user

n = int(input("Enter the number of Fibonacci numbers to generate: "))

# Call the fibonacci function from the imported module

fib_sequence = fibonacci(n)

# Print the result

print(f"The first {n} Fibonacci numbers are: {fib_sequence}")


OUTPUT:

RESULT:

The program was executed successfully and the output was verified.
EXPERIMENT NO: 15

CHECK THE VALIDITY OF A MOBILE NUMBER

AIM:

To check whether the given number is a valid mobile number or not using functions.

ALGORITHM:

Step 1: Start

Step 2: Define a function is_valid_mobile_number(number).

Step 2.1 Check if the length of number is 10.

Step 2.2 Check if number consists of digits only.

Step 2.3 Check if the first digit is 7, 8, or 9.

Step 2.4 Return True if all conditions are met, otherwise return False.

Step 3: Input the mobile number from the user.

Step 4:Call the is_valid_mobile_number() function with the user input.

Step 5:If the function returns True:

Step 5.1 Print "The mobile number is valid."

Step 6: Else

Step 6.1: Print "The mobile number is not valid."

Step 7: Stop

PROGRAM

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.")

OUTPUT

RESULT

The program was executed successfully and output was verified.


EXPERIMENT NO: 16

MERGING AND SORTING TWO LISTS WITH EVEN NUMBERS FIRST AND ODD
NUMBERS LAST

AIM:

To 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.

ALGORITHM:

Step 1: Start

Step 2: Input Two Lists from the User , list1 and list2

Step 3: Use the concatenation operator (+) to merge list1 and list2 into a new list called
merged_list

Step 4: Sort the Merged List

Step 4.1: Use the sorted() function to sort merged_list

Step 4.2: Provide a custom sorting key using lambda x: (x % 2, x), which sorts:

Step 4.2.1: based on whether the number is even or odd (x % 2),

where even numbers have a lower value (0) and come first.

Step 4.2.2: For even and odd numbers separately, sort by the number itself.

Step 5: Print the sorted list with even numbers first, followed by odd numbers, both in
ascending order.

Step 6: Stop

PROGRAM

# 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)

OUTPUT

RESULT

The program was executed successfully and output was verified.


EXPERIMENT NO: 17

TWO-PLAYER STICK GAME: AVOID TAKING THE LAST STICK!

AIM:

To implement a simple two-player stick game where players take turns picking 1, 2, or 3 sticks.
The player forced to take the last stick loses.

ALGORITHM:

Step 1: Start

Step 2: Initialize the Total Number of Sticks

Step 3: While total_sticks > 0, continue the loop, allowing both players to take turns.

Step 4 : Player 1's Turn

Step 4.1: Display the number of sticks left (total_sticks).

Step 4.2: Ask Player 1 to input their choice (player1_choice) of how many sticks to
take (1, 2, or 3).

Step 5: Validate Player 1's Input

Step 5.1: Ensure Player 1's choice is valid by checking: The number is between 1 and 3
and does not exceed the remaining sticks.

Step 5.2: If the input is invalid, keep asking for a valid input.

Step 6: Update the Number of Sticks After Player 1's Turn

Step 6.1: Subtract player1_choice from total_sticks.

Step 7: Check if Player 1 Loses

Step 7.1: If total_sticks == 0 after Player 1’s turn, print "Player 1 has taken the last stick.
Player 1 loses!" and end the game.

Step 8: Player 2's Turn

Step 8.1: Repeat the process from Steps 4 to 7 for Player 2.

Step 9: The game ends when either Player 1 or Player 2 is forced to take the last stick, and that
player loses.

Step 10: Stop

PROGRAM:

# 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

OUTPUT:

RESULT:

The program was executed successfully and output was verified.


EXPERIMENT NO: 18

MONTY HALL PROBLEM SIMULATION: STAY OR SWITCH?

AIM:

To implement the famous Monty Hall problem, allowing players to understand the probabilities
involved in the game when choosing to stay with their initial choice or switch after a door is
opened.

ALGORITHM:

Step 1: Start

Step 2: Import the random library to generate random numbers.

Step 3: Define a function monty_hall_simulation(num_trials) that takes the number of trials as


input.

Step 4: Create two counters: stay_wins = 0 (for wins when the player stays) and switch_wins =
0 (for wins when the player switches).

Step 5: Loop for the specified number of trials:

Step 5.1: Randomly place the car.

Step 5.2: Player chooses a door.

Step 5.3: Host opens a door with a goat.

Step 5.4: Determine the switching door.

Step 6: Check win conditions.

Step 6.1: f the player's initial choice has the car, increment stay_wins.

Step 6.2: If the switching door has the car, increment switch_wins.

Step 7: Return the counts.

Step 8: Set the number of trials (e.g., num_trials = 10000) and Call the function and capture the
results.

Step 9: Print the results.

Step 10: Stop

PROGRAM:

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}%).")

OUTPUT:

RESULT:

The program was executed successfully and output was verified.

You might also like