Pramit CS
Pramit CS
Pramit CS
Roll NO : 1224
2. Write a program to generate prime numbers up to N. Where N is a user input more than
3. A wrong input should display proper error message.
3.
Write a python program to count the number of characters (character frequency) in a
string.
4. Write a python program to count and display the vowels of a given text.
5. Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.
6.
Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.
7. Write a python program to capitalize first and last letters of each word of a given string.
10 RAHU AND ARYAN BOTH ARE FRIEND THEY WAHT TO DISPLAY ADDITION OF
AGE SUBTRACTION OF FIGHTS MUPLTIPLIER AND DIVISION OF IQ.
DESCRIPTION AS FOLLOWS:
11. Write definition of a method ZeroEnding(scores) to add all those values in the list of
scores, which are ending with zero(0) and display the sum.
12.
Write a user – defined function which take string as a parameter and check whether the
string contains digit or not if it contains digit then calculate the sum of digits and print the
digit and print the original string. If it is not contained digit then it give original string with
appropriate message, “No digit is present “.
14. WAF to read the contents from a ‘abc.txt’ line by line and display the same on the
screen.
15.
WAF inn python to read lines from a text file abc.txt and display those lines which are
starting with alphabet’F’.
16. WAF to count how many lines are start with ‘f’.
17. WAF to read abc.txt and print those lines which are start with alphabet ‘f’ or ‘d’ including
both case.
Write a method in python to read lines from a file abc.txt and display those lines which
18.
are bigger than 50 characters.
WAF to count no. of characters from a file.
19.
21. WAF to read lines from a text file to find and display the occourance of the word ‘and’.
22. WAF to read thr contents from a text file and display the occurance of those words
which are having five or more alphabets.
WAF to read contents of a file to count and display the occurance of the words ‘is’ , ‘up’
23.
, ‘to’.
28. WAP to a binary file called emp.dat and write into it employee details of some
employees available in the form of dictionary.
Write a menu driven code to perform all binary operations on binary file.
29.
1
-
SOLUTION:
def print_pattern(rows):
num = 1
for i in range(1, rows + 1):
print()
rows = 4
print_pattern(rows)
OUTPUT-
-
Q-2 Write a program to generate prime numbers up to N. Where N is a user input more
than 3. A wrong input should display proper error message.
SOLUTION:
def is_prime(num):
if num < 2:
return False
return False
return True
try:
else:
if is_prime(num):
print(num)
except ValueError:
OUTPUT-
-
result = {}
for char in test_str:
result[char] = result.get(char, 0) + 1
return result
input_str = "vivekmaurya"
result = char_frequency(input_str)
print("Character frequencies in vivekmaurya:")
print(result)
OUTPUT-
Q-4 Write a python program to count and display the vowels of a given text.
SOLUTION:
def count_vowels_method(text):
vowels = "aeiouAEIOU"
num_vowels_method = count_vowels_method(input_text)
OUTPUT :
Q-5 Write a python program to swap each character of a given string from
lowercase to uppercase and vice versa.
SOLUTION:
def swap_case(text):
return text.swapcase()
swapped_text = swap_case(input_text)
OUTPUT:
-
Q-6 Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.
SOLUTION:
def find_longest_word(word_list):
OUTPUT:
-
Q-7 Write a python program to capitalize first and last letters of each word of a given
string.
SOLUTION:
def capitalize_words(s):
words = s.split()
result = []
modified_word
=word[0].upper()+word[1:-1] + word[-
1].upper()
result.append(modified_word)
print("String after:",
capitalize_words(input_str))
OUTPUT:
-
SOLUTION:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)
OUTPUT:
-
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Example usage:
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array is:", arr)
OUTPUT:
-
Q-10 RAHU AND ARYAN BOTH ARE FRIEND THEY WAHT TO DISPLAY ADDITION
OF AGE SUBTRACTION OF FIGHTS MUPLTIPLIER AND DIVISION OF IQ.
DESCRIPTION AS FOLLOWS:
RAHUL DESCRIPTION
AGE 32
HEIGHT 175 cm
WEIGHT 75 kg
IQ 100
ARYAN DESCRIPTION
AGE 25
HEIGHT 165 cm
WEIGHT 75 kg
IQ 50
FIRSTLY, DEFINE THE FUNCTION add(), mul (), & div()
SOLUTION:
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero!"
-
# Example usage:
rahul_age = 32
aryan_age = 25
rahul_weight = 75
aryan_weight = 75
rahul_iq = 100
aryan_iq = 50
print("Addition of ages:", add(rahul_age, aryan_age))
print("Subtraction of fights (assuming zero):", sub(rahul_age, aryan_age))
print("Multiplication of weights:", mul(rahul_weight, aryan_weight))
print("Division of IQs:", div(rahul_iq, aryan_iq))
OUTPUT:
-
Q-11 Write definition of a method ZeroEnding(scores) to add all those values in the list of
scores, which are ending with zero(0) and display the sum.
For example,
SOLUTION:
def ZeroEnding(scores):
total = 0
for number in scores:
if number % 10 == 0:
total += number
return total
# Example usage:
scores = [200, 456, 300, 100, 234, 678]
result = ZeroEnding(scores)
print("Sum of values ending with zero:", result)
OUTPUT:
Q-12 Write a user – defined function which take string as a parameter and check whether
the string contains digit or not if it contains digit then calculate the sum of digits and print
the digit and print the original string. If it is not contained digit then it give original string
with appropriate message, “No digit is present “.
SOLUTION:
def process_string(input_string):
if has_digit:
input_string ifchar.isdigit())
else:
# Example usage:
user_input = input("Enter a string: ")
process_string(user_input)
OUTPUT:
Q -13 WAP to read first 20 bytes and print them.
SOLUTION:
a=open(“abc.txt”,’r’)
Data = a.read(20)
print(Data)
a.close()
OUTPUT:
Q- 14 WAF to read the contents from a ‘abc.txt’ line by line and display the same on the screen.
SOLUTION: def
read():
f = open("abc.txt", "r")
break else:
print(i,end='')
f.close() read()
OUTPUT:
FILE:
Q-15 WAF inn python to read lines from a text file abc.txt and display those lines which are
starting with alphabet’F’.
SOLUTION: def
abc():
f=open('abc.txt','r')
data = f.readlines()
for i in data: if
i[0]=='f': print(i)
f.close() abc()
OUTPUT:
FILE:
Q-16 WAF to count how many lines are start with ‘f’.
SOLUTION: def abc(): with
open("abc.txt", "r") as f:
OUTPUT:
FILE:
Q-17 WAF to read abc.txt and print those lines which are start with alphabet ‘f’ or ‘d’
including both case.
SOLUTION: def abc():
with open('abc.txt') as f:
a = f.readlines() for i
in a: if i[0] == 'f' or
i[0]== 'd':
print(i)
abc()
OUTPUT:
FILE:
Q-18 Write a method in python to read lines from a file abc.txt and display those lines
which are bigger than 50 characters.
SOLUTION: def abc(): with
open("abc.txt") as f:
a = f.readlines()
for i in a: if
len(i) >= 50:
print(i) else:
print("not exist!")
abc() OUTPUT:
FILE:
Q-19WAF to count no. of characters from a file.
SOLUTION: def abc(): with
open("abc.txt") as f:
n = f.read()
c=0 for i in
n: if
i.isalpha():
c += 1 print("total
characters:",c) abc()
OUTPUT:
FILE:
Q-20 WAF to count the total no. of words in a file.
SOLUTION: def abc(): with
open("abc.txt") as a:
b = a.read() c = b.split()
FILE:
Q-21 WAF to read lines from a text file to find and display the occourance of the word
‘and’.
SOLUTION: def abc(): with
open("abc.txt") as a:
b = a.read() c = b.split()
d=0 for i in c: if i ==
'and' or i == 'And':
FILE:
–
Q 22 WAF to read thr contents from a text file and display the occurance of those words
which are having five or more alphabets.
SOLUTIONS: def abc():
with open("abc.txt") as z:
f = z.read()
h = f.split() a
=0 for i in h:
if len(i) >= 5:
a += 1
OUTPUT:
FILE:
Q-23 WAF to read contents of a file to count and display the occurance of the words ‘is’ ,
‘up’ , ‘to’.
SOLUTION: def abc(): with
open("abc.txt") as z:
f = z.read() h=
f.split() a=0 for
i in h: if i in
['is','up','to']:
FILE:
Q-24 WAF to write data to the text file.
SOLUTION: with
open("sample.txt", "w") as f:
f.write("Hello World")
open(r"sample.txt", "r") as f:
a = f.read()
print(a)
OUTPUT:
open("abc.txt", "wb") as a:
std = {} for i in
range(30):
OUTPUT:
Q-27WAP to read data from student.dat.
SOLUTION: import pickle with
open('student.dat','rb') as z:
OUTPUT:
Q-28 WAP to a binary file called emp.dat and write into it employee details of some
employees available in the form of dictionary.
DETAILS: Name,ID,Age,Salary SOLUTION:
a = {} for i in
range(1):
a['name'] = input("Enter name: ")
OUTPUT:
Q- 29 Write a menu driven code to perform all binary operations on binary file.
SOLUTION:
record=[]
while True:
rno=int(input("enter your roll no:"))
marks = int(input("enter your marks:"))
name = input("enter your name:")
data=[rno,name,marks]
record.append(data) ch = input("more
records y/n") if ch in "Nn":
break
pickle.dump(record,f)
print("record added")
def read():
open("student.dat","rb") as f:
while True:
s=pickle.load(f)
for i in s:
print(i)
def append(): with
open("student.dat","rb") as f:
rec.append(data) ch = input("more
records y/n:") if ch in "Nn": break
f.seek(0)
pickle.dump(rec,f)
print("record appended")
s=pickle.load(f)
for I in s: if
I[0]==r:
print(i) found
=1 break
except Exception:
f.close() if
found == 0:
pickle.dump(s,f)
break except
Exception:
f.close()
s = pickle.load(f) f.close() r =
print(s)
reclst =
for i in s:
if i[0]:
continue
reclst.append(i)
pickle.dump(reclst,f)
def mainmenu():
print("1.write")
print("2.read")
print("3.append")
print("4.search")
print("5.update")
print("6.delete")
print("7.exit") while True:
mainmenu() ch =
int(input("enter your choice"))
SOLUTION:
import csv
def write_records_to_csv(filename="std.csv"):
writer = csv.writer(csvfile)
for _ in range(num_records):
writer.writerow(record)
print("Record added!")
write_records_to_csv()
output:
Q-31 write a user-defined function and input book details [book no. , author name , price]
in the form of list using CSV file.
SOLUTION:
import csv
def input_book_details(filename="books.csv"):
writer = csv.writer(csvfile)
while True:
writer.writerow(book_details)
if add_more.lower() == 'n':
break
input_book_details()
output:
Q-32 write a menu-driven code to perform read,write and search operatons in a csv file.
SOLUTION:
import csv
def input_book_details(filename="books.csv"):
writer = csv.writer(csvfile)
while True:
writer.writerow(book_details)
if add_more.lower() == 'n':
break
def read_book_details(filename="books.csv"):
reader = csv.reader(csvfile)
found = False
if row[0] == book_no:
found = True
break
if not found:
def main():
while True:
print("\nMenu:")
print("4. Exit")
if choice == "1":
input_book_details()
read_book_details()
break
else:
print("Invalid choice!")
if __name__ == "__main__":
main()
OUTPUT
Q-33 WAP to implement all basic operations [push,pop,display].
SOLUTION:
s = []
c = 'y'
while c == 'y':
print('1. Push')
print('2. Pop')
print('3. Display')
if choice == 1:
s.append(n)
elif choice == 2:
if s == []:
print('Stack is empty')
else:
elif choice == 3:
l = len(s)
print(s[i])
else:
print('Invalid choice')
List contains the 2 values (Employee No., Name) should include options for addition,
deletion, to view topmost element (peek()) and display of Employee details.
SOLUTIONS:
stack = []
def push(employee_details):
stack.append(employee_details)
def pop():
if stack:
popped_item = stack.pop()
return popped_item
else:
print("Stack is empty!")
return None
def peek():
if stack:
top_item = stack[-1]
return top_item
else:
print("Stack is empty!")
return None
def display():
if stack:
print("Employee Details:")
else:
print("Stack is empty!")
while True:
print("\nStack Operations:")
print("4. Display")
print("5. Exit")
if choice == "1":
push([emp_no, emp_name])
pop()
display()
break
else:
print("Invalid choice!")
OUTPUT: