0% found this document useful (0 votes)
19 views27 pages

File

Uploaded by

dikshitaa79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views27 pages

File

Uploaded by

dikshitaa79
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Program 1 :

Write a program to count the frequency of each element in a tuple. The program accepts a tuple of integers
from the user and displays the count of frequency of each element in the tuple.

print("hi user !")


tup1 = eval(input("enter integers separated by commas :"))
t = tuple(tup1)
list1 = []
for i in tup1:
if i not in list1:
print('value ', i ,' has occurence ', tup1.count(i))
list1.append(i)
Program 2 :
Create a function that takes a matrix (2D list) as input and returns the sum of each row as a list. For example,
if the input is [[1, 2, 3], [4, 5, 6], [7, 8, 9]], the output should be [6, 15, 24].

def matrix(list1):
l = []
for i in list1:
sum = 0
for j in i:
sum +=j
l.append(sum)
print(l)

l = [[1,4,5],[8,6,3],[5,6,2,4],[8,7,2,3]]
matrix(l)
Program 3 :
Develop a Python program that takes a year as input and determines whether it is a leap year or not. Print a
message indicating the result. A leap year is divisible by 4, except for years that are divisible by 100.
However, years divisible by 400 are leap years.

def leap(year):
if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
return print("{} is a leap year.".format(year))

a = int(input("enter the year :"))


leap(a)
Program 4 :
In a Python program, given a dictionary containing products as keys and their respective prices as values,
write a program to identify and print the product with the highest price.

a = {'a':'100','b':'200','c':'50','d':'105'}
l = []
x = a.values()
l.extend(x)
print(l)
b = max(l)
print(b)
for i,j in a.items() :
if j==b:
print(i)
Program 5:
Develop a Python program that takes a dictionary containing temperatures in Celsius as values with city
names as keys. Convert the temperatures to Fahrenheit and update the dictionary with the new values.

a = {'gurgaon':30 , 'delhi':45 , 'mumbai' :28}


def convert_to_F(dict):
for key,value in dict.items():
fah = (value * 9/5) + 32
dict[key] = fah
return dict

print(convert_to_F(a))
Program 6:
Write a Python program to combine two dictionaries by adding values for common keys. If a key is present
in only one dictionary, include it with its value in the result.

a = {'a': 100, 'b': 200, 'c':300}


b = {'a': 300, 'b': 200, 'd':400}
c= {}
c.update(a)
c.update(b)
for i,j in a.items():
for x,y in b.items():
if i ==x:
c[i] = j+y
print(c)
Program 7 :
Write a python program to count and display the number of vowels and the frequency of their occurrence in
the string.

def char_count(str):
vowel = ['a','e','i','o','u']
count = {'a':0,'e':0,'i':0,'o':0,'u':0}
v_count = 0
c_count = 0
for char in str:
if char in vowel:
v_count += 1
count[char] += 1
else:
c_count +=1
print("Number of Vowels : ",v_count)
print("Frequency of each Vowel : ", count)
print("Number of Consonants : ",c_count)

a = input("enter a string :")


char_count(a.lower())
Program 8:
Write a Python program that takes a sentence as input and creates a dictionary where keys are unique words,
and values are the frequencies of those words in the sentence.

def word_freq(s):
s = s.lower().split()
d = {}
for i in s:
d[i] = s.count(i)
return d

a = input('enter a sentence :')


print(word_freq(a))
Program 9:
Define a function ZeroEnding(SCORES) to add all those values in the list of SCORES, which are ending
with zero (0) and display the sum. For example : If the SCORES contain [200, 456, 300, 100, 234, 678] The
sum should be displayed as 600

def ZeroEnding(scores):
s = list(scores)
sum = 0
for i in s :
if str(i).endswith('0'):
sum+=i
else:
pass
return sum

a = eval(input("enter the list of numbers separated by comma :"))


print(ZeroEnding(a))
Program 10:
Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument and
displays the names (in uppercase)of the places whose names are longer than 5 characters. For example,
Consider the following dictionary PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"} The
output should be: LONDON NEW YORK

def countnow(places):
maxc = 5
for i in places.values():
if len(i) > maxc:
print(i.upper())
else :
pass
P={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
print(countnow(P))
Program 11:
Write a function LeftShift(Numlist, n) in Python, which accepts a list Numlist of numbers and n is a numeric
value by which all elements of the list are shifted to left.
Sample input data of the list
Numlist = [10, 20, 30, 40, 50, 60, 70], n=2
Output Numlist = [30, 40, 50, 60, 70, 10, 20]

def LeftShift(Numlist,n):
return Numlist[n:] + Numlist[:n]
print(LeftShift([10, 20, 30, 40, 50, 60, 70], 2))
Program 12:
Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The
function returns another list named ‘indexList’ that stores the indices of all Non-Zero Elements of L. For
example: If L contains [12,4,0,11,0,56] The indexList will have - [0,1,3,5]

def INDEX_LIST(L):
indexlist = []
for i in range(len(L)):
if L[i] != 0:
indexlist.append(i)
return indexlist

a =[12,4,0,11,0,56]
print(INDEX_LIST(a))
Program 13:
Write a Python function SwitchOver(Val) to swap the even and odd positions of the values in the list Val.
Note : Assuming that the list has even number of values in it. For example : If the list Numbers contain
[25,17,19,13,12,15] After swapping the list content should be displayed as [17,25,13,19,15,12]

def SwitchOver(l):
b = len(l)
l2=[]
for i in range(0,b,2) :
l2.append(l[i+1])
l2.append(l[i])
print(l2)

a = eval(input("enter the list of numbers separated by comma"))


l = list(a)
print(SwitchOver(l))
Program 14:
Write a Python function that takes a dictionary with student names as keys and their corresponding scores as
values. Convert this dictionary into a list of tuples, where each tuple contains the student's name and score.
Sort the list based on scores in descending order.

a = {'rastogi':85,'mice':99,'doggy don':62}
def convert(dict):
b=list(dict.items())
b.sort(key=lambda x:x[1],reverse=True)
return b
print(convert(a))
Program 15:
Write a python program to count and display the number of digits and the number of alphabets in a string.

def count_chars(string):
digits = 0
alpha = 0
for char in string:
if char.isdigit():
digits += 1
elif char.isalpha():
alpha += 1
else :
continue
print("Number of Digits = ", digits)
print("Number of Alphabets = ", alpha)

a = input("enter a string :")


count_chars(a)
Program 16:
Write a user defined function in Python named showgrades (S) which takes the dictionary S as an argument.
The dictionary, S contains Name: (Eng, Math, Science] as key: value pairs. The function displays the
corresponding grade obtained by the students according to the following grading rules:
AVG OF ENG,MATH,SCIENCE Grade
>=90 A
<90 but >=60 B
<60 C

def showgrade(s):
for i,j in s.items():
a=sum(j)/3
if a>=90:
print(f'{i} - A')
elif 60<=a and a<90:
print(f'{i}-B')
elif a<60:
print(f'{i}-C')
s={'Rajdeep':[12,56,89],'Anshul':[97,90,99],'Doggy don':[94,67,89],'Charley':[92,67,90]}
showgrade(s)
Program 17 :
Write a program in python to count the no. of vowels present in a given file named as “sample.txt”.
with open("sample.txt" , 'r') as f :
data = f.read()
def vowels(content):
v = 'AEIOUaeiou'
v_count = 0
for i in content :
if i in v:
v_count+=1
else :
pass
return v_count

print(f"The number of vowels present in sample.txt is {vowels(data)}")


Program 18:
Write a Python program to check if the number is an Armstrong number or not

num = int(input("Enter a number: "))


sum = 0
ab = num
while ab > 0:
digit = ab % 10
sum += digit ** 3
ab //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Program 19 :
Write a python program to print frequency of each word present in file ‘sample.txt’.

with open("sample.txt" , "r") as f:


data = f.read()
l1 = data.lower().split()
d = {}
l = []
for i in l1 :
if i not in l:
d[i] = l1.count(i)
l.append(i)
else:
pass
print(d)
Program 20 :
Write a python program that takes data line by line as input from the user in an interactive manner until the
user provides a null string as the input. Each line read should be capitalized and written to a file named
data.txt.

def get_data():
with open('data.txt', 'a') as f:
while True:
s = input("Enter a line (or blank to finish): ")
if not s:
break
else:
f.write(s.capitalize() + '\n')
f.close()
get_data()

print("your file data.txt has been created")


F = open("data.txt", "r")
lines = F.readlines()
print(f"This is your file : \n {lines} ")
Program 21 :
Write a python program to take students data from user and store it in a txt file .

with open("Stu.txt", "w") as fg:


n = int(input("No. of students to be entered: "))
for i in range(n):
a = input("Name:")
b = input("Roll: ")
c = input("Class: ")
d = input("Address: ")
fg.write(f"Name: {a}, Roll: {b}, Class:{c}, Address: {d}\n")
fg.close()
Program 22:
Write a program that takes two dictionaries containing details of all students of the class XII A and XII B
respectively. For each student, the dictionary should have an entry for roll number as the key and the name
of the student as the value part. Write a function in the program that takes these two dictionaries as an input
and writes it to a file 'classXIIstudents.dat'. Write another function that reads these two dictionaries from the
file and display the details of each student in separate lines.

import pickle
def file(d1, d2):
with open('classXIIstudents.dat', 'wb') as f:
pickle.dump([d1, d2],f)
try :
n = int(input("the no. of students to be entered for class XII A : "))
d1 = {}
for i in range(n):
rno=int(input("Enter roll number : "))
name=input("Enter Name : ")
d1[rno]=name
m = int(input("\nthe no. of students to be added to class XII B (if any) :"))
d2 = {}
for i in range(m):
rno=int(input("Enter roll number : "))
name=input("Enter Name : ")
d2[rno]=name
except:
print("Please enter valid integer")
file(d1,d2)
print("\n\nDetails saved successfully.")
def read_file():
with open ('classXIIstudents.dat','rb')as f:
print("Details of Students are : \n")
[d1,d2] =pickle.load(f)
if len(d1)>0:
print("Class XII A : ")
for k,v in d1.items():
print(k," ",v)
if len(d2)>0:
print("\nClass XII B : ")
for k, v in d2.items():
print(k," ",v)
read_file()
Program 23 :
Write a program that takes a dictionary of the following form from a user:
{'RollNum':12001, 'Name': 'Priyanka', 'Section':'A', 'Marks':85}
The program should contain n dictionaries in the file'classXIlstudents.dat' entered by user. Thereafter, it
should read the contents of the file and should update the marks by providing an increment of 5 while
ensuring that the marks scored does not exceed maximum marks of 100.
import pickle
with open("classXIIstudents.dat","wb") as f:
n = int(input("Enter no. of students: "))
for i in range(n):
R = int(input("Enter your roll no. : "))
ng = input("Enter your name: ")
Se = input("Enter your section: ")
M = int(input("Enter your marks: "))
d={'Rollno.':R,'Name':ng,'sec':Se,'marks':M}
pickle.dump(d,f)
with open("classXIIstudents.dat","rb") as f:
for i in range(n):
d = pickle.load(f)
print("Old Data: ",d)
if d['marks']<=95:
d['marks'] = d['marks'] + 5
print("Updated Data", d)
Program 24:
Program 25 :

You might also like