0% found this document useful (0 votes)
29 views

Programs

Uploaded by

bhavanask16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Programs

Uploaded by

bhavanask16
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1. a.

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 name of the student:')


USN = input ('Enter the USN of the student:')
m1 = int (input ('Enter the marks in the first subject:'))
m2 = int (input ('Enter the marks in the second subject:'))
m3 = int (input ('Enter the marks in the third subject:'))

total_marks = m1 + m2 + m3
percentage = (total_marks/300) *100

print ('Student details are:')


print ('Name is:', name)
print ('USN is:', USN)
print ('Marks in the first subject:', m1)
print ('Marks in the second subject:', m2)
print ('Marks in the third subject:', m3)
print ('Total Marks obtained:', total_marks)
print ('Percentage of marks:', percentage)

1. b. Develop a program to read the name and year of birth of a person.


Display whether the person is asenior citizen or not.

name = input ('Enter the name of a person:')


year_of_birth = int (input ('Enter the birth year:'))
age = 2023-year_of_birth

print ('The age is:', age)


if age>60:
print ('The person is senior citizen')
else:
print ('The person is not senior citizen')
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N
from the console.

def fib (n):


a=0
b =1
if n == 1:
print (a)
else:
print(a)
print(b)

for i in range (2,n):


c=a+b
a=b
b=c
print (c)
fib(5)

2. b. Write a function to calculate factorial of a number. Develop a program to


compute binomialcoefficient (Given N and R).

def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : "))
r = int(input("Enter the value of R (R cannot be negative or greater than N): "))
nCr = fact(n)/(fact(r)*fact(n-r))
print(n,'C',r," = ","%d"%nCr,sep=" ")
3. Read N numbers from the console and create a list. Develop a program to
print mean, variance andstandard deviation with suitable messages.

from math import sqrt


myList = []
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
print('The length of list is', len(myList))
print('List Contents', myList)
# Mean Calculation
total = 0
for elem in myList:
total += elem
mean = total / num
# Variance Calculation
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / num
# Standard Deviation Calculation
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stdDev)
4. Read a multi-digit number (as chars) from the console. Develop a program
to print the frequency of each digit with suitable message.

num = input("Enter a number : ")


print("The number entered is :", num)
freq = set(num)
for digit in freq:
print(digit, "occurs", num.count(digit), "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]

# Open the file in read mode


text = open("sample.txt", "r")
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
text = open("sample.txt", "r")
d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
for key in list(d.keys()):
print(key, ":", d[key])
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()].

import os.path
import sys

fname = input("Enter the filename whose contents are to be sorted : ")#sample file
unsorted.txt also provided

infile = open(fname, "r")

myList = infile.readlines()
# print(myList)
#Remove trailing \n characters
lineList = []
for line in myList:
lineList.append(line.strip())

lineList.sort()
#Write sorted contents to new file sorted.txt

outfile = open("sorted.txt","w")

for line in lineList:


outfile.write(line + "\n")

infile.close() # Close the input file


outfile.close() # Close the output file

if os.path.isfile("sorted.txt"):
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")
rdFile = open("sorted.txt","r")
for line in rdFile:
print(line, end="")
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 os
import sys
import pathlib
import zipfile

dirName = input("Enter Directory name that you want to backup : ")

curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
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

import sys

def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)

You might also like