PythonLabFile Vanshi F-1
PythonLabFile Vanshi F-1
(Affiliated to)
GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY
SECTOR – 16 C, DWARKA, NEW DELHI
PYTHON
num = 0
p = n ** i
num = num +
p print(num)
for i in range(stran,
endran+1): if i % num ==
0:
print(i)
3. Accept three distinct digits and print all possible combinations from
the digits
arr = [2,4,5]
for i in range(3):
for j in range(3):
for k in range(3):
=k):
print(arr[i],arr[j],arr[k])
4. Program to Find the Sum of Digits in a Number
num = int(input('enter number: '))
sum = 0
temp = num
0:
digit = temp %
10 sum += digit
temp //= 10
print(sum)
5. Program to Find the Smallest Divisor of an Integer (other than 1)
num = int(input("Enter an integer: "))
divisor = 2
if num % divisor == 0:
op = divisor
break
else:
divisor += 1
=0: print(i)
7. Accept a number n and prints an identity matrix of nXn
if i == j:
") else:
") print()
q=0
for i in
range(1,n+1): q =
q+i
print(q)
9. Compute euler’s number. Use the Formula: e = 1 + 1/1! + 1/2! + ……1/n!
def fact(n):
fact = 1
fact = fact * i
return fact
print('euler formula')
')) op=0
for i in range(1,num+1):
div = 1/fact(i)
op = op + div
',op)
10. Read Print Prime Numbers in a range using Sieve of Eratosthenes (using User
defined function)
def is_prime(num):
if num <= 1:
return False
def encrypt(message,
keys):
encrypted_message = ""
for char in message:
if char.isalpha(): # Check if the character is a letter
shift = (ord(char) + keys - ord('a') if char.islower() else ord(char) + keys - ord('A')) %
26
encrypted_char = chr(shift + ord('a') if char.islower() else shift + ord('A'))
encrypted_message += encrypted_char
else:
encrypted_message += char # Keep non-alphabetic characters unchanged
return encrypted_message
input_message = "abc"
key = 3
output_message = encrypt(input_message, key)
print(f"Input: \"{input_message}\"")
print(f"Output: \"{output_message}\"")
12. Write a program to parse an email id to print from which email server it was sent
and when. ( input: From abc.jims@gmail.com Sun Jan 27 20:29:15 2023,
output : The email has been sent through gmail.com It was sent on Sun Jan 27 20:29:15
2023)
import re
def parse_email(email_id):
pattern = re.compile(r'From\s+(\S+@\S+)\s+\w+\s+(\w+\s+\d+\s+\d+:\d+:\d+\s+\
d+)') match = pattern.search(email_id)
if match:
server = match.group(1)
timestamp = match.group(2)
return f"The email has been sent through {server}\nIt was sent on {timestamp}"
else:
return "Invalid email ID format"
mx = max(list1[0], list1[1])
secondmax = min(list1[0],
list1[1]) n = len(list1)
for i in range(2,n):
secondmax =
mx mx = list1[i]
\ mx != list1[i]:
secondmax = list1[i]
secondmax != list1[i]:
secondmax = list1[i]
",\ str(secondmax))
14. Write a Python code to delete all odd numbers and negative numbers from a
given numeric list.
def filter_numbers(nums):
# Example usage:
filtered_numbers = filter_numbers(numbers)
print(filtered_numbers)
15. Python Program to Find Element Occurring Odd Number of Times in a List.
def find_odd_occurrence(numbers):
element_count = {}
if number not in
element_count:
element_count[number] = 1
else:
element_count[number] +=
1 odd_occ_elements = []
if element_count[element] % 2 != 0:
odd_occ_elements.append(element)
return odd_occ_elements
odd_elements = find_odd_occurrence(numbers)
def palindrome(string):
reversed_string =
== reversed_string
print(palindrome("racecar"))
print(palindrome("hello"))
17. Check if the Substring is present in a Given String .
s = "Hello, World!"
substring =
"World"
if s.find(substring) != -1:
string.") else:
stack = []
if char in
mapping.values():
stack.append(char)
else:
continue
print(balanced("(hi[world])"))
print(balanced("(hi[world])]"))
19. Display Letters which are in the First String but not in the Second.
second_set = set(second_string)
difference_set = first_set -
second_set result_string =
"".join(difference_set)
print("The letters in the first string but not in the second string:", result_string)
20. Write a program that reads a string and then prints a string that capitalizes
every other letter in the string. E.g., corona becomes cOrOnA.
def capitalize(input_string):
output_string = ""
for i, char in
enumerate(input_string): if i % 2
== 0:
output_string +=
char.upper() else:
output_string +=
char return
output_string
input_string = "corona"
output_string = capitalize(input_string)
print(output_string)
21. Python Program to Remove the Given Key from a Dictionary.
'c']
for key in
keys_to_remove: del
my_dict[key]
print(my_dict)
22. Python Program to Count the Frequency of Words Appearing in a String
Using a Dictionary.
frequencies = {}
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
print("frequencies are:")
print(frequencies)
23. WAP to store students’ information like admission number, roll number,
name and marks in a dictionary and display information on the basis of
admission number.
class Student:
marks = []
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)
def displayData(self):
def total(self):
def average(self):
m3) s1.displayData()
24. Python Program to Find the Total Sum of a Nested List Using Recursion.
def
flatten(seq):
for item in
seq:
if isinstance(item, list):
yield from
flatten(item)
else:
yield item
100] total_sum =
sum(flatten(nested_list))
print(total_sum)
25. Python Program to Read a String from the User and Append It into a File.
file3=open(fname,"a")
n"); file3.write("\n")
file3.write(
c)
file3.close(
print("Contents of appended
file:"); file4=open(fname,'r')
line1=file4.readline() while(line1!
=""):
print(line1)
line1=file4.readline()
file4.close()
26. Python Program to Count the Occurrences of a Word in a Text File.
f=
open('file.txt', 'r')
count = 0
words =
line.split() for i
in words:
if i == word:
count += 1
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n,
print("Element not
found") else:
def bubble_sort(arr):
arr_len = len(arr)
for i in range(arr_len-1):
flag = 0
arr[j+1] flag = 1
if flag == 0:
brea
k return arr
class Calculator:
def init
(self):
pass
calc = Calculator()
if operation == '+':
print("Result:", calc.add(num1, num2))
elif operation == '-':
print("Result:", calc.subtract(num1,
num2)) elif operation == '*':
print("Result:", calc.multiply(num1,
num2)) elif operation == '/':
print("Result:", calc.divide(num1,
num2)) elif operation == '%':
print("Result:", calc.mod(num1,
num2)) else:
print("Invalid operation. Please enter +, -, *, or /.")
31. Every time a vote is cast the name of the candidate is
appended to the data structure. Print the names of candidates
who received maximum vote in lexicographical order and if there
is a tie print lexicographically smaller name.
class
VoteCounter:
def init (self):
self.votes = {}
def cast_vote(self,
candidate_name): if
candidate_name in self.votes:
self.votes[candidate_name] += 1
else:
self.votes[candidate_name] = 1
def get_max_votes_candidates(self):
max_votes = max(self.votes.values())
max_vote_candidates = [candidate for candidate, votes
in
self.votes.items() if votes ==
max_votes] return
sorted(max_vote_candidates)[0]
counter = VoteCounter()
votes_casted = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Bob", "Alice"]
# Record the votes
for vote in votes_casted:
counter.cast_vote(vote)
import datetime
class
BirthdayReminder:
def init (self,
filename):
self.filename = filename
def add_birthday(self, name,
date): try:
with open(self.filename, 'a') as file: file.write(f"{name},
{date}\n")
print("Birthday added successfully!")
except Exception as e:
print(f"Error occurred while adding birthday:
{e}") def check_birthdays(self):
try:
today = datetime.date.today().strftime('%d-
%m') with open(self.filename, 'r') as file:
for line in file:
name, date =
line.strip().split(',') if date ==
today:
print(f"Today is {name}'s birthday!")
except Exception as e:
print(f"Error occurred while checking birthdays:
while True:
print("\n1. Add
Birthday") print("2.
Check Birthdays")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter name: ")
date = input("Enter date (DD-MM): ")
reminder.add_birthday(name, date)
elif choice == '2':
reminder.check_birthdays()
elif choice == '3':
print("Exiting..
.") break
else:
print("Invalid choice! Please enter a valid option.")
33. Create a class “Time” and initialize it with hrs and mins.
1.Make a method addTime which should take two time object and
add them. E.g.- (6 hour and 35 min)+(2 hr and 12 min) is (8 hr and
47 min)
2.Make a method showTime which should print the time.
3.Make a method showMinute which shoulddisplay the total
minutes in the Time. E.g.- (2 hr 6 min) should display 126
minutes.
@staticmethod
def addTime(t1, t2):
total_hrs = t1.hrs +
t2.hrs
total_mins = t1.mins + t2.mins
def showMinute(self):
total_minutes = self.hrs * 60 + self.mins
print(f"Total minutes: {total_minutes}")
class
StringManipulator:
def init (self):
self.input_string = ""
def get_String(self):
self.input_string = input("Enter a string: ")
def
print_String(self)
: if
self.input_string:
print("String in uppercase:",
self.input_string.upper()) else:
print("No string provided. Please use get_String method first.")
manipulator = StringManipulator()
manipulator.get_String()
manipulator.print_String()
35. Create a class “GrandMother” with a subclass “Mother” with a
subclass “Daughter”. All the three classes to have there own
constructors. The object of only “Daughter” class to be made to
fetch all the details of Grandmother and mother.
class GrandMother:
def init (self, grandmother_name):
self.grandmother_name = grandmother_name
class Mother(GrandMother):
def init (self, grandmother_name, mother_name):
super(). init (grandmother_name)
self.mother_name = mother_name
class Daughter(Mother):
def init (self, grandmother_name, mother_name,
daughter_name): super(). init (grandmother_name,
mother_name) self.daughter_name = daughter_name
def fetch_details(self):
return f"Grandmother: {self.grandmother_name}, Mother:
{self.mother_name}, Daughter: {self.daughter_name}"
print(daughter.fetch_details())
36. Create a class“Parent” and a subclass “Child”. The “Parent”
holds a constructor with two parameters name and age and also
one method print() that prints name and age. The“child to have
only one constructor that send the value to parent constructor and
calls print() from its constructor only. Note: the object of only
“Child” class to be created.
class Parent:
def init (self, name,
age):
self.name =
name self.age =
age
def print_info(self):
print(f"Name: {self.name}, Age: {self.age}")
class Child(Parent):
def init (self, name,
age): super(). init
(name, age)
self.print_info() # Call print_info method from Parent class within Child
constructor
class Animal(ABC):
@abstractmethod
def
movement(self):
pass
@abstractmethod
def habitat(self):
pass
@abstractmethod
def sound(self):
pass
class Mammals(Animal):
def movement(self):
return "Mammals can walk, run, or swim."
def habitat(self):
return "Mammals live in various habitats including forests, deserts, and
oceans."
def sound(self):
return "Mammals produce a variety of sounds including roars, howls, and
grunts."
class
Reptiles(Animal):
def
movement(self):
return "Reptiles move by crawling, slithering, or
swimming." def habitat(self):
return "Reptiles inhabit diverse environments such as deserts,
rainforests, and oceans."
def sound(self):
return "Reptiles can produce sounds but they are generally not as vocal
as mammals or birds."
class Birds(Animal):
def
movement(self):
return "Birds move by walking, hopping, flying, or swimming."
def habitat(self):
return "Birds are found in various habitats including forests,
grasslands, and wetlands."
def sound(self):
return "Birds are known for their diverse vocalizations such as
songs, chirps, and calls."
class
Amphibians(Animal):
def movement(self):
return "Amphibians have diverse modes of movement including hopping,
crawling, and swimming."
def habitat(self):
return "Amphibians are commonly found near water bodies such
as ponds, lakes, and streams."
def sound(self):
return "Some amphibians can produce sounds like croaks or
chirps, especially during mating season."
# Example usage:
mammal =
Mammals() reptile =
Reptiles() bird =
Birds()
amphibian = Amphibians()
print("=== Mammals ===")
print(mammal.movement())
print(mammal.habitat())
print(mammal.sound())
print("\n=== Reptiles ===")
print(reptile.movement())
print(reptile.habitat())
print(reptile.sound())
print("\n=== Birds ===")
print(bird.movement())
print(bird.habitat())
print(bird.sound()) print("\
n=== Amphibians ===")
print(amphibian.movement()
) print(amphibian.habitat())
print(amphibian.sound())
38. Implement ATM simulation system displaying its
operations using object oriented features.
class ATM:
def init (self, balance=0):
self.balance = balance
def
check_balance(self):
print(f"Your current balance is: $
{self.balance}") def deposit(self, amount):
self.balance += amount
print(f"${amount} deposited successfully.")
self.check_balance()
def withdraw(self,
amount): if amount <=
self.balance:
self.balance -= amount
print(f"${amount} withdrawn successfully.")
self.check_balance()
else:
print("Insufficient funds.")
initial_balance = float(input("Enter initial balance:
")) atm = ATM(initial_balance)
print("Welcome to the ATM!")
atm.check_balance() # Check initial balance
deposit_amount = float(input("Enter amount to deposit: "))
atm.deposit(deposit_amount)
withdraw_amount = float(input("Enter amount to withdraw: "))
atm.withdraw(withdraw_amount)
39. Python Program to Append, Delete and Display Elements of
a List Using Classes.
class
ListManager:
def init (self):
self.my_list = []
def delete_element(self,
element): if element in
self.my_list:
self.my_list.remove(element)
print(f"Element '{element}' deleted successfully.")
else:
print(f"Element '{element}' not found in the list.")
def
display_elements(self):
if self.my_list:
print("Elements in the
list:") for element in
self.my_list:
print(element
) else:
print("List is
empty.") manager =
ListManager() while
True:
print("\n1. Append
Element") print("2. Delete
Element") print("3. Display
Elements") print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
element = input("Enter element to append: ")
manager.append_element(element)
elif choice == '2':
element = input("Enter element to delete: ")
manager.delete_element(element)
elif choice == '3':
manager.display_elements()
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice! Please enter a valid option.")