You are on page 1of 17

Abhishek 12c

#WAP that creates a file named 'file.txt' and enters 5 names

INPUT:

fh = open('file.txt', 'w')
for i in range(5):
name = input("Enter a name: ")
fh.write(name + '\n')
fh.close()

OUTPUT:

Enter a name: Abhishek


Enter a name: Shreyas
Enter a name: Zaid
Enter a name: Taksh
Enter a name: Ranvir

# WAP that creates a file named ‘file.txt’ and inputs 5 sentences

INPUT:

fh= open('file.txt', 'w')

sentences = []
for i in range(5):
sentence = input("Enter a sentence: ")
sentences.append(sentence)
fh.writelines(sentences)
fh.close()

OUTPUT:

Enter a sentence: I am going


Enter a sentence: I might be going
Enter a sentence: I am not going
Enter a sentence: I was not going to
Enter a sentence: I will be going
Abhishek 12c
# WAP to read the contents of the file. and display (1) one character at a time try to
(2) count the no. of Alphabets,digits ,spaces, total no. of Characters.
(3) display entire content at a time

INPUT:
file = open('file.txt', 'r')
content = file.read()
alphabets_count = 0
digits_count = 0
spaces_count = 0
total_characters = 0

for char in content:


if char.isalpha():
alphabets_count += 1
elif char.isdigit():
digits_count += 1
elif char.isspace():
spaces_count += 1
total_characters += 1

print(f"Alphabets count:”, alphabets_count)


print("Digits count:”, digits_count)
print("Spaces count: “,spaces_count)
print("Total characters:” ,total_characters)
print("Content of the file:")
print(content)

file.close()

OUTPUT:

Alphabets count:46
Digits count:5
Spaces count:23
Total characters:77
Abhishek 12c
#WAP Read the contents of file "file. txt" (i) replace the occurences of 'e' with '@'
(ii)Count the no. of 'the' and 'these'(i) count no. of words
dont write comments explainiing the code

INPUT:

file = open('file.txt', 'r')


content = file.read()
content1 = content.replace('e', '@')

count_the = content.count('the')
count_these = content.count('these')

words = content.split()
word_count = len(words)

print("Occurrences of 'the':", count_the)


print("Occurrences of 'these':", count_these)
print("Total number of words:", word_count)
print(‘e replaced with @:’, content1)
print(content)
file.close()

OUTPUT:

Occurrences of 'the': 5
Occurrences of 'these':3
Total number of words:18
e replaced with @
Abhishek 12c
#WAP to read the content of the file, display the entire content, then display each line
one at a time, and finally count the number of lines beginning with 'I' and 'T':

INPUT:

with open('file.txt', 'r') as file:


content = file.read()

print("Entire Content:")
print(content)

content1=file.readlines()
print("Displaying One Line at a Time:")
for i in content1:
print(i)
count_I = 0
count_T = 0
for line in content1:
if line.startswith('I'):
count_I += 1
if line.startswith('T'):
count_T += 1

print("Number of lines starting with 'I':", count_I)


print("Number of lines starting with 'T':", count_T)

OUTPUT:

Number of lines starting with ‘I’:1


Number of lines starting with 'T':3
Abhishek 12c
#WAP to read the file, splits its content into words, and then prints each word that does
not start with a vowel.

INPUT:

with open('file.txt', 'r') as file:


content = file.read()

words = content.split()

for i in words:
if i and i[0].lower() not in 'aeiou':
print(word)

OUTPUT:

Banana
Carrot
Dog

#WAP to display the contents of the file 'try.txt' line by line along with the number of
bytes occupied by each line

INPUT:

with open('try.txt', 'r') as file:


while True:
position = file.tell()
line = file.readline()
if not line:
break
line_bytes = position - file.tell()
print("Line:", line, "Bytes:", line_bytes)

OUTPUT:

Line: This is the first line.


Bytes: 24
Line: This is the second line.
Bytes: 25
Line: And this is the third line.
Bytes: 29
Abhishek 12c
#WAP to read a text file and (i) display the line with max no of words
(ii) line with max 5 letter words (iii) line with 5 words only

INPUT:

with open('file.txt', 'r') as file:


lines = file.readlines()

max_word_count_line = ""
max_five_letter_word_line = ""
five_word_lines = []

max_word_count = 0
max_five_letter_word_count = 0

for line in lines:


words = line.strip().split()
word_count = len(words)

five_letter_word_count = sum(1 for word in words if len(word) >= 5)

if word_count > max_word_count:


max_word_count = word_count
max_word_count_line = line.strip()

if five_letter_word_count > max_five_letter_word_count:


max_five_letter_word_count = five_letter_word_count
max_five_letter_word_line = line.strip()

if word_count == 5:
five_word_lines.append(line.strip())

print("Line with maximum number of words:", max_word_count_line)


print("Line with maximum number of 5-letter words or more:", max_five_letter_word_line)

print("Lines with exactly 5 words:")


for line in five_word_lines:
print(line)

OUTPUT:
Line with maximum number of words: This is a line with the maximum number of words.
Line with maximum number of 5-letter words or more: This line has maximum number of 5-
letter words.
Lines with exactly 5 words:
This is a line with exactly five words.
Abhishek 12c
#WAP that reads a file and displays each word separated by a '#' character
INPUT:

with open('file.txt', 'r') as file:


content = file.read()

words = content.split()

content1 = "#".join(words)
print(content1)

OUTPUT:

This#is#a#sample#text#file#OR#IS#IT.

#WAP to read a file and count the number of words and lines ending with a digit

INPUT:
with open('file.txt', 'r') as file:
lines = file.readlines()
word_count = 0
line_count_digit_end = 0
for line in lines:
words = line.strip().split()
word_count += len(words)
if line.strip() and line.strip()[-1].isdigit():
line_count_digit_end += 1
print("Number of words:", word_count)
print("Number of lines ending with a digit:", line_count_digit_end)

OUTPUT:

Number of words: 20
Number of lines ending with a digit: 2

Abhishek 12c
#WAP to read a file named 'try1.txt', duplicate all lines except those containing 'a', and
write the modified lines to another file named 'try2.txt'
INPUT
f1=open('try1.txt', 'r')
f2=open('try2.txt', 'w')
lines = f1.readlines()
for line in lines:
if 'a' in line:
lines.pop(line)
f2.write(lines)
f1.close()
f2.close()

OUTPUT:
Banana
Grapes

#WAP to create and write into a binary file

INPUT
import pickle

f1 = open("binary.dat", "wb+")
choice = 'yes'

while choice == 'yes':


name = input("Enter your name: ")
cl_sec = input("Enter class and section: ")
roll = int(input("Enter your roll number: "))
totm = int(input("Enter your total marks: "))
per = totm / 5
l = [name, cl_sec, roll, totm, per]
pickle.dump(l, f1)
choice = input("Do you want to continue? (yes/no): ")

print("\nName", "Class and Section", "Roll Number", "Total Marks", "Percentage")

f1.seek(0)

try:
while True:
record = pickle.load(f1)
for data in record:
print(data, end="\t")
print()

except EOFError:
print("All records displayed")
finally:
f1.close()
OUTPUT:
Enter your name: Abhishek
Enter class and section: 12A
Enter your roll number: 101
Enter your total marks: 450
Do you want to continue? (yes/no): yes
Enter your name: Shreyas
Enter class and section: 12B
Enter your roll number: 102
Enter your total marks: 480
Do you want to continue? (yes/no): no

Name Class and Section Roll Number Total Marks Percentage


Abhishek 12A 101 450 90.0
Shreyas 12B 102 480 96.0
All records displayed

Abhishek 12c
#WAP to search and display in a binary file

INPUT:
import pickle
fh= open("student.dat" "rb")"
ctr=0
rno=int(input("Enter roll no to search?"))
try:
while True:
l=pickle.load(fh)
if rno==l[0]:
ctr=ctr+1
for i in l:
print(i)
except EOFError:
if ctr==0:
print ('No match found")
else:
print("records displayed")

finally:
fh.close()

OUTPUT:
Enter roll no to search: 11
11
Abhishek
Physics

Abhishek 12c
#WAP to locate and update a binary file at the exact location

INPUT:

import pickle
f=open('student.dat','wb+')
mm = input ("Enter name to be updated:")
try:
While True:
pos=f.tell()
l = pickle. load (f)
if mm = l [1]:
nm_2=input("Enter new name")
l[1]=nm_2
f.seek(pos)
pickle.dump(l,f)
found=True
else:
pickle.dump(l,f)
except EOFError:
if found==True:
print("Record updated")
else:
print("Record not updated")
finally:
f.close()

OUTPUT:
Enter name to be updated: Abhishek
Enter new name: Shreyas
Record updated

Abhishek 12c
#WAP to write into the binary file with dictionary

INPUT:
import pickle

d = {}
f = open("itemsm.dat", "wb+")
ch = 'yes'
while ch == "yes":
iname = input("Enter name:")
inno = int(input("Enter item number:"))
price = float(input("Enter price:"))
qty = int(input("Enter quantity:"))
d[iname] = {"item_number": inno, "price": price, "quantity": qty}
pickle.dump(d, f)
ch = input("Do you want to continue? (yes/no): ")

f.seek(0)
try:
while True:
d1 = pickle.load(f)
for i in d1:
print(i, ":", d1[i])
except EOFError:
print("All records displayed")
finally:
f.close()

OUTPUT:
Enter name: Apple
Enter item number: 101
Enter price: 2.5
Enter quantity: 50
Do you want to continue? (yes/no): yes
Enter name: Banana
Enter item number: 102
Enter price: 1.0
Enter quantity: 30
Do you want to continue? (yes/no): no
Apple : {'item_number': 101, 'price': 2.5, 'quantity': 50}
Banana : {'item_number': 102, 'price': 1.0, 'quantity': 30}
All records displayed

Abhishek 12c
# Write a program to implement a stack for the employee details (empno, name).

INPUT
stk=[]
top=-1
def line():
print('~'*100)
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None

def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1

def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])

def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1

def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:nm
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
else:
print("Invalid Choice")
OUTPUT:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the employee number to push: 101
Enter the employee name to push: John
Element Pushed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter the employee number to push: 102
Enter the employee name to push: Alice
Element Pushed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
[102, 'Alice'] <-top
[101, 'John']
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
[101, 'John'] <-top
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4

Abhishek 12c
Write a python program to check whether a string is a palindrome or not using stack.

INPUT:

stack = []
top = -1
def push(ele):
global top
top += 1
stack[top] = ele
def pop():
global top
ele = stack[top]
top -= 1
return ele
def isPalindrome(string):
global stack
length = len(string)
stack = ['0'] * (length + 1)
mid = length // 2
i=0
while i < mid:
push(string[i])
i += 1
if length % 2 != 0:
i += 1
while i < length:
ele = pop()
if ele != string[i]:
return False
i += 1
return True
string = input("Enter string to check:")

if isPalindrome(string):
print("Yes, the string is a palindrome")
else:
print("No, the string is not a palindrome")

OUTPUT:

Enter string to check: hello


No, the string is not a palindrome

You might also like