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.

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


usn = input("Enter the usn of Student: " )
s1 = float(input("Enter the marks in subject1: ”)
s2 = float(input("Enter the marks in subject2: ”)
s3 = float(input("Enter the marks in subject3: ”)
total_marks= s1+s2+s3
per= (total_marks/300)*100
print ("student details are: ")
print ("Name:", name)
print ("USN:", usn)
print ("Marks in first subject is:", s1)
print ("Marks in second subject is:", s2)
print ("Marks in third subject is:", s3)
print ("Total Marks:", total_marks)
print ("Percentage is:", per)

Output:
Student details are:
Name: X
USN:1JS22
Marks in first subject is: 88
Marks in second subject is:77
Marks in third subject is: 93
Total Marks:258
Percentage is:86

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.
name = input("Enter the name: ")
yob =int( input("Enter the year of birth: "))
a=(2023-yob)
Print (“Name of the person is: ”, name)
Print (“Year of birth is: ”, yob)
Print (“Age of the person is: ”, a)
if a>=60:
print ("Person is Senior Citizen ”)
else:
print ("Person is Not a Senior Citizen ")

Output:
Name of the person is: X
Year of birth is: 1988
Age of the person is: 35
Person is Not a Senior Citizen
Name of the person is: Y
Year of birth is: 1950
Age of the person is: 73
Person is Senior Citizen
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

f0 = 0
f1 = 1
N = int(input(“Enter the Number of Terms needed in Fibonacci series:” ))
if N<=0:
print('Enter Positive Integer value: ')
else:
i=0
print('Fibonacci Sequence for N = '+ str(N) + ' is: ')
while i<N:
print(f0)
fth = f0 + f1
f0 = f1
f1 = fth
i += 1

Output:
Enter the Length of required Fibonacci Sequence: 10
Fibonacci Sequence for N = 10 is:
0
1
1
2
3
5
8
13
21
34

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

fact = 1
num = int (input(“Enter the Number: “)
act = num
print ("The Entered number is ", num)
while num > 0:
fact = fact * num
num = num -1
print ("The factorial of ", act, "is ", fact)

Output

The Entered number is 5


The factorial of 5 is 120
In mathematics, binomial helps us to expand some terms with higher power easily. For example, if we
have a number 103 to the power of 7. At that time, binomial is useful to expand this term. A binomial is
known as a polynomial of the sum or difference of two terms.
The binomial coefficient is a positive integer. It means is a positive whole number that is a constant in the
binomial theorem. This is useful to expand the highest power. In mathematics, it is one of the most
interesting and beneficial.
The formula for the binomial coefficient is

In this, the value of n should always be greater than ‘k’.

def factorial(N):
fact = 1
if N<0:
print('Enter the positive integer')
elif N==0:
print('The Factorial of 0 is ', fact)
elif N==1:
print('The Factorial of 1 is ', fact)
else:
num = N
while num > 0:
fact = fact*num
num = num -1
return fact

N=int(input('Enter the value of N: '))


R= int(input('Enter the value of R '))
factN = factorial(N)
factR = factorial(R)
binomial = factN / (factR*factorial(N-R))
print ('Factorial of ” +str(N)+ ‘is:', factN)
print ('Factorial of ”, str(R) + ‘is:', factR)
print('The Binomial coefficient for N= ' +str(N)+ ' and R= '+str(R)+ ' is ', binomial)

Output

Factorial of 7 is: 5040


Factorial of 3 is: 6
The Binomial coefficient for N=7 and R=3 is 35.0

3. Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.

Standard deviation is the spread of a group of numbers from the mean. The variance measures the average
degree to which each point differs from the mean. While standard deviation is the square root of the
variance, variance is the average of all data points within a group.
N=int(input('Enter the number of elements: '))
print(‘The number of elements in list is:’, N)
list1=[]
for i in range(N):
list1.append(int(input('Enter the element: ')))
print(‘The entered list is’,list1)
mean = round(sum(list1)/N,2)
print('Mean is ',mean)
lis_mean=[]
for i in range(N):
lis_mean.append((list1[i] - mean)**2)
variance = round(sum(lis_mean)/N,2)
print('Variance is ', variance)
SD=round(variance**(1/2),2)
print('Standard deviation is ', SD)

Output
The number of elements in list is:5
The entered list is [10,12, 23, 23,16]
Mean is 16.8
Variance is 29.36
Standard deviation is 5.42

4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.

str1 = input ("Enter the string: ")


print('The given string is:\n',str1)
d = dict()
for c in str1:
if c in d:
d[c] = d[c] + 1
else:
d[c] = 1
print(d)
print('Frequency of each digit\n')
for k,v in d.items():
print('Character \''+str(k)+'\' appeared ' + str(v)+ ' times')

Output:
The given string is:
123203345516617708895348309366247987488543289
{‘1’:3, ‘2’:4, ‘3’:7, ‘0’:3, ‘4’:5, ‘5’:4, ‘6’:4, ‘7’:4, ‘8’:7, ‘9’:4}

Frequency of each digit


Character '1' appeared 3 times
Character '2' appeared 4 times
Character '3' appeared 7 times
Character '0' appeared 3 times
Character '4' appeared 5 times
Character '5' appeared 4 times
Character '6' appeared 4 times
Character '7' appeared 4 times
Character '8' appeared 7 times
Character '9' appeared 4 times

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 occurrences. Sort the dictionary in the reverse order of
frequency and display dictionary slice of first 10 items]{'1': 3, '2': 4, '3': 7, '4': 5,
'
ECE.txt file:
JSSATE was established in the year 1997 at Bangalore to proactively participate in establishing a world
class Institution for Technical Education. The Campus is located on the South-Western edge of Bangalore
City. JSSATE is affiliated to Visvesvaraya Technological University VTU. ECE Department was started
in the year 1997. ECE Department is strengthened by well-qualified faculty members whose main aim is
to make students aware of the cutting-edge technology with competence, commitment & teamwork. ECE
Department has an excellent infrastructure for both Under Graduate and Post Graduate Degree with a
separate Academic block.
5': 4, '7': 4, '8': 7, '9': 4}
fname = input('Enter the file name: ')
fhand = open(r"C:\Users\JSS\Desktop\ECE.txt")
counts = dict( )
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
sortedcount = sorted(counts.items(), key=lambda x:x[1], reverse=True) #x[1] is the value and sorting is
based on value
converttodict = dict(sortedcount)
print('\n Sorted in descending order:\n\n',converttodict)
out = dict(list(converttodict.items())[0: 10])
print('\nTen Most frequently appeared word in a paragraph :\n',out)

Output:
Ten Most frequently appeared word in a paragraph :

{'the': 4, 'is': 4, 'in': 3, 'to': 3, 'ECE': 3, 'Department': 3, 'JSSATE': 2, 'was': 2, 'year': 2, 'Bangalore': 2}

6. Develop a program to sort the contents of a text file and write the sorted contents into a separate text
file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and file methods open(),
readlines(), and write()].
Input File
ECE.txt file:
JSSATE is the best Engg College under VTU Engg College
ECE department is the best department in JSSATE

infile = open(r'C:\Users\minch\Desktop\ECE.txt')
words = []
for line in infile:
temp = line.split()
for i in temp:
words.append(i)
infile.close()
words.sort(key=str.lower)
outfile = open(r'C:\Users\minch\Desktop\result.txt', 'w')
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()Character '4' appeared 5 times

Output
Result.txt

best best College College department department ECE EnggEngg in is is JSSATE JSSATE the the under
VTU

7. Develop a program to backing Up a given Folder (Folder in a current working directory) into a ZIP File
by using relevant modules and suitable methods.

import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder)
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
# Main Program
backupToZip(r'C:\Users\JSS\Desktop\AA')

Output:
Done. Character'1' appeared 3 times
Character '2' appeared 4 times

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.

def DivExp(a,b):
try:
c=round((a/b),2)
except ZeroDivisionError:
print('Error: Division by zero')
else:
return c
a = int(input('Enter the Dividend value of \'a\': '))
b = int(input('Enter the Divisor value of \'b\': '))
d=DivExp(a,b)
if d is not None:
print('The result of division is: ', d)
else:
print('The result of division is: infinity')

Output:
Case(1)
Enter the Dividend value of 'a': 10
Enter the Divisor value of 'b': 3
The result of division is: 3.33

Case(2)
Enter the Dividend value of 'a': 10
Enter the Divisor value of 'b': 0
Error: Division by zero
The result of division is: infinity

Case(2)
Enter the Dividend value of 'a': 0
Enter the Divisor value of 'b': 5
The result of division is: 0.0

9.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. Develop a program to read N (N >=2) complex numbers and to compute the addition
of N complex numbers.

class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __str__(self):
if self.imag >= 0:
return f"{self.real}+{self.imag}i"
else:
return f"{self.real}{self.imag}i"
def add_complex_numbers(num1, num2):
return num1 + num2
n = int(input("Enter the number of complex numbers: "))
complex_numbers = []
for i in range(n):
real, imag = input(f"Enter complex number {i+1}: ").split()
complex_numbers.append(Complex(float(real), float(imag)))
result = complex_numbers[0]
for i in range(1, n):
result = add_complex_numbers(result, complex_numbers[i])
print("Sum of the complex numbers is:", result)

Output:
Enter the number of complex numbers: 2
Enter complex number 1: 1 2
Enter complex number 2: 3 4
Sum of the complex numbers is: 4.0+6.0i

Enter the number of complex numbers: 2


Enter complex number 1: 2 9
Enter complex number 2: 10 5
Sum of the complex numbers is: 12.0+14.0i

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.]
class Student():
def __init__(self, name, usn):
self.name=name
self.usn=usn
self.marks=[]
self.subjects=[]

def enterMarks(self):
for i in range(3):
sub=input('Enter subject: ')
self.subjects.append(sub)
mark=int(input('Enter marks of %s in %s: '%(self.name,sub)))
self.marks.append(mark)

def total(self):
total=self.marks[0]+self.marks[1]+self.marks[2]
return total

def per(self):
per=(self.marks[0]+self.marks[1]+self.marks[2])/3
return per

def disp(self):
print(self.name,'USN:',self.usn,'got',self.marks,'in',self.subjects)
print('Total marks:',self.total())
print('Percentage:',self.per())

name=input('Enter name of student: ')


usn=input('Enter USN: ')
s1=Student(name,usn)
s1.enterMarks()
s1.disp()

class Complex():
def __init__(self, a, b):
self.a=a
self.b=b

def add(self):
print(self.a+self.b)

n=int(input('Enter number: '))


if n>=2:
for i in range(n):
a=complex(input('Enter first complex number: '))
b=complex(input('Enter second complex number: '))
a1=Complex(a,b)
a1.add()
else:
print('Invalid input. Enter number greater than 2')

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 = float(input(f"Enter marks for subject {i+1}: "))
self.marks.append(marks)
self.total += marks
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:")
for i in range(3):
print(f"\tSubject {i+1}: {self.marks[i]}")
print("Total:", self.total)
print("Percentage:", round((self.total / 3),2))
# Main program
name = input("Enter name: ")
usn = input("Enter USN: ")
student = Student(name, usn)
student.getMarks()
student.display()
Output:

You might also like