Professional Documents
Culture Documents
INPUT:
fh = open('file.txt', 'w')
for i in range(5):
name = input("Enter a name: ")
fh.write(name + '\n')
fh.close()
OUTPUT:
INPUT:
sentences = []
for i in range(5):
sentence = input("Enter a sentence: ")
sentences.append(sentence)
fh.writelines(sentences)
fh.close()
OUTPUT:
INPUT:
file = open('file.txt', 'r')
content = file.read()
alphabets_count = 0
digits_count = 0
spaces_count = 0
total_characters = 0
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:
count_the = content.count('the')
count_these = content.count('these')
words = content.split()
word_count = len(words)
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:
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
OUTPUT:
INPUT:
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:
OUTPUT:
INPUT:
max_word_count_line = ""
max_five_letter_word_line = ""
five_word_lines = []
max_word_count = 0
max_five_letter_word_count = 0
if word_count == 5:
five_word_lines.append(line.strip())
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:
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
INPUT
import pickle
f1 = open("binary.dat", "wb+")
choice = 'yes'
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
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: