0% found this document useful (0 votes)
20 views23 pages

Ashab Ali Khan

The document contains the practical file of a student named Ashab Ali Khan for a programming and problem solving course. It includes 10 programming problems and their solutions. For each problem, it provides the problem statement, Python code, output and an explanation.

Uploaded by

s4m33r.tempo
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)
20 views23 pages

Ashab Ali Khan

The document contains the practical file of a student named Ashab Ali Khan for a programming and problem solving course. It includes 10 programming problems and their solutions. For each problem, it provides the problem statement, Python code, output and an explanation.

Uploaded by

s4m33r.tempo
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/ 23

NAME:- Ashab Ali Khan 23SCSE2030407

(Department of Computer Science & Engineering)

Session- 2023-24
Program- MCA

Practical File Of
(Programming and Problem Solving)

Submitted By Submitted To
Name- Ashab Ali Khan Prof. Kalyani Singh ma’am
Sec on- 04
Roll No. 23SCSE2030407
Date - /01/2024 SIGNATURE
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT NO :1

PROBLEM STATEMENT:- 1
Write the pseudo-code and draw a flow chart to calculate the sum and
product of two numbers and display it.
Pseudo-code

BEGIN
NUMBER s1, s2, sum
OUTPUT("Input number1:")
INPUT s1
OUTPUT("Input number2:")
INPUT s2
sum=s1+s2
OUTPUT sum
END

Flowchart

FOR DISPLAYING THE ADDITION FOR DISPLAYING THE Mul plica on

1
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT : 2

PROBLEM STATEMENT :-
Write a Python program to calculate simple interest based on user input for principal
amount, rate, and me. Provide a clear explanation on of the formula and calculations.

Explanation-
Simple interest formula is given by: Simple Interest = (P x
T x R)/100 Where, P is the principal amount T is the me and R is the rate

Program

OUTPUT

2
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIME NT NO : 3

Program Statement :-
Write a program that checks if a given number is even or odd. Provide an
explanation on of the concept of even and odd numbers. Take input from the
user.

Program

Output

Explanation

We use the input function on to get a number as a string from the user.
The int function on is then used to convert the user input to an integer.
We use the modulo operator (%) to check if the number is divisible by 2. If the remainder is 0,
the number is even; otherwise, it's odd.
Finally, the program prints the result based on whether the number is even or odd

3
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERTIMENT : 4

Problem Statement :
Write a program that checks if a given year is a leap year. Provide
an explanation on of the rules for determining leap years.

Program

Output

Explanation
We use the input function on to get a year as an integer from the user.

We check the conditions for a leap year using the rules mentioned above.

If the year satisfies the conditions, it is considered a leap year, and the
program prints the result; otherwise, it prints that the year is not a leap year.

4
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT : 5

Problem Statement:
Write a program to print the given pattern.

PROGRAM

Output

5
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT : 6

PROBLEM STATEMENT :-
Write a program to check whether an alphabet entered by the user is a vowel or a constant.

Program

Output

6
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT : 7

PROGRAM STATEMENT :-
Write a program to find all the prime numbers in a given range from the user.

PROGRAM

Output

7
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT :8

PROBLEM STATEMENT :- Create a list of your favourite fruits. Display the list of fruits.
Add a new fruit to the list an display the updated list. Remove one fruit from the list and display
the updated list. Also, write a program that searches for a specific element in a list and returns its
index. Explain the search algorithm used in the program.

PROGRAM

favorite_fruits = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']

# Display the initial list of fruits


print("Initial List of Favorite Fruits:", favorite_fruits)

new_fruit = 'Strawberry'
favorite_fruits.append(new_fruit)

print("Updated List after Adding", new_fruit + ":", favorite_fruits)

# Remove one fruit from the list


fruit_to_remove = 'Banana'
favorite_fruits.remove(fruit_to_remove)

# Display the updated list after removing a fruit


print("Updated List after Removing", fruit_to_remove + ":", favorite_fruits)

def search_element_index(lst, element):


"""Search for an element in a list and return its index."""
for index, item in enumerate(lst):
if item == element:
return index
return -1 # Return -1 if the element is not found

search_element = 'Grapes'
index = search_element_index(favorite_fruits, search_element)

# Display the result of the search if


index != -1:
print(f"{search_element} found at index {index}.") else:

print(f"{search_element} not found in the list.")


Output

8
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT 9

PROBLEM STATEMENT: Write a program using Sets, Dictionaries (Maximum and


Minimum in a Set, Count number of vowels using sets in given string, Dictionary with
keys having multiple inputs, find the sum of all items in a dictionary).

PROGRAM

def find_max_min_in_set(input_set):
if not input_set:
return None, None
return max(input_set), min(input_set)

def count_vowels_in_string(input_string):
vowels = set("AEIOU")
count = 0
for char in input_string:
if char in vowels:
count += 1
return count

def create_dictionary(keys, values):


if len(keys) != len(values):
raise ValueError("Keys and values must have the same length.")
return dict(zip(keys, values))

def sum_all_items_in_dictionary(input_dict):
return sum(input_dict.values())

# Example usage
if __name__ == "__main__":
# Sets
num_set = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5} max_num,
min_num = find_max_min_in_set(num_set)
print(f"Maximum in set: {max_num}, Minimum in set: {min_num}")

# Count vowels in a string


input_str = "Hello, World!"
vowel_count = count_vowels_in_string(input_str)
print(f"Number of vowels in '{input_str}': {vowel_count}")

# Dictionary with multiple inputs


keys = ['name', 'age', 'city']
values = ['John', 25, 'New York']
personal_info = create_dictionary(keys, values)

9
NAME:- Ashab Ali Khan 23SCSE2030407

print("Personal Information Dictionary:", personal_info)

# Sum of all items in a dictionary


expenses = {'food': 200, 'rent': 1000, 'utilities': 150, 'entertainment':
50}
total_expenses = sum_all_items_in_dictionary(expenses)
print("Total Expenses:", total_expenses)

OUTPUT

10
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 10

Write a function on that calculates the factorial of a given integer using recursion. Explain
the recursive approach and its limitations.

PROGRAM

def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

# Example usage result


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

OUTPUT

Explanation of the recursive approach:

1. Base case: The base case is the simplest scenario where the function does not make a
recursive call. In this case, if n is 0 or 1, the factorial is 1.

2. Recursive case: The function makes a call to itself with a smaller version of the problem. In this
case, the factorial of n is calculated by multiplying n with the factorial of n - 1.

3. Termination: The recursion terminates when the base case is reached. As n gets smaller
with each recursive call, eventually it will reach 0 or 1, and the recursion stops.

Limitations of recursive approach:

1. Stack Overflow: Recursive solutions may lead to a stack overflow for large values of n. Each recursive call

adds a new frame to the call stack, and if the recursion is too deep, it may exhaust the stack space.

2. Performance: Recursive solutions may not be as efficient as iterative solutions for certain
problems. Each recursive call incurs the overhead of creating a new function call frame, which
can be less efficient in terms of memory usage and execution time.

3. Readability and Debugging: Recursive solutions, while elegant, may be harder to read and
debug for some people. Understanding the flow of recursion and keeping track of multiple
function calls can be challenging.

11
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 11

PROBLEM STATEMENT: Create a text file named "sample.txt" and write a few lines of text to
it. Write a Python program to open the file, read its contents, and display them.

PROGRAM

# Create and write to the file


with open("sample.txt", "w") as file:
file.write("Hello, this is a sample text file.\n")
file.write("It contains multiple lines of text.\n")
file.write("This is the third line.")

# Open and read the file


with open("sample.txt", "r") as file:
contents = file.read()

# Display the contents


print("Contents of 'sample.txt':")
print(contents)

OUTPUT

12
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 12

PROBLEM STATEMENT: Write a program to create a lambda


func on to find square of a given number.
PROGRAM

# Define a lambda function to find the square of a number


square = lambda x: x ** 2

# Example usage
number = 5
result = square(number)
print(f "The square of {number} is: {result}")

OUTPUT

13
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 13

PROBLEM STATEMENT : You are given a CSV file named


"sales_data.csv" containing sales data for a store. Load the data into a Pandas
DataFrame and answer the following ques ons:
a. (a) Display the first 5 rows of the dataset to inspect its structure.
b. (b) Calculate the total revenue generated from all sales.
c. (c) Determine the number of unique products sold.
d. (d) Find the maximum and minimum sale prices.

PROGRAM
import pandas as pd

# Load the data into a Pandas DataFrame df


= pd.read_csv("sales_data.csv")

# (a) Display the first 5 rows of the dataset


print("(a) Display the first 5 rows of the dataset:")
print(df.head())

# (b) Calculate the total revenue generated from all sales


total_revenue = df['Sale Price'].sum()
print("\n(b) Total revenue generated from all sales:", total_revenue)

# (c) Determine the number of unique products sold

unique_products = df['Product'].nunique()
print("\n(c) Number of unique products sold:", unique_products)

# (d) Find the maximum and minimum sale prices


max_sale_price = df['Sale Price'].max()
min_sale_price = df['Sale Price'].min()

print("\n(d) Maximum sale price:", max_sale_price)

print("(d) Minimum sale price:", min_sale_price)

Note- This code assumes that the CSV file has columns named "Sale Price" and "Product" for the
sale prices and products, respec vely. Adjust the column names accordingly
based on your actual dataset.

14
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 14

PROBLEM STATEMEMT-
Create a NumPy array that takes the value
between o and 1. Also, create the numpy array uning arange func on.

PROGRAM
import numpy as np

# Create a NumPy array with values between 0 and 1 using arrange

array_arange = np.arange(0, 1.1, 0.1) # The third argument is the step size

print("NumPy array using arange:", array_arange)

OUTPUT

15
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 15

PROBLEM STATEMENT: Given a NumPy array containing


student exam scores, perform the following opera ons:
i. Calculate the mean, median, and standard devia on of the exam scores.
ii. Find the indices of the top 5 scores.

PROGRAM

import numpy as np

# Assuming you have a NumPy array of exam scores


exam_scores = np.array([85, 90, 78, 92, 88, 94, 76, 98, 87, 89])

# i. Calculate the mean, median, and standard deviation of the exam scores

mean_score = np.mean(exam_scores)
median_score = np.median(exam_scores)
std_deviation = np.std(exam_scores)

print("i. Calculated statistics:")


print("Mean:", mean_score)
print("Median:", median_score)
print("Standard Deviation:", std_deviation)

# ii. Find the indices of the top 5 scores


top_5_indices = np.argsort(exam_scores)[-5:][::-1]
print("\nii. Indices of the top 5 scores:", top_5_indices)

OUTPUT

16
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 16

PROBLEM STATEMENT: Write a program to add, subtract, mul ply, and


divide two integers using a user-defined type func on with return type.

PROGRAM
def perform_operations(num1, num2):

addition_result = num1 + num2

subtraction_result = num1 - num2

multiplication_result = num1 * num2

if num2 != 0:
division_result = num1 / num2
else:
division_result = "Cannot divide by zero"

return addition_result, subtraction_result, multiplication_result,


division_result

# Get user input for two integers


num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

results = perform_operations(num1, num2)

# Display the results print(f"Sum:


{results[0]}") print(f"Difference:
{results[1]}") print(f"Product:
{results[2]}") print(f"Quotient:
{results[3]}")

OUTPUT

17
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 17

PROBLEM STATEMENT: Write a program to find the


factorial of a given number using a func on.

PROGRAM
def calculate_factorial(number):

if number < 0:
return "Factorial is undefined for negative numbers"
elif number == 0 or number == 1:
return 1
else:
result = 1
for i in range(2, number + 1):
result *= i
return result

# Get user input for the number


user_input = int(input("Enter a non-negative integer to calculate its factorial: "))

factorial_result = calculate_factorial(user_input)

# Display the result


print(f"The factorial of {user_input} is: {factorial_result}")

OUTPUT

18
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 18

PROBLEM STATEMENT: Write a program to swap two


integers using call by value and call by reference.

PROGRAM
# Function to swap two integers using call by value def
swap_by_value(a, b):
temp = a
a=b
b = temp
return a, b

# Function to swap two integers using call by reference (using a list) def
swap_by_reference(lst):
temp = lst[0]
lst[0] = lst[1]
lst[1] = temp

# Example usage
x=5
y = 10

# Using call by value


x, y = swap_by_value(x, y)
print("After swapping by value: x =", x, "y =", y)

# Using call by reference (using a list) values


= [5, 10] swap_by_reference(values)

print("After swapping by reference: x =", values[0], "y =", values[1])

OUTPUT

19
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 19

PROBLEM STATEMENT: Write a program to transpose a matrix.

PROGRAM
def transpose_matrix(matrix):
# Using a nested list comprehension to transpose the matrix
transposed_matrix = [[matrix[j][i] for j in range(len(matrix))] for i in
range(len(matrix[0]))]
return transposed_matrix

# Example matrix
matrix = [
[1, 2, 3], [4,
5, 6], [7, 8,
9]
]

# Display the original matrix


print("Original Matrix:") for row
in matrix:
print(row)

# Transpose the matrix


transposed = transpose_matrix(matrix)

# Display the transposed matrix


print("\nTransposed Matrix:") for
row in transposed:
print(row)

OUTPUT

20
NAME:- Ashab Ali Khan 23SCSE2030407

LAB EXPERIMENT: 20

PROBLEM STATEMENT: Write a program to add,


multiply two matrices of size (3,3).

PROGRAM
def add_matrices(matrix1, matrix2):
result_matrix = [[0 for _ in range(3)] for _ in range(3)] # Initialize a
3x3 matrix with zeros

for i in range(3):
for j in range(3):
result_matrix[i][j] = matrix1[i][j] + matrix2[i][j] return

result_matrix

def multiply_matrices(matrix1, matrix2):


result_matrix = [[0 for _ in range(3)] for _ in range(3)] # Initialize a
3x3 matrix with zeros

for i in range(3):
for j in range(3):
for k in range(3):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]

return result_matrix

# Example matrices
matrix_a = [
[1, 2, 3], [4,
5, 6], [7, 8,
9]
]

matrix_b = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
]

# Add matrices
sum_matrix = add_matrices(matrix_a, matrix_b)

# Multiply matrices
product_matrix = multiply_matrices(matrix_a, matrix_b)

21
NAME:- Ashab Ali Khan 23SCSE2030407

# Display the original matrices


print("Matrix A:")
for row in matrix_a:
print(row)

print("\nMatrix B:")
for row in matrix_b:
print(row)

# Display the result of addition


print("\nSum of Matrices:") for row
in sum_matrix:
print(row)

# Display the result of multiplication


print("\nProduct of Matrices:")
for row in product_matrix:
print(row)

OUTPUT

22

You might also like