Program
Program
def bubble(lst):
n = len(lst)
print("The list before sorting: ", lst)
for i in range (0,n):
for j in range (0, n-i-1):
if lst[j]>lst[j+1]:
lst[j],lst[j+1]=lst[j+1],lst[j]
print("litterary list: ", lst)
print("Sorted list: ", lst)
def insertion(lst):
n = len(lst)
print("The list before sorting: ", lst)
for i in range (1, n):
key = lst[i]
j = i-1
while (j >= 0 and key < lst[j]):
lst[j+1] = lst [j]
j -= 1
else:
lst[j+1] = key
print("litterary list: ", lst)
print("The final sorted list: ", lst)
ch='y'
while ch.lower()=='y':
l=eval(input('Enter your list to be sorted: '))
sort_type=int(input('\nChoose the type of sorting you want:\n1. Bubble Sort \n2. Insertion Sort\nYour choice :'))
if sort_type ==1:
bubble(l)
elif sort_type ==2:
insertion(l)
ch=input("\nDo you want to continue? y/n: ")
Output:
Enter your list to be sorted: [12,1,3,23,431,0]
Search Algorithm:
1.Linear Search
2.Binary Search
Enter the search algorithm you want to use:1
Enter the element you are searching for:4
element 4 found in position 3
Search Algorithm:
1.Linear Search
2.Binary Search
Enter the search algorithm you want to use:2
Enter the element you are searching for:5
Element 5 found in position: 5
Search Algorithm:
1.Linear Search
2.Binary Search
Enter the search algorithm you want to use:1
Enter the element you are searching for:6
element 6 not found
Search Algorithm:
1.Linear Search
2.Binary Search
Enter the search algorithm you want to use:2
Enter the element you are searching for:6
Element not found
def maxmin(t):
min=t[0]
max=t[0]
for i in t:
if min>i:
min=i
elif max<i:
max=i
print("maximum value in the tuple is: ",max)
print("minimum value in the tuple is: ",min)
def perfect_number(t):
t1=()
for i in t:
f=0
for j in range(1,i):
if i%j==0:
f+=j
if f==i:
t1+=(i,)
if len(t1)!=0:
print(t1)
else:
print("no perfect number in the tuple")
ch='y'
while ch.lower()=='y':
print("\n1. Find Maximum and Mminimum NUmber in the tuple\n2. Find perfect numbers in the tuple\n3. Exit")
ans = int(input("Enter your choice: "))
if ans==1:
t = eval(input("Enter the tuple: "))
maxmin(t)
elif ans==2:
t = eval(input("Enter the tuple: "))
perfect_number(t)
elif ans==3:
break
ch=input("\nDo you want to continue? y/n: ")
Output
def prime_sum(lst):
l=[]
for i in lst:
if i>1:
for j in range(2,i):
if i%j==0:
break
else:
l.append(i)
return sum(l)
def second_biggest(lst):
lst.sort()
return lst[-2]
ch='y'
while ch.lower()=='y':
print("\n1.Sum Of All Prime Numbers\n2. Second Biggest Number\n3. Exit")
ans = int(input("Enter your choice: "))
if ans==1:
lst = eval(input("Enter list: "))
print(prime_sum(lst))
elif ans==2:
lst = eval(input("Enter list: "))
print(second_biggest(lst))
elif ans==3:
break
ch=input("\nDo you want to continue? y/n: ")
Output
def replace(s):
i=int(input("enter the index you want to replace: "))
rw=input("enter the character: ")
s=s[:i]+rw+s[i+1:]
print(s)
def stringpalindrome(s):
for i in range(len(s)//2):
bi = len(s)-(i-1)
if s[i] != s[bi]:
print("not a palindrome")
break
else:
print("palindrome")
ch='y'
while ch.lower()=='y':
print("\n1. Replace\n2. String Palindrome\n3. Exit")
ans = int(input("Enter your choice: "))
if ans==1:
s = input("Enter the string: ")
replace(s)
elif ans==2:
s = input("Enter the string: ")
stringpalindrome(s)
elif ans==3:
break
ch=input("\nDo you want to continue? y/n: ")
Output:
1. Replace
2. String Palindrome
3. Exit
Enter your choice: 1
Enter the string: naman
enter the index you want to replace: 2
enter the character: a
naaan
1. Replace
2. String Palindrome
3. Exit
Enter your choice: 2
Enter the string: naman
palindrome
1. Replace
2. String Palindrome
3. Exit
Enter your choice: 2
Enter the string: jai
not a palindrome
def counting():
s=input("Enter a string:")
uv=uc=lc=lv=dig=spl=0
for ch in s:
if ch.isalnum():
if ch.isalpha():
if ch.isupper():
if ch in "AEIOU":
uv+=1
else:
uc+=1
else:
if ch in "aeiou":
lv+=1
else:
lc+=1
else:
dig+=1
else:
spl+=1
print("No.of Uppercase Vowels:",uv)
print("No.of Uppercase Consonants:",uc)
print("No.of Lowercase Vowels:",lv)
print("No.of Lowercase Consonants:",lc)
print("No.of Digits:",dig)
print("No.of Special Characters:",spl)
def longest(s):
s=s.split()
L=[]
for i in s:
l=len(i)
L.append(l)
m=max(L)
for j in s:
if len(j)==m:
print(j)
ans="y"
while ans.lower()=="y":
if choice==1:
counting()
ans=input("Would you like to continue:(y/n)")
if choice==2:
s=input("Enter a string:")
longest(s)
ans=input("Would you like to continue:(y/n)")
output
def frequency(s):
d={}
for i in s:
if i not in d:
d[i]=1
else:
d[i]+=1
print(d)
def firstch(l):
d={}
for i in l:
n=i[0]
if n in d:
d[n].append(i)
else:
d[n]=[i]
print(d)
ans="y"
while ans.lower()=="y":
print("1.Perform Frequency Of Characters In A String ")
print("2.Perform First Letter Of Words In A String In A Dictionary")
choice=int(input("Enter your choice:"))
if choice==1:
s=input("Enter a string:")
frequency(s)
ans=input("Would you like to continue:(y/n)")
if choice==2:
l=eval(input("Enter your list:"))
firstch(l)
ans=input("Would you like to continue:(y/n)")
Output
def create():
f=open("f1.txt","w")
n=int(input("Enter how many lines to be created:"))
for i in range(n):
t=input("Enter the line:")
f.write(t+"\n")
if (f):
print("File Created Successfully")
else:
print("Error")
f.close()
def read():
try:
f=open("f1.txt","r")
except:
print("no file found")
create()
f=open("f1.txt","r")
data=f.read()
wds=data.split()
lines=data.split('\n')
print("No.of characters:",len(data))
print("No.of Words:",len(wds))
print("No.of Lines:",len(lines)-1)
f.close()
def add():
try:
f=open("f1.txt","r")
except:
print("no file found")
create()
f=open("f1.txt","a")
n=int(input("Enter how many lines to be added:"))
l=[]
for i in range(n):
t=input("Enter the line:")
l.append(t+"\n")
f.writelines(l)
ans="y"
while ans.lower()=="y":
print("1.Perform Create A Text File")
print("2.Perform Read characters,Words And Lines in the Text File")
print("3. Add Data to the Text File")
choice=int(input("Enter your choice:"))
if choice==1:
create()
ans=input("Would you like to continue:(y/n)")
if choice==2:
read()
ans=input("Would you like to continue:(y/n)")
if choice==3:
add()
ans=input("Would you like to continue:(y/n)")
output:
def createf1():
f=open("f1.txt","w")
n=int(input("Enter how many lines to be created:"))
for i in range(n):
t=input("Enter the line:")
f.write(t+"\n")
if (f):
print("File Created Successfully")
else:
print("Error")
f.close()
def fcopy():
f=open("f1.txt","r")
l=open("f2.txt","w")
ch=input("The Letter Who's Corresponding Line To Be Printed:")
for i in f.readlines():
if ch==i[0]:
l.write(i)
print("copied succesfuly")
f.close()
l.close()
def capcopy():
f=open("f1.txt","r")
l=open("f2.txt","w")
for i in f.readlines():
i=i.title()
l.write(i)
print("copied succesfuly")
f.close()
l.close()
def revcopy():
f=open("f1.txt","r")
l=open("f2.txt","w")
for i in f.readlines():
l.write(i[::-1])
print("copied succesfuly")
f.close()
l.close()
ans="y"
while ans.lower()=="y":
print("1.Create A Text File")
print("2.Copy from file 1 to file 2 on basis of the first character")
print("3.Copy from file 1 to file 2 by capitalizing first letter of every word")
print("4.Copy from file 1 to file 2 by reversing every word")
choice=int(input("Enter your choice:"))
if choice==1:
createf1()
if choice==2:
fcopy()
if choice==3:
capcopy()
if choice==4:
revcopy()
ans=input('Do you want to continue y/n: ')
output
import pickle
def create():
f=open("dictionary.dat","wb")
n=int(input("Enter how many words and their meanings you want:"))
for i in range(n):
word=input("Enter A Word:")
meaning=input("Enter Meaning Of The Word:")
d={word:meaning}
pickle.dump(d,f)
if (f):
print("File Created Successfully")
else:
print("Error Occured")
f.close()
def display():
f=open("dictionary.dat","rb")
try:
while True:
det=pickle.load(f)
print(det)
except:
f.close()
def search(word):
f=open("dictionary.dat","rb+")
try:
while True:
det=pickle.load(f)
for i in det:
if i==word:
print("Meaning of",word,":",det[i])
except:
f.close()
ans="y"
while ans.lower()=="y":
print("1.Perform To Create A Binary File")
print("2.Perform To Display The File")
print("3.Perform To Search The Meaning Of The Word In The File")
choice=int(input("Enter your choice:"))
if choice==1:
create()
if choice==2:
display()
if choice==3:
word=input("Enter The Word Whose Meaning Is To Be Searched:")
search(word)
ans=input("Would you like to continue:(y/n)")
Output
import csv
def create():
with open('empData.csv','w', newline='') as f:
w = csv.writer(f)
a = 'y'
while a.lower()=='y':
empId = int(input('enter the id: '))
sal = int(input('enter salary: '))
deseg = input('enter desegnation: ')
l=[empId, sal, deseg]
w.writerow(l)
a = input('do you want to add more records: ')
def display():
with open('empData.csv','r') as f:
r = csv.reader(f)
print('id' ,'salary', 'designation', sep='\t')
for i in r:
print(i[0], i[1], i[2], sep='\t')
def search(empid):
with open('empData.csv','r') as f:
r = csv.reader(f)
for i in r:
if int(i[0])==empid:
print(i[0], i[1], i[2], sep='\t')
ans="y"
while ans.lower()=="y":
print("1.Create A CSV File")
print("2.Display The Content File")
print("3.Search On Basis Of Employee Id")
choice=int(input("Enter your choice:"))
if choice==1:
create()
if choice==2:
display()
if choice==3:
empid=int(input('enter the employee Id: '))
search(empid)
ans=input("Would you like to continue:(y/n)")
Output
import csv
def create():
with open('student.csv','w', newline='') as f:
w = csv.writer(f)
a = 'y'
while a.lower()=='y':
stuId = int(input('enter the id: '))
name = input('enter name: ')
s1 = int(input('enter subject 1 mark: '))
s2 = int(input('enter subject 2 mark: '))
s3 = int(input('enter subject 3 mark: '))
s4 = int(input('enter subject 4 mark: '))
s5 = int(input('enter subject 5 mark: '))
msum = s1+s2+s3+s4+s5
avg=msum/5
l=[stuId, name, msum, avg]
w.writerow(l)
a = input('do you want to add more records: ')
def display():
with open('student.csv','r') as f:
r = csv.reader(f)
print('id' ,'name', 'Sum of all the marks','avg. marks', sep='\t')
for i in r:
print(i[0], i[1], i[2], i[3], sep='\t')
def search(sid):
with open('student.csv','r') as f:
r = csv.reader(f)
for i in r:
if int(i[0])==sid:
print('Total marks of',i[1],'is',i[-2])
print('avrage marks of',i[1],'is',i[-1])
ans="y"
while ans.lower()=="y":
print("1.Create A CSV File")
print("2.Display The Content File")
print("3.Search Based On StudentID")
choice=int(input("Enter your choice:"))
if choice==1:
create()
if choice==2:
display()
if choice==3:
sid=int(input('enter student Id: '))
search(sid)
ans=input("Would you like to continue:(y/n)")
Output
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
def password_generator():
print("Welcome to the Password Generator!")
while True:
try:
length = int(input("Enter the desired length of the password: "))
if length <= 0:
print("Please enter a positive integer.")
continue
password = generate_password(length)
print("Generated Password:", password)
break
except ValueError:
print("Invalid input. Please enter a valid integer.")
password_generator()
Output:
Welcome to the Password Generator!
Enter the desired length of the password: 10
Generated Password: 2MS2Iy8=b$
def isEmpty(stk):
if len(stk)==0:
return True
else:
return False
def PUSH(stk,ele):
stk.append(ele)
def POP(stk):
if isEmpty(stk):
return None
else:
item=stk.pop()
return item
def PEEK(stk):
if isEmpty(stk):
print("Stack is empty! Underflow!")
else:
top=len(stk)-1
print("The topmost element is:",stk[top])
def DISPLAY(stk):
if isEmpty(stk):
print("Stack is empty!")
else:
top=len(stk)-1
print(stk[top],"<----TOP")
for i in range(top-1,-1,-1):
print(stk[i])
print("End of Stack")
stack=[]
while True:
print("1.PUSH-Enter elements into a stack")
print("2.POP-Delete element of the stack")
print("3.PEEK-See the topmost element")
print("4.DISPLAY-Display the stack")
print("5.EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
n=int(input("Enter the number of elements you want to enter:"))
for i in range(n):
element=eval(input("Enter the element:"))
PUSH(stack,element)
elif ch==2:
delele=POP(stack)
if delele==None:
print("Stack is empty!! Underflow!")
else:
print("Deleted Item is:",delele)
elif ch==3:
PEEK(stack)
elif ch==4:
DISPLAY(stack)
elif ch==5:
print("Exited!")
break
else:print("Invalid choice:")
OUTPUT:
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:1
Enter the number of elements you want to enter:5
Enter the element:100
Enter the element:200
Enter the element:300
Enter the element:400
Enter the element:500
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:4
500 <----TOP
400
300
200
100
End of Stack
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:2
Deleted Item is: 500
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:4
400 <----TOP
300
200
100
End of Stack
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:3
The topmost element is: 400
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:4
400 <----TOP
300
200
100
End of Stack
1.PUSH-Enter elements into a stack
2.POP-Delete element of the stack
3.PEEK-See the topmost element
4.DISPLAY-Display the stack
5.EXIT
Enter your choice:5
Exited!
Book=[]
Message=["Stack is Empty!","Book Added","Book Deleted!","Underflow!"]
def Pushbook():
bkname=input("Enter the book title:")
price=int(input("Enter the price of the book:"))
Book.append([bkname,price])
print(Message[1])
def Popbook():
if Book==[]:
print(Message[3])
else:
Book.pop()
print(Message[2]) 17
def dispbook():
if Book==[]:
print(Message[0])
else:
top=len(Book)-1
print(Book[top],"<----TOP")
for i in range(top-1,-1,-1):
print(Book[i])
while True:
print("1.Add new book(s)")
print("2.Delete a book")
print("3.Display the books")
print("4.EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
n=int(input("Enter the number of books you want to enter:"))
for i in range(n):
Pushbook()
elif ch==2:
Popbook()
elif ch==3:
dispbook()
elif ch==4:
print("Exited!")
break
else:
print("Invalid choice:")
OUTPUT:
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:1
Enter the number of books you want to enter:3
Enter the book title:Famous Five
Enter the price of the book:500
Book Added
Enter the book title:Secret Seven
Enter the price of the book:700
Book Added
Enter the book title:Gernimo Stilton
Enter the price of the book:600
Book Added
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:3
['Gernimo Stilton', 600] <----TOP
['Secret Seven', 700]
['Famous Five', 500]
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:2
Book Deleted!
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:3
['Secret Seven', 700] <----TOP
['Famous Five', 500]
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:2
Book Deleted!
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:2
Book Deleted!
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:3
Stack is Empty!
1.Add new book(s)
2.Delete a book
3.Display the books
4.EXIT
Enter your choice:4
Exited!