0% found this document useful (0 votes)
11 views

Python Lab Experiments With Algm_n_code

Uploaded by

anndriyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Lab Experiments With Algm_n_code

Uploaded by

anndriyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

1.

Program to find the largest of three numbers


Algorithm :
1. Input: Read three numbers num1, num2, and num3.
2. Initialize:
o Set largest = num1.
3. Compare with the second number:
o If num2 > largest, then update largest = num2.
4. Compare with the third number:
o If num3 > largest, then update largest = num3.
5. Output:
o Print largest as the largest number.
Program
# Program to find the largest of three numbers
# Input: Three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Initialize largest to the first number


largest = num1

# Compare with the second number


if num2 > largest:
largest = num2

# Compare with the third number


if num3 > largest:
largest = num3

# Output the largest number


print(f"The largest number is: {largest}")
OUTPUT
Enter the first number: 123
Enter the second number: 412
Enter the third number: 110
The largest number is: 412.0
2. Program to find the sum, difference, and average of two numbers
Algorithm: Find the Sum, Difference, and Average of Two Numbers
1. Input: Read two numbers, num1 and num2.
2. Calculate Sum:
o Compute sum_result = num1 + num2.
3. Calculate Difference:
o Compute difference = num1 - num2.
4. Calculate Average:
o Compute average = sum_result / 2.
5. Output:
o Print the values of sum_result, difference, and average
o

# Program to find the sum, difference, and average of two numbers


# Input: Two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Calculate sum
sum_result = num1 + num2

# Calculate difference
difference = num1 - num2

# Calculate average
average = sum_result / 2

# Output the results


print(f"Sum of {num1} and {num2} is: {sum_result}")
print(f"Difference between {num1} and {num2} is: {difference}")
print(f"Average of {num1} and {num2} is: {average}")
OUTPUT:
Enter the first number: 14
Enter the second number: 12
Sum of 14.0 and 12.0 is: 26.0
Difference between 14.0 and 12.0 is: 2.0
Average of 14.0 and 12.0 is: 13.0
3. Program to convert Celsius to Fahrenheit
Algorithm: Convert Celsius to Fahrenheit
1. Input: Read the temperature in Celsius (celsius).
2. Apply the Formula:
o Calculate Fahrenheit (fahrenheit) using the formula:
fahrenheit=(celsius×95)+32fahrenheit = \left( \frac{celsius \times 9}{5}
\right) + 32fahrenheit=(5celsius×9)+32
3. Output:
o Print the temperature in Fahrenheit (fahrenheit).
#Program to convert Celsius to Fahrenheit
# Input: Temperature in Celsius
celsius = float(input("Enter the temperature in Celsius: "))
# Convert Celsius to Fahrenheit using the formula
fahrenheit = (celsius * 9 / 5) + 32
# Output the temperature in Fahrenheit
print(f"The temperature in Fahrenheit is: {fahrenheit}")
OUTPUT:
Enter the temperature in Celsius: 100
The temperature in Fahrenheit is: 212.0
4. Program to check if a year is a leap year
Algorithm to Check Leap Year:
1. Input: Read the year (year).
2. Check Conditions:
o If the year is divisible by 4:
▪ Check if it is not divisible by 100 or divisible by 400:
▪ If true, it is a leap year.
▪ Otherwise, it is not a leap year.
3. Output:
o Print whether the year is a leap year or not.
#Program to check if a year is a leap year
# Input: Year
year = int(input("Enter a year: "))

# Check if the year is a leap year


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
OUTPUT:
Enter a year: 2000
2000 is a leap year.
5. Write a program to find the roots of a Quadratic equation and print the roots.
Algorithm: Find Roots of a Quadratic Equation Considering All Cases
1. Input:
o Read the coefficients a, b, and c of the quadratic equation ax2+bx+c=0ax^2 +
bx + c = 0ax2+bx+c=0.
2. Calculate the Discriminant:
o Compute D=b2−4acD = b^2 - 4acD=b2−4ac.
3. Check the Value of the Discriminant:
o Case 1 (D>0D > 0D>0):
▪ The equation has two real and distinct roots.
▪ Compute: x1=−b+D2a,x2=−b−D2ax_1 = \frac{-b + \sqrt{D}}{2a},
\quad x_2 = \frac{-b - \sqrt{D}}{2a}x1=2a−b+D,x2=2a−b−D
o Case 2 (D=0D = 0D=0):
▪ The equation has two real and equal roots.
▪ Compute: x=−b2ax = \frac{-b}{2a}x=2a−b
o Case 3 (D<0D < 0D<0):
▪ The equation has two complex roots.
▪ Compute: x1=−b+D2a,x2=−b−D2ax_1 = \frac{-b + \sqrt{D}}{2a},
\quad x_2 = \frac{-b - \sqrt{D}}{2a}x1=2a−b+D,x2=2a−b−D
▪ Use the complex square root for D\sqrt{D}D.
4. Output:
o If D>0D > 0D>0, print two real and distinct roots x1x_1x1 and x2x_2x2.
o If D=0D = 0D=0, print two real and equal roots x,xx, xx,x.
o If D<0D < 0D<0, print two complex roots x1x_1x1 and x2x_2x2.
#program to find the roots of a Quadratic equation and print the roots.
import cmath # For handling complex roots
# Input coefficients of the quadratic equation
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

# Calculate the discriminant


discriminant = (b**2) - (4 * a * c)

# Check cases based on the value of discriminant


if discriminant > 0:
# Two real and distinct roots
root1 = (-b + discriminant**0.5) / (2 * a)
root2 = (-b - discriminant**0.5) / (2 * a)
print(f"The equation has two real and distinct roots: {root1} and {root2}")
elif discriminant == 0:
# Two real and equal roots
root = -b / (2 * a)
print(f"The equation has two real and equal roots: {root} and {root}")
else:
# Two complex roots
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
print(f"The equation has two complex roots: {root1} and {root2}")
OUTPUT:
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 3
The equation has two complex roots: (-1+1.4142135623730951j) and (-1-
1.4142135623730951j)

6. Write a program in Python to swap two numbers using third variable and find the
area of a triangle with these swapped values

Algorithm : swap two numbers using third variable and find the area of a triangle with
these swapped values
1. Input the two numbers, num1 and num2.
2. Swap the numbers:
o Use a third variable, temp, to hold the value of num1.
o Assign the value of num2 to num1.
o Assign the value of temp to num2.
3. Calculate the area of the triangle:
o Treat the swapped num1 as the base and num2 as the height.
o Use the formula for the area of a triangle: Area=12×base×height\text{Area} =
\frac{1}{2} \times \text{base} \times \text{height}Area=21×base×height
4. Output the swapped values and the area.
Program in Python to swap two numbers using third variable and find the area of a
triangle with these swapped values

import math
# Input two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Swap using a third variable


temp = num1
num1 = num2
num2 = temp

print(f"After swapping: First number = {num1}, Second number = {num2}")

# Calculate the semi-perimeter-based area


a = num1
b = num2
c = float(input("Enter the third side of the triangle: ")) # Input the third side

# Calculate the semi-perimeter


s = (a + b + c) / 2

# Calculate the area using Heron's formula


area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print(f"The area of the triangle with sides {a}, {b}, and {c} is: {area}")

OUTPUT
Enter the first number: 12
Enter the second number: 11
After swapping: First number = 11.0, Second number = 12.0
Enter the third side of the triangle: 13
The area of the triangle with sides 11.0, 12.0, and 13.0 is: 61.48170459575759

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


7.1 right-angled triangle pattern of stars:

Algorithm
1. Input the number of rows for the pattern from the user.
2. Use an outer loop to iterate through each row:
o The loop variable represents the current row.
3. Use an inner loop to control the number of stars (*) printed in each row:
o The number of stars printed equals the row number in most patterns.
4. Print the stars in each row and move to the next line.
5. Stop once all rows are printed.

Program1: # Input number of rows


rows = int(input("Enter the number of rows: "))

# Generate the pattern


for i in range(1, rows + 1): # Outer loop for rows
for j in range(i): # Inner loop for stars in each row
print("*", end="") # Print star without newline
print() # Move to the next line after each row
OUTPUT:
Enter the number of rows: 5
*
**
***
****
*****
Pattern 2: Inverted Triangle
for i in range(rows, 0, -1): # Start from the largest row
for j in range(i):
print("*", end="")
print()
OUTPUT
*****
****
***
**
*
Pattern 3: Pyramid
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
Output:
*
***
*****
*******
*********

Pattern 3: Diamond
# Upper part
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
# Lower part
for i in range(rows - 1, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))
*
***
*****
*******
*********
*******
*****
***
*
8. Write a program in Python to print the Fibonacci series up to a given limit N
Algorithm to Print Fibonacci Series up to a Given Limit (N)
1. Start.
2. Input the limit NNN from the user.
3. Initialize two variables:
o a=0(first Fibonacci number).
o b=1 (second Fibonacci number).
4. Print aaa, the first number in the Fibonacci series.
5. While aaa is less than or equal to NNN:
6. Print 𝑎
7. Calculate the next Fibonacci number
8. temp = b (store the value of b).
9. b=a+b (update b to the next Fibonacci number)
10. a=temp (update a to the value of the old b).
11. Stop the loop when a>N.
12. End.

Program
# Input the limit
n = int(input("Enter the limit (N): "))
# Initialize the first two numbers of the Fibonacci series
a, b = 0, 1
# Print the Fibonacci series up to N
print("Fibonacci series up to", n, ":")
while a <= n:
print(a, end=" ")
a, b = b, a + b # Update to the next numbers in the series
OUTPUT
Enter the limit (N): 8
Fibonacci series up to 8 :
0 112358

9. Write a program to check whether a number is palindrome or not.

Algorithm to Check Whether a Number is a Palindrome

1. Start.

2. Input a number from the user and store it in a variable, num.

3. Initialize reverse = 0 and original = num to store the reverse of the number and preserve
the original value for comparison.

4. While num > 0:

o Extract the last digit using digit = num % 10.

o Update reverse = reverse * 10 + digit to build the reversed number.

o Remove the last digit from num using num = num // 10.

5. Compare reverse with original:

o If reverse == original, the number is a palindrome.

o Otherwise, it is not a palindrome.

6. Output the result.

7. End.
Program to check whether a number is palindrome or not.

# Input a number

num = int(input("Enter a number: "))

# Initialize variables

original = num

reverse = 0

# Reverse the number

while num > 0:

digit = num % 10 # Extract the last digit

reverse = reverse * 10 + digit # Build the reversed number

num = num // 10 # Remove the last digit

# Check if the original number is equal to the reversed number

if original == reverse:

print(f"{original} is a palindrome.")

else:

print(f"{original} is not a palindrome.")

OUTPUT:
Enter a number: 121
121 is a palindrome.
Enter a number: 123
123 is not a palindrome.
10. Program to convert a decimal number to binary and an octal number.

Algorithm to Convert Decimal to Binary and Octal


Steps for Decimal to Binary
1. Start.
2. Input a decimal number n from the user.
3. Initialize an empty string binary to store the binary representation.
4. While n > 0:
o Compute the remainder of n divided by 2: remainder = n % 2.
o Add the remainder to the beginning of the binary string: binary =
str(remainder) + binary.
o Update n to n // 2 (integer division by 2).
5. If the binary string is still empty (case when n=0), set binary = "0".
6. Return the binary string as the binary representation of the decimal number.
Steps for Decimal to Octal
1. Repeat steps 1 to 5, but instead of 2 (base for binary), use 8 (base for octal).
o Compute the remainder of n divided by 8.
o Add the remainder to the beginning of the octal string.
o Update n to n // 8.
2. If the octal string is still empty, set octal = "0".
3. Return the octal string as the octal representation of the decimal number.
End.
Program to Convert Decimal to Binary and Octal
# Convert decimal to binary
def decimal_to_binary(n):
binary = ""
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n = n // 2
return binary if binary else "0" # Handle case when n = 0
# Convert decimal to octal
def decimal_to_octal(n):
octal = ""
while n > 0:
remainder = n % 8
octal = str(remainder) + octal
n = n // 8
return octal if octal else "0" # Handle case when n = 0

# Input a decimal number


decimal_number = int(input("Enter a decimal number: "))

# Perform conversions
binary_representation = decimal_to_binary(decimal_number)
octal_representation = decimal_to_octal(decimal_number)

# Display results
print(f"Binary representation: {binary_representation}")
print(f"Octal representation: {octal_representation}")

# Function to convert decimal to binary


def decimal_to_binary(n):
binary = ""
while n > 0:
remainder = n % 2
binary = str(remainder) + binary
n = n // 2
return binary if binary else "0" # Handle case when n = 0
# Function to convert decimal to octal
def decimal_to_octal(n):
octal = ""
while n > 0:
remainder = n % 8
octal = str(remainder) + octal
n = n // 8
return octal if octal else "0" # Handle case when n = 0

# Input a decimal number from the user


decimal_number = int(input("Enter a decimal number: "))

# Perform conversions
binary_representation = decimal_to_binary(decimal_number)
octal_representation = decimal_to_octal(decimal_number)

# Display results
print(f"Binary representation: {binary_representation}")
print(f"Octal representation: {octal_representation}")

OUTPUT
Enter a decimal number: 45
Binary representation: 101101
Octal representation: 55
LAB CYCLE 2

11. A program that prints prime numbers less than N with algorithm and program
in python
Algorithm
1. Initialize Variables:
• Create an empty list lst to store prime numbers.
• Initialize a flag variable to 0.
2. Iterate Over the Range:
• Loop through each number iii from starting_range to ending_range - 1.
3. Check for Primality:
• Skip numbers less than 2 as they are not prime.
• For each number iii, iterate through potential divisors jjj from 2 to i−1i -
1i−1.
• If i%j==0:
Set flag = 1 and break the inner loop (indicating iii is not prime).
• Otherwise, ensure flag = 0.
4. Append to Prime List:
• After exiting the inner loop, if flag == 0, append iii to lst.
5. Print the Result:
• After the outer loop completes, print the list lst containing all prime numbers
Program
# Input range
N=int(input(“Enter the range”))
# Initialize list for prime numbers
lst = [ ]
# Iterate through the range
for i in range(N):
if i < 2: # Skip numbers less than 2
continue
flag = 0 # Reset flag for each number
for j in range(2, i): # Check divisors from 2 to (i-1)
if i % j == 0: # If divisible, not a prime number
flag = 1
break
if flag == 0: # If flag remains 0, it's a prime number
lst.append(i)

# Print the prime numbers


print(f"Prime numbers < N : {lst}")
OUTPUT
Enter a number N: 12
2 3 5 7 11

12. Program to find the factorial of a number using Recursion.

Algorithm

To find the factorial of a number nnn using recursion:

1. BaseCase:
If n=0 or n=1, return 1. This is because 0!=1!=1.

2. RecursiveCase:
For n>1, the factorial of n can be defined as:

n!=n×(n−1)!

This involves calling the function recursively with n−1

3. Termination:
The recursion ends when the base case is reached.

Program

def factorial(n):

# Base case
if n == 0 or n == 1:

return 1

# Recursive case

else:

return n * factorial(n - 1)

# Input from user

num = int(input("Enter a number: "))

# Ensure input is non-negative

if num < 0:

print("Factorial is not defined for negative numbers.")

else:

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

13. Program to create a menu driven desktop calculator using Python. Only the five
basic arithmetic operators.

Algorithm

To create a menu-driven desktop calculator in Python that supports five basic arithmetic
operators:

1. Display Menu:
1.1 Show options for addition, subtraction, multiplication, division, and
modulus.
1.2 Include an option to exit the program.
2. User Input:
2.1 Prompt the user to select an operation by entering a number corresponding
to the menu option.
3. Perform Calculation:
3.1 Based on the user's choice, prompt for two numbers.
3.2 Perform the selected operation and display the result.
4. Loop:
4.1 Keep displaying the menu until the user chooses to exit.
5. Exit:
5.1 Terminate the program when the user selects the exit option.

Program

while True:

print("\n--- Menu Driven Calculator ---")

print("1. Addition (+)")

print("2. Subtraction (-)")

print("3. Multiplication (*)")

print("4. Division (/)")

print("5. Modulus (%)")

print("6. Exit")

# Prompt user for choice

choice = int(input("Enter your choice (1-6): "))

if choice == 6:

print("Exiting the calculator.")

break

elif 1 <= choice <= 5:

# Prompt user for two numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Perform selected operation


if choice == 1:

print(f"Result: {num1} + {num2} = {num1 + num2}")

elif choice == 2:

print(f"Result: {num1} - {num2} = {num1 - num2}")

elif choice == 3:

print(f"Result: {num1} * {num2} = {num1 * num2}")

elif choice == 4:

if num2 != 0:

print(f"Result: {num1} / {num2} = {num1 / num2}")

else:

print("Error: Division by zero is not allowed.")

elif choice == 5:

if num2 != 0:

print(f"Result: {num1} % {num2} = {num1 % num2}")

else:

print("Error: Division by zero is not allowed.")

else:

print("Invalid choice. Please enter a number between 1 and 6.")

OUTPUT:

--- Menu Driven Calculator ---


1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
6. Exit
Enter your choice (1-6): 1
Enter the first number: 10
Enter the second number: 5
Result: 10 + 5 = 15
--- Menu Driven Calculator ---
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
5. Modulus (%)
6. Exit
Enter your choice (1-6): 6
Exiting the calculator.
14. Create, concatenate, and print a string and access a sub-string from a given string.

Algorithm

1. Create a String:

o Initialize a string with some value.

2. Concatenate Strings:

o Create another string and concatenate it with the first string using the + operator.

3. Print the Concatenated String:

o Output the concatenated string.

4. Access a Substring:

o Use slicing (string[start:end]) to extract a portion of the string. Specify the


starting and ending indices.

Program:
OUTPUT

15. Familiarize time and date in various formats (Eg. “Thu Jul 11 10:26:23 IST
2024”).

Algorithm

1. Import the datetime Module:

o Use Python's built-in datetime module to handle date and time operations.

2. Get the Current Date and Time:

o Use datetime.now() to retrieve the current date and time.

3. Format the Date and Time:

o Use the strftime() method to format the date and time in different styles.
o Specify format codes to control the output format (e.g., %A for weekday, %B
for month name).

4. Print the Date and Time:

o Display the date and time in various formats.

Program

from datetime import datetime

# Step 1: Get the current date and time

current_datetime = datetime.now()

# Step 2: Format the date and time in different styles

format1 = current_datetime.strftime("%a %b %d %H:%M:%S %Z %Y") # Thu Jul 11


10:26:23 IST 2024

format2 = current_datetime.strftime("%Y-%m-%d %H:%M:%S") # 2024-07-11


10:26:23

format3 = current_datetime.strftime("%d/%m/%Y, %I:%M:%S %p") # 11/07/2024,


10:26:23 AM

format4 = current_datetime.strftime("%A, %B %d, %Y") # Thursday, July 11, 2024

# Step 3: Print the formatted date and time

print("Format 1:", format1)

print("Format 2:", format2)

print("Format 3:", format3)

print("Format 4:", format4)

OUTPUT:

Format 1: Sun Dec 01 14:13:33 2024

Format 2: 2024-12-01 14:13:33

Format 3: 01/12/2024, 02:13:33 PM


Format 4: Sunday, December 01, 2024

16. Recursive function to add two positive numbers

Algorithm

To add two positive numbers a and b using a recursive function:

1. Base Case:

o If b is 0, the addition is complete, and a is returned.

2. Recursive Case:

o Add 1 to a and decrement b by 1.

o Call the function recursively with updated values of a and b.

3. Termination:

o The recursion ends when b=0.

Program

Output
17. Recursive function to multiply two positive numbers.

Algorithm

To multiply two positive numbers a and b using recursion:

1. Input two positive no.s a and b.


2. If b=0, the result is 0, as anything multiplied by 0 is 0.
3. Use the property: a×b=a+(a×(b−1)).
4. Add a to the result of multiplying a with b−1.

5. The recursion stops when b becomes 0.

Program
18. Recursive function to find the greatest common divisor of two positive numbers.

Algorithm

To find the greatest common divisor (GCD) of two positive numbers aaa and bbb using
recursion:

1. If b=0, the GCD is a. This is based on the property that GCD(a,0) = a.

2. Use the Euclidean algorithm, which states: GCD(a, b)=GCD(b, a mod b).

3. Call the function recursively with b and a mod b.

4. The recursion stops when b=0.

Program
19. 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]

Algorithm

1. Input and Accept the mobile number as a string to handle cases like leading zeros or
non-numeric characters.

2. Check Length: Verify that the length of the number is exactly 10 digits.

3. Check First Digit: Ensure the first digit is either 7, 8, or 9.

4. Check for Digits Only: Ensure the number consists only of digits.

5.1 If all conditions are met, print that the number is valid.
5.2 Otherwise, indicate that it is invalid.

Program:

OUTPUT
CYCLE 3

20. 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
1. Input three numbers representing the sides of a triangle.
2. Sort the three sides in ascending order so the largest side is treated as the hypotenuse.
3. Check Pythagorean Theorem: c2=a2+b2 (where c is the largest side).
o If the condition holds, it's a right triangle; otherwise, it's not.
4. Print whether the triangle is a right triangle or not.

Program

OUTPUT:
21. Write a program to create, append, and remove lists in Python using NumPy.
Algorithm
1. Initialize NumPy: Import the numpy library.
2. Create a List: Use numpy.array() to create a NumPy array.
3. Append Elements: Use numpy.append() to add elements to the array.
4. Remove Elements: Use slicing or other NumPy operations to remove elements (as
numpy arrays do not have a direct method like remove() in Python lists).
5. Output the Results: Display the list after each operation
Program

Output
22. 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
Algorithm
1. Input Two Lists of numbers.
2. Merge the Lists: two lists into a single list.
3. Iterate through the merged list, separating even and odd numbers into two separate lists.
4. Sort the even numbers list and the odd numbers list.
5. Merge Sorted Lists: - Combine the sorted even numbers list followed by the sorted odd
numbers list.
6. Display the merged and sorted list.

Program:

# Step 1: Input two lists from the user

print("Enter the elements of the first list, separated by spaces:")

list1 = list(map(int, input().split()))

print("Enter the elements of the second list, separated by spaces:")

list2 = list(map(int, input().split()))

# Step 2: Merge the lists

merged_list = list1 + list2

print("\nMerged List:", merged_list)


# Step 3: Separate even and odd numbers

even_numbers = [num for num in merged_list if num % 2 == 0]

odd_numbers = [num for num in merged_list if num % 2 != 0]

# Step 4: Sort the even and odd numbers

even_numbers.sort()

odd_numbers.sort()

# Step 5: Merge the sorted lists

result = even_numbers + odd_numbers

# Step 6: Output the final list

print("\nFinal List with evens first (sorted) and odds next (sorted):")

print(result)

Output

23. Program to define a module to find Fibonacci Numbers and import the module to
another program
Algorithm
1. Define a Module:
o Create a Python file (e.g., fibonacci_module.py) with functions to generate
Fibonacci numbers.
2. Implement Functionality:
o Implement a function to generate Fibonacci numbers up to a certain number or
count.
Main Program:
3. Import the Module:
o Import the custom module into another program.
4. Call the Function:
o Use the functions from the module to calculate Fibonacci numbers and display
the results.

Program

# Define a module for Fibonacci sequence functions

def fibonacci_by_count(count):

"""Generate Fibonacci sequence up to a given count."""

sequence = []

a, b = 0, 1

for _ in range(count):

sequence.append(a)

a, b = b, a + b

return sequence

def fibonacci_up_to(max_value):

"""Generate Fibonacci sequence up to a maximum value."""

sequence = []

a, b = 0, 1

while a <= max_value:

sequence.append(a)
a, b = b, a + b

return sequence

# Import the custom Fibonacci module

import fibonacci_module

# Input: Choose mode and enter values

print("Choose mode:")

print("1. Generate Fibonacci numbers by count")

print("2. Generate Fibonacci numbers up to a maximum value")

choice = int(input("Enter choice (1/2): "))

if choice == 1:

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

result = fibonacci_module.fibonacci_by_count(n)

print(f"First {n} Fibonacci numbers:", result)

elif choice == 2:

max_value = int(input("Enter the maximum value for Fibonacci numbers: "))

result = fibonacci_module.fibonacci_up_to(max_value)

print(f"Fibonacci numbers up to {max_value}:", result)

else:

print("Invalid choice!")

You might also like