Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

1a) Develop a program to read the student details like Name, USN, and marks in three subjects.

Display the
student details, total marks, and percentage with suitable messages.

In [9]:

name = input("enter your name: ")


usn = input("enter USN: ")
marks1 = int(input("enter subject1 marks: "))
marks2 = int(input("enter subject2 marks: "))
marks3 = int(input("enter subject3 marks: "))
total = marks1 + marks2 + marks3
totmarks = 300
percentage = (total/totmarks)*100
print("name = ",name)
print("usn = ",usn)
print("total = ",total)
print("percentage = ",percentage)

enter your name: abc


enter USN: 1rl21cs00005
enter subject1 marks: 10
enter subject2 marks: 20
enter subject3 marks: 30
name = abc
usn = 1rl21cs00005
total = 60
percentage = 20.0

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]:

name = input("enter your name: ")


year = int(input("enter born year: "))
if((2023 - year)>60):
print(name," is senior citizen")
else:
print(name, " not a senior citizen")

enter your name: abc


enter born year: 1885
abc is senior citizen

2a) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
In [6]:

n = int(input("enter the length of Fibonacci Sequence"))


n1 = 0
n2 = 1
count = 2
if n<0:
print("enter only positive values")
elif n == 1:
print(n1)
else:
print(n1)
print(n2)
while(count<n):
n3 = n1 + n2
print(n3)
n1 = n2
n2 = n3
count = count + 1

enter the length of Fibonacci Sequence7


0
1
1
2
3
5
8

2b) Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).

nCr = n! / (r! (n - 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")

enter the value of n: 7


enter the value of r: 2
Answer = 21
3)Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.

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)

enter the number of values to be added into a list: 5


enter the number: 1
[1]
enter the number: 2
[1, 2]
enter the number: 3
[1, 2, 3]
enter the number: 4
[1, 2, 3, 4]
enter the number: 5
[1, 2, 3, 4, 5]
elements in a list are: [1, 2, 3, 4, 5]
sum = 15
mean = 3.0
variance = 2.0
standard deviation = 1.4142135623730951

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)

enter the number length: 5


enter the number: 2
enter the number: 1
enter the number: 1
enter the number: 2
enter the number: 3
21123
2 is occuring 1 time
1 is occuring 1 time
1 is occuring 2 time
2 is occuring 2 time
3 is occuring 1 time
{'2': 2, '1': 2, '3': 1}

or

In [2]:

message = input("enter the multidigit number: ")


count = {}
for i in message:
count.setdefault(i,0)
count[i] = count[i] + 1
print(count)

enter the multidigit number: 12322456789


{'1': 1, '2': 3, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1}

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.

['my', 'name', 'is', 'zebra,', 'zebra', 'likes', 'grass,', 'grass', 'is',


'grown', 'on', 'land.']
['i', 'am', 'from', 'India']
----------After sorting---------------
['India', 'am', 'from', 'grass', 'grass,', 'grown', 'i', 'is', 'is', 'lan
d.', 'likes', 'my', 'name', 'on', 'zebra', 'zebra,']

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

# set the source directory path


source_dir = r"C:\Users\Ashwath\Desktop\Darshan"

# initialize the zip file with a name


zip_name = "backup.zip"
backup_zip = zipfile.ZipFile(zip_name, 'w')

# traverse through all files and folders in the source directory


for foldername, subfolders, filenames in os.walk(source_dir):
# add each file or directory to the zip file
for filename in filenames:
backup_zip.write(os.path.join(foldername, filename))
# close the zip file
backup_zip.close()

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:

def __init__(self, tempReal, tempImaginary):


self.real = tempReal
self.imaginary = tempImaginary

def addComp(self, C1, C2):


temp=Complex(0, 0)
temp.real = C1.real + C2.real
temp.imaginary = C1.imaginary + C2.imaginary
return temp

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)

print("Sum of complex number :", C3.real, "+ i", C3.imaginary)

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)

Enter the number of complex numbers to add (N >= 2): 3


Enter the real part of complex number 1: 2
Enter the imaginary part of complex number 1: 3
Enter the real part of complex number 2: 1
Enter the imaginary part of complex number 2: 5
Enter the real part of complex number 3: 6
Enter the imaginary part of complex number 3: 4
The sum of the complex numbers is: (9+12j)

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)

name = input("Enter name of the student: ")


usn = input("Enter USN of the student: ")
s = Student(name, usn)
s.getMarks()
s.display()

Enter name of the student: abc


Enter USN of the student: 123
Enter mark in subject 1: 10
Enter mark in subject 2: 30
Enter mark in subject 3: 40
Name: abc
USN: 123
Marks: [10, 30, 40]
Total: 80
Percentage: 26.666666666666668

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)}%")

name = input("Enter student name: ")


usn = input("Enter student USN: ")

student = Student(name, usn)


student.getMarks()
student.display()

Enter student name: darsh


Enter student USN: 123
Enter marks for subject 1: 150
Enter marks for subject 2: 120
Enter marks for subject 3: 130

--- Score Card ---


Name: darsh
USN: 123
Marks: [150, 120, 130]
Total marks: 400
Percentage: 133.33%

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))

x = int(input("enter first number: "))


y = int(input("enter second number"))
print(x,y)
print(DivExp(x,y))

enter first number: -23


enter second number8
-23 8
Assertion failure:Number a is negative.
None

You might also like