Lab Programs - Jupyter Notebook
Lab Programs - Jupyter Notebook
Lab Programs - Jupyter Notebook
Display the
student details, total marks, and percentage with suitable messages.
In [9]:
1b) Develop a program to read the name and Year of birth of a person. Display whether the person is a
senior citizen or not.
In [11]:
2a) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
In [6]:
2b) Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).
In [1]:
def fact(num):
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
return factorial
n = int(input("enter the value of n: "))
r = int(input("enter the value of r: "))
if n>r:
print("Answer = ",int(fact(n)/((fact(r)*fact(n-r)))))
else:
print("value of n should be greater than r")
In [2]:
import math
ln = []
n = int(input("enter the number of values to be added into a list: "))
sum = 0
sumstd = 0
for i in range(n):
v = int(input("enter the number: "))
ln.append(v)
print(ln)
print("elements in a list are: ",ln)
for i in range(n):
sum = sum + ln[i]
print("sum = ",sum)
mean = sum / n
print("mean = ",mean)
for i in range(n):
sumstd = sumstd + math.pow((ln[i]-mean),2)
var = sumstd/n
std = math.sqrt(var)
print("variance = ",var)
print("standard deviation = ",std)
4. Read a multi-digit number from the console. Develop a program to print the frequency of each digit with
suitable message.
In [1]:
str = ''
n = int(input("enter the number length: "))
for i in range(n):
a = input("enter the number: ")
str = str + a
print(str)
count = {}
for i in str:
count.setdefault(i,0)
count[i] = count[i] + 1
print(i , "is occuring " , count[i] , " time")
print(count)
or
In [2]:
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use dictionary with
distinct words and their frequency of occurences. Sort the dictionary in the reverse order of frequency
and display slice of first 10 items.]
In [4]:
text = open("sample.txt","r")
d = {}
for line in text:
line = line.strip()
#print(line)
words = line.split(" ")
#print(words)
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
a = sorted(d.items(), key=lambda x:x[1], reverse=True)
print("value stored in a = ",a)
#print("after slicing")
print(dict(a[:10]))
value stored in a = [('is', 2), ('my', 1), ('name', 1), ('zebra,', 1),
('zebra', 1), ('likes', 1), ('grass,', 1), ('grass', 1), ('grown', 1), ('o
n', 1), ('land.', 1), ('i', 1), ('am', 1), ('from', 1), ('India', 1)]
{'is': 2, 'my': 1, 'name': 1, 'zebra,': 1, 'zebra': 1, 'likes': 1, 'gras
s,': 1, 'grass': 1, 'grown': 1, 'on': 1}
6. Develop a program to sort the contents of a text file and write the sorted contents into a separate text
file.
In [7]:
def sorting(filename):
infile = open(filename)
words = []
for line in infile:
temp = line.split()
print(temp)
for i in temp:
words.append(i)
infile.close()
words.sort()
print("----------After sorting---------------")
print(words)
outfile = open("result9.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
sorting("sample.txt")
#writelines() method writes the items of a list to the file.
7 . Develop a program to backing Up a given Folder (Folder in a current working directory) into a ZIP File by
i l t d l d it bl th d
In [3]:
import os
import zipfile
print("Backup successful!")
#Note: Make sure to replace the "folder_name" with your desired folder path.
Backup successful!
9a) Define a function which takes TWO objects representing complex numbers and returns new complex
number with a addition of two complex numbers. Define a suitable class ‘Complex’ to represent the complex
number.
In [13]:
class Complex:
C1 = Complex(4, 2)
print("Complex number 1 :", C1.real, "+ i" , C1.imaginary)
C2 = Complex(8, 5)
print("Complex number 2 :", C2.real, "+ i" , C2.imaginary)
C3 = Complex(0, 0)
C3 = C3.addComp(C1, C2)
Complex number 1 : 4 + i 2
Complex number 2 : 8 + i 5
Sum of complex number : 12 + i 7
9b) Develop a program to read N (N >=2) complex numbers and to compute the addition of N complex
numbers.
In [12]:
import math
N = int(input("Enter the number of complex numbers to add (N >= 2): "))
sum = 0 + 0j
for i in range(N):
real = float(input(f"Enter the real part of complex number {i+1}: "))
imag = float(input(f"Enter the imaginary part of complex number {i+1}: "))
sum += complex(real, imag)
print("The sum of the complex numbers is:", sum)
10. Develop a program that uses class Student which prompts the user to enter marks in three subjects and
calculates total marks, percentage and displays the score card details. [Hint: Use list to store the marks
in three subjects and total marks. Use init() method to initialize name, USN and the lists to store marks
and total, Use getMarks() method to read marks into the list, and display() method to display the score
card details.]
In [11]:
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
for i in range(3):
#mark = int(input("Enter mark in subject {}: ".format(i+1)))
mark = int(input("Enter mark in subject %d: "%(i+1)))
self.marks.append(mark)
self.total += mark
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:", self.marks)
print("Total:", self.total)
print("Percentage:", self.total/3)
OR
In [10]:
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
for i in range(3):
marks = int(input(f"Enter marks for subject {i+1}: "))
self.marks.append(marks)
self.total += marks
def display(self):
print("\n--- Score Card ---")
print(f"Name: {self.name}")
print(f"USN: {self.usn}")
print(f"Marks: {self.marks}")
print(f"Total marks: {self.total}")
print(f"Percentage: {round((self.total/300)*100,2)}%")
8)Write a function named DivExp which takes TWO parameters a, b and returns a value c (c=a/b). Write
suitable assertion for a>0 in function DivExp and raise an exception for when b=0. Develop a suitable
program which reads two values from the console and calls a function DivExp.
In [2]:
def DivExp(a,b):
try:
assert a>0,"Number a is negative."
if b==0:
raise ZeroDivisionError("Zero Division Error")
c = a/b
return c
except ZeroDivisionError as x:
print(x)
except AssertionError as x:
print("Assertion failure:"+str(x))