Focp Practical
Focp Practical
Submitted By Submitted To
DIVYANSHU DEEP Mr. Deepak Kaushik
Roll NO = 2401010215
Program Name = B.tech CSE Core
Semester 1st
INDEX
S.N EXPERIMENTS Page DATE signature
no
1 Write a Python function that takes two numbers as input and returns a 06-
string indicating whether the first number is greater than, less than, or 1 09-
equal to the second number using comparison operators. 24
2 Create a Python program that functions as a calculator. It should support 06-
addition, subtraction, multiplication, division, and modulus operations. 09-
2-3
Maintain a history of calculations performed and provide an option to 24
display the history. Implement error handling for division by zero.
3 Develop a Python function that takes a list of tuples as input, where each 13-
tuple contains two numbers. For each tuple, compare the numbers using 4-5 09-
all comparison operators and store the results in a dictionary. Return a list 24
of dictionaries for all comparisons.
4 Write a Python program to simulate the operations of basic logic gates 13-
(AND, OR, NOT, NAND, NOR, XOR) using functions. The program should 6-7 09-
take two boolean inputs and the type of gate, then return the result of the 24
logical operation.
8 Create a class Custom String that mimics some of the built-in string 20-
methods in Python. Implement methods like find(), replace(), split(), and 12-13 09-
join(). The class should be able to handle these operations efficiently and 24
correctly.
9 Create a Python function that finds all prime numbers up to a given number 20-
n. Use nested loops to check for primality and optimize the function to 14-15 09-
handle large inputs efficiently. Additionally, allow the user to break the 24
loop prematurely if they input a specific command.
10 Write a Python program that takes a list of tuples representing student 20-
names and grades, and sorts the list by grades using a lambda function. 15 09-
Ensure that if two students have the same grade, they are sorted by their 24
names.
11 Create a Python function that takes a list of integers and returns a new list 20-
containing only the unique elements of the original list. Use a set to 16 09-
remove duplicates and maintain the order of elements as they appear in 24
the original
list.
12 Write a Python function that takes a string of text and returns a dictionary 27-
with the frequency of each word in the text. The function should handle 17 09-
punctuation and capitalization correctly and provide a case-insensitive 24
count.
13 Create a Python function that takes a tuple as an argument and returns a 27-
new tuple with the elements reversed. Demonstrate the use of tuples as 18 09-
function parameters and unpacking tuple elements within the function. 24
14 Create a Python function that checks if a given string containing 27-
parentheses is balanced. The function should return True if the 19-20 09-
parentheses are balanced and False otherwise. Use a stack to solve this 24
problem and
handle multiple types of parentheses: (), {}, and [].
15 Create a Python function that takes a list of strings and groups them into 4-
anagrams. The function should return a list of lists, where each sublist 20-21 10-
contains words that are anagrams of each other. Use dictionaries to store 24
and group the anagrams efficiently
17 Create a class Book with attributes title, author, and isbn. Implement a 4-
class Library that manages a collection of books. Implement methods to 24-26 10-
add, remove, and search for books by title or author. Use file handling to 24
save and load the library collection from a file.
18 Write a Python program that copies the contents of one file to another. 18-
Implement functions to open, read, write, and close files. Use exception 27-29 10-
handling to manage file errors, such as file not found or permission denied. 24
19 Create a base class Employee with attributes name and employee_id. 18-
Derive classes Manager and Developer from Employee, each with 29-31 10-
additional attributes and methods specific to their roles. Override methods 24
where necessary and use polymorphism to write a function that prints the
details
of all employees.
20 Develop a class Item with attributes name, price, and quantity. Create a 18-
class ShoppingCart that manages a collection of items 32-34 10-
24
21 Write a Python program that encrypts and decrypts the contents of a file 18-
using a simple Caesar cipher. 34-35 10-
24
22 Project Title: ROCK PAPER SCISSOR 8-11-
36-37 24
23 Project Title: PASSWORD GENERATOR 22-
38-40 11-
24
24 Project Title: DATA VISUALIZATION 27-
41-43 11-
24
Experiment-1
Write a Python function that takes two numbers as input and returns a
string indicating whether the first number is greater than, less than, or
equal to the second number using comparison operators.
Code:
a=int(input("enter first number:"))
if a>b:
elif a<b:
else:
Output:
output:
Experiment 2
Create a Python program that functions as a calculator. It should support
addition, subtraction, multiplication, division, and modulus operations.
Maintain a history of calculations performed and provide an option to
display the history. Implement error handling for division by zero.
code:
print('''Please choose from the following
1. Addition
2.Subtraction
3.Multiplication
4.Division
5.Modulus
6.History
7.Quit''')
def add(a,b):
c=a+b
print("Addition of the given numbers is",c)
hist.append(f"{a} + {b} is {c}")
def sub(a,b):
c=a-b
print("Subtraction of the given numbers is",c)
hist.append(f"{a} - {b} is {c}")
def mul(a,b):
c=a*b
print("Multiplication of the given numbers is",c)
hist.append(f"{a} * {b} is {c}")
def div(a,b):
if b == 0:
print("Error: division by zero is not allowed")
hist.append(f"{a} / {b} failed due to division by zero")
else:
c= a/b
print("Divison of the given numbers is",c)
hist.append(f"{a} / {b} is {c}")
def mod(a,b):
c=a%b
print("Modulus of the given numbers is",c)
hist.append(f"{a} % {b} is {c}")
hist = []
while True:
op = int(input("Enter your choice of operator:"))
if op == 7:
break
elif op == 6:
for i in hist:
print(i)
break
if op==1:
add(a,b)
elif op==2:
sub(a,b)
elif op==3:
mul(a,b)
elif op == 4:
div(a,b)
elif op==5:
mod(a,b)
Output:
Experiment 3
Develop a Python function that takes a list of tuples as input, where each
tuple contains two numbers. For each tuple, compare the numbers using
all comparison operators and store the results in a dictionary. Return a list
of dictionaries for all comparisons.
Code:
if compare_tuples(tuple_list):
"""
Takes a list of tuples, compares the numbers in each tuple using all comparison
operators,
and returns a list of dictionaries containing the results.
for a, b in tuple_list:
comparison_results = {
'equal': a == b,
'not_equal': a != b,
'less_than': a < b,
'greater_than': a > b,
'less_than_or_equal': a <= b,
'greater_than_or_equal': a >= b}
results.append(comparison_results)
return results
# Example usage
input_tuples = [(3, 5), (7, 7), (10, 2)]
output = compare_tuples(input_tuples)
print(output)
output:
Experiment-4
Write a Python program to simulate the operations of basic logic gates
(AND, OR, NOT, NAND, NOR, XOR) using functions. The program should
take two boolean inputs and the type of gate, then return the result of the
logical operation.
Code:
def logic_gate(input1, input2=None, gate_type="AND"):
"""
Simulates the operation of basic logic gates.
if gate_type == "AND":
return input1 and input2
elif gate_type == "OR":
return input1 or input2
elif gate_type == "NAND":
return not (input1 and input2)
elif gate_type == "NOR":
return not (input1 or input2)
elif gate_type == "XOR":
return input1 ^ input2
elif gate_type == "NOT":
if input2 is not None:
raise ValueError("NOT gate only requires one input.")
return not input1
else:
raise ValueError(f"Unknown gate type: {gate_type}")
# Example usage
try:
print("AND gate:", logic_gate(True, False, "AND")) # False
print("OR gate:", logic_gate(True, False, "OR")) # True
print("NAND gate:", logic_gate(True, False, "NAND")) # True
print("NOR gate:", logic_gate(False, False, "NOR")) # Trueprint("XOR gate:",
logic_gate(True, True, "XOR")) # False
print("NOT gate:", logic_gate(True, gate_type="NOT")) # False
except ValueError as e:
print(e)
Output:
Experiment-5
Create a Python function to check if any permutation of an input string is a
palindrome. For example, the string "civic" is a palindrome, and "ivicc" is a
permutation of "civic". The function should return True if any permutation
is a palindrome, otherwise False.
Code:
def can_form_palindrome(s: str) -> bool: #
Count the frequency of each character
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
# A string can form a palindrome if at most one character has an odd frequency
return odd_count <= 1
output:
Experiment-6
Develop a Python function that takes a string and a substring as input and
returns the number of times the substring appears in the string.
Implement this without using built-in string functions and optimize it for
large inputs.
Code:
def count_substring(string, substring):
"""
Counts the occurrences of a substring in a string without using built-in string
functions.
Args:
string (str): The main string to search in.
substring (str): The substring to count.
Returns:
int: The number of times the substring appears in the string.
"""
if not string or not substring:
return 0
n = len(string)
m = len(substring)
count = 0
if m > n:
return 0 # Substring is longer than the string, so it can't appear
string = "aaaaaa"
substring = "aa"
print(count_substring(string, substring))
output:
Experiment-7
Write a Python function that performs bitwise operations (AND, OR, XOR)
on two arrays of integers. The function should take two arrays and an
operator as input, perform the bitwise operation element-wise, and return
the resulting array.
Code:
Parameters:
- array1 (list of int): The first array of integers.
- array2 (list of int def bitwise_operation(array1, array2, operator):
"""
Perform bitwise operations (AND, OR, XOR) on two arrays of integers.
Returns:
- list of int: Resulting array after performing the operation.
Raises:
- ValueError: If the arrays have different lengths or an invalid operator is provided.
"""
if len(array1) != len(array2):
raise ValueError("Both arrays must have the same length.")
if operator == "AND":
return [a & b for a, b in zip(array1, array2)]
elif operator == "OR":
return [a | b for a, b in zip(array1, array2)]
elif operator == "XOR":
return [a ^ b for a, b in zip(array1, array2)]
else:
raise ValueError("Invalid operator. Use 'AND', 'OR', or 'XOR'.")
# Example usage:
array1 = [1, 2, 3]
array2 = [4, 5, 6]
output:
Experiment-8
Create a class CustomString that mimics some of the built-in string
methods in Python. Implement methods like find(), replace(), split(), and
join(). The class should be able to handle these operations efficiently and
correctly.
Code :
def _init_(self, value=""):
if not isinstance(value, str):
raise TypeError("CustomString value must be a string.")
self.value = value class CustomString
output:
Experiment-9
Create a Python function that finds all prime numbers up to a given number
n. Use nested loops to check for primality and optimize the function to
handle large inputs efficiently. Additionally, allow the user to break the
loop prematurely if they input a specific command.
Code:
import math
def find_primes(n):
primes = []
is_prime = True
return primes
n = int(input("Enter the number n up to which you want to find prime numbers: "))
primes = find_primes(n)
print(f"Prime numbers up to {n}: {primes}")
output:
EXPERIMENT 10
Write a Python program that takes a list of tuples representing student names and
grades, and sorts the list by grades using a lambda function. Ensure that if two
students have the same grade, they are sorted by their names.
Code:
def sort_students_by_grade(students):
sorted_students = sort_students_by_grade(students)
print(student)
OUTPUT:
EXPERIMENT 11
Create a Python function that takes a list of integers and returns a new list
containing only the unique elements of the original list. Use a set to
remove duplicates and maintain the order of elements as they appear in
the original list.
Code:
def remove_duplicates(nums):
seen = set()
unique_nums = []
return unique_nums
original_list = [1, 2, 2, 3, 4, 3, 5, 6, 5]
result = remove_duplicates(original_list)
print(result)
OUTPUT:
EXPERIMENT 12
Write a Python function that takes a string of text and returns a dictionary
with the frequency of each word in the text. The function should handle
punctuation and capitalization correctly and provide a case-insensitive count.
Code:
import string
def word_frequency(text):
text = text.lower()
words = text.split()
word_count = {}
word_count[word] = word_count.get(word, 0) + 1
return word_count
result = word_frequency(text)
print(result)
OUTPUT:
EXPERIMENT 13
Create a Python function that takes a tuple as an argument and returns a
new tuple with the elements reversed. Demonstrate the use of tuples as
function parameters and unpacking tuple elements within the function.
Code:
def reverse_tuple(input_tuple):
*elements, = input_tuple
reversed_tuple = tuple(elements[::-1])
return reversed_tuple
original_tuple = (1, 2, 3, 4, 5)
reversed_tuple = reverse_tuple(original_tuple)
OUTPUT:
EXPERIMENT 14
Create a Python function that checks if a given string containing
parentheses is balanced. The function should return True if the
parentheses are balanced and False otherwise. Use a stack to solve this
problem and handle multiple types of parentheses: (), {}, and [].
Code:
def is_balanced(s):
stack = []
for char in s:
if char in parentheses_map:
top_element = stack.pop() if stack else '#'
if parentheses_map[char] != top_element:
return False
else:
stack.append(char)
print(is_balanced("()"))
print(is_balanced("{[()]}"))
print(is_balanced("{[(])}"))
print(is_balanced("([)]"))
print(is_balanced("((()))"))
print(is_balanced("([{}])"))
print(is_balanced("["))
Output:
EXPERIMENT 15
Create a Python function that takes a list of strings and groups them into
anagrams. The function should return a list of lists, where each sublist
contains words that are anagrams of each other. Use dictionaries to store
and group the anagrams efficiently.
Code:
from collections import defaultdict
def group_anagrams(strs):
anagram_dict = defaultdict(list)
sorted_word = ''.join(sorted(word))
anagram_dict[sorted_word].append(word)
return list(anagram_dict.values())
words = ["eat", "tea", "tan", "ate", "nat", "bat"]
result = group_anagrams(words)
print(result)
OUTPUT:
EXPERIMENT 16
Create a class BankAccount that represents a bank account with attributes
account_number, account_holder, and balance. Implement methods for
depositing, withdrawing, and checking the balance. Override the str
and repr methods to provide meaningful string representations of the
account. Include error handling to prevent overdrafts.
Code:
class BankAccount:
self.account_number = account_number
self.account_holder = account_holder
self.balance = initial_balance
if amount <= 0:
self.balance += amount
if amount <= 0:
self.balance -= amount
def check_balance(self):
return f"BankAccount(account_number={self.account_number},
account_holder='{self.account_holder}', balance={self.balance:.2f})"
account.deposit(500)
try:
account.withdraw(200)
except ValueError as e:
print(e)
try:
account.withdraw(1500)
except ValueError as e:
print(e)
print(str(account))
print(repr(account))
OUTPUT:
EXPERIMENT 17
Create a class Book with attributes title, author, and isbn. Implement a
class Library that manages a collection of books. Implement methods to
add, remove, and search for books by title or author. Use file handling to
save and load the library collection from a file.
Code:
import json
class Book:
self.title = title
self.author = author
self.isbn = isbn
class Library:
self.filename = filename
self.books = self.load_books()
self.books.append(book)
self.save_books()
book_to_remove = None
if book.isbn == isbn:
book_to_remove = book
break
if book_to_remove:
self.books.remove(book_to_remove)
self.save_books()
else:
return found_books
return found_books
def save_books(self):
json.dump(books_data, file)
def load_books(self):
try:
books_data = json.load(file)
return books
except FileNotFoundError:
return []
library = Library()
library.add_book(book1)
library.add_book(book2)
library.add_book(book3)
library.remove_book("1234567890")
print(book)
OUTPUT:
EXPERIMENT 18
Write a Python program that copies the contents of one file to another.
Implement functions to open, read, write, and close files. Use exception
handling to manage file errors, such as file not found or permission
denied.
Code:
def open_file(filename, mode):
try:
return file
except FileNotFoundError:
return None
except PermissionError:
return None
except Exception as e:
print(f"Unexpected error:
def read_file(file):
try:
content =
file.read() return
content
except Exception as e:
return None
file.write(content)
except Exception as e:
def close_file(file):
try:
file.close()
except Exception as e:
"""Copies the content from the source file to the destination file."""
if source_file is None:
content = read_file(source_file)
if content is None:
close_file(source_file)
close_file(source_file)
destination_file = open_file(destination_filename,
write_file(destination_file, content)
close_file(destination_file)
source = "source.txt"
destination = "destination.txt"
copy_file(source, destination)
Output :
EXPERIMENT 19
Create a base class Employee with attributes name and employee_id. Derive classes
Manager and Developer from Employee, each with additional attributes and methods
specific to their roles. Override methods where necessary and use polymorphism to write
a function that prints the details of all employees.
Code:
class Employee:
self.name = name
self.employee_id = employee_id
def print_details(self):
class Manager(Employee):
self.team_size = team_size
def print_details(self):
def manage_team(self):
class Developer(Employee):
self.programming_language = programming_language
def print_details(self):
super().print_details()
def write_code(self):
def print_employee_details(employees):
employee.print_details()
manager.manage_team()
developer.write_code()
OUTPUT:
EXPERIMENT 20
Develop a class Item with attributes name, price, and quantity. Create a
class ShoppingCart that manages a collection of items .
Code:
class Item:
self.name = name
self.price = price
self.quantity = quantity
def total_price(self):
class ShoppingCart:
self.items = []
self.items.append(item)
if item.name == item_name:
self.items.remove(item)
return
def calculate_total(self):
def list_items(self):
if not self.items:
else:
print(item)
if not self.items:
else:
cart = ShoppingCart()
cart.add_item(item1)
cart.add_item(item2)
cart.add_item(item3)
cart.list_items()
cart.remove_item("Mouse")
cart.list_items()
print("\nCart Summary:")
print(cart)
Output:
EXPERIMENT 21
Write a Python program that encrypts and decrypts the contents of a file
using a simple Caesar cipher.
Code:
def caesar_cipher(text, shift, mode='encrypt'):
"""
Parameters:
Returns:
"""
result = []
if char.isalpha():
# Determine the start of the alphabet (either lowercase or uppercase)
output:
PROJECT 1:
Code:
import random
def get_computer_choice():
return random.choice(choices)
if player_choice == computer_choice:
def play_game():
return
computer_choice = get_computer_choice()
print(result)
play_game()
OUTPUT:
PROJECT 2:
PASSWORD GENERATOR
Code:
import random
import string
def generate_password(length=12):
lowercase = string.ascii_lowercase
uppercase = string.ascii_uppercase
digits = string.digits
punctuation = string.punctuation
password = [
random.choice(lowercase),
random.choice(uppercase),
random.choice(digits),
random.choice(punctuation)
random.shuffle(password)
return ''.join(password)
password = generate_password(length)
OUTPUT:
PROJECT 3:
DATA VISUALISASTION
Code:
import pandas as pd
import numpy as np
data = {
df = pd.DataFrame(data)
print(df)
plt.figure(figsize=(10, 6))
plt.xlabel('Product Category')
plt.show()import pandas as pd
import numpy as np
data = {
df = pd.DataFrame(data)
print(df)
plt.figure(figsize=(10, 6))
plt.xlabel('Product Category')
plt.show()
output: