Lab Front Sheet - Merged
Lab Front Sheet - Merged
Record Work
Register Number :
Semester / Year :
Department :
1
SRMI INSTITUTE OF SCIENCE AND TECHNOLOGY
S.R.M. NAGAR, KATTANKULATHUR -603 203
BONAFIDE CERTIFICATE
Register No.
Technology, Kattankulathur.
Examiner-1 Examiner-2
2
INDEX SHEET
3
8
10
11
12
13
14
4
18CSC207J- Advanced Programming Practices
Record Work
Department : CSE
SRMI INSTITUTE OF SCIENCE AND TECHNOLOGY
S.R.M. NAGAR, KATTANKULATHUR -603 203
BONAFIDE
CERTIFICATE
Technology, Kattankulathur.
9
10
11
12
13
14
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Write a Python program to find those numbers which are divisible by 8 and multiple of 5,
between 1000 and 2000 (both included)
Algorithm:
Program:
Input/Output
Problem:
Write a Python program to guess a number between 1 to 9. Note : User is prompted to enter
a guess. If the user guesses wrong then the prompt appears again until the guess is correct,
on successful guess, user will get a "Well guessed!" message, and the program will exit.
Algorithm:
Program:
Problem:
Write a Python program to construct the following pattern, using a nested for loop.
*
**
***
****
*****
****
***
**
*
Algorithm:
Program:
n_882=5
for i in range(n_882): #for loop, i from 0 to n
for j in range(i): #j from 0 to i
print('* ',end="") #print '*' one after the other
print('') #change line
Input/Output
Problem:
Write a Python program that accepts a word from the user and reverse it. ( should not use
any functions)
Algorithm:
Program:
Input/Output
Problem:
Write a Python program which takes two digits m (row) and n (column) as input and
generates a two-dimensional array. The element value in the i-th row and j-th column of the
array should be i*j. Note :
i = 0,1.., m-1
j = 0,1, n-1.
Test Data : Rows = 3, Columns = 4
Expected Result : [[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]]
Algorithm:
Program:
print(array)
Input/Output:
Problem:
Write a Python program that accepts a string and calculate the number of digits and letters.
Algorithm:
Program:
s = input("Input a string") #takes an input
d=l=0
for c in s: #for a letter/character in string
if c.isdigit(): #using the function to check is c is a digit
d=d+1 #adding the value
elif c.isalpha(): #using the function to check is c is a alpha
l=l+1
else:
pass
print("Letters", l) print("Digits", d)
Input/Output:
Problem:
Algorithm:
Program:
l, u, p, d = 0, 0, 0, 0
s = input("Input a string: ")
if (len(s) >= 8) and (len(s) <= 16):
for i in s:
if (i.islower()):
l+=1
if (i.isupper()):
u+=1
if (i.isdigit()):
d+=1
Input/Output:
Problem:
Write a Python program to find numbers between 100 and 400 (both included) where each
digit of a number is an even number. The numbers obtained should be printed in a comma-
separated sequence.
Algorithm:
Program:
items = []
for i in range(100, 401):
s = str(i)
if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0): #convert into int
and check if each digit is divisible by 2
items.append(s)
print( ",".join(items))
Input/Output:
Problem:
Step 3: Check if the month is Jan, March, May, August, print (31 days )
Step 4: Check if month in April ,June ,September ,November print 30 days.
Program:
if month_name == "February":
print("No. of days: 28/29 days")
elif month_name in ("April", "June", "September", "November"):
print("No. of days: 30 days")
elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
print("No. of days: 31 day")
else:
print("Wrong month name")
Input/Output:
Problem:
Write a Python program to sum of two given integers. However, if the sum is between 105
to 200 it will return 200.
Algorithm:
Program:
Input/Output:
Problem:
Write a Python program to construct the following pattern, using a nested loop number.
Expected Input/Output:
999999999
88888888
7777777
666666
55555
4444
333
22
1
Algorithm:
Program:
for i in range(9,0,-1):
print(str(i) * i)
Input/Output:
Problem:
Write a Python program to create a histogram from a given list of integers
Algorithm:
Program:
histogram([2, 3, 6, 5])
Input/Output:
Problem:
Write a Python program that will return true if the two given integer values are equal or
their sum or difference is 5.
Algorithm:
Program:
Input/Output:
Problem:
Write a Python program to compute the distance between the points (x1, y1) and (x2, y2).
Algorithm:
Program:
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)
Input/Output:
Problem:
Function that takes a sequence of numbers and determines whether all are different from
each other
Algorithm:
Program:
data=input("set of intergers from 0-9: ")
if len(data) == len(set(data)):
print("True")
else:
print("False")
Input/Output:
Problem:
Write a Python program to count the number of each character of a given text
Algorithm:
Program:
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
Input/Output:
Problem:
Write a Python program that accept a positive number and subtract from this number the
sum of its digits and so on. Continues this operation until the number is positive.
Algorithm:
Program:
Input/Output:
Problem:
Write a Python program to find the digits which are absent in a given mobile number.
Algorithm:
Program:
Input/Output:
Problem:
Write a Python program to reverse the digits of a given number and add it to the original, If
the sum is not a palindrome repeat this procedure
Algorithm:
Input/Output:
Problem:
Write a Python program to print the length of the series and the series from the given 3rd
term, 3rd last term and the sum of a series.
Algorithm:
Program:
if n-5==0:
d = (s_sum-3*tn)//6
else:
d = (tltn-tn)/(n-5)
a = tn-2*d
j = 0
print("Series:")
for j in range(n-1):
print(int(a),end=" ")
a+=d
print(int(a),end=" ")
Input/Output:
Result: Hence the Structured Programming has been successfully executed and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Algorithm:
Program:
Input/Output:
Problem:
Algorithm:
Program:
Input/Output:
Problem:
Algorithm:
Step 1: Input n
Step 2: Input string and key
Step 3: Randint function used to create random “0” or “1”
Step 4: Append the randomly generated “0” and “1” to string, key.
Step 5: return string,key
Step 6: Exit
Program:
import random
n_882= int(input("Enter the length of binary string:"))
k_882= random.randint(1,5)
for i in range(1,n_882+1):
if((k_882+i)%2 == 0):
print("0",end='')
else:
print("1",end='')
Input/Output:
Problem:
Algorithm:
Program:
Input/Output:
Problem:
Input
(11, 2, 3, 14)
(13, 5, 22, 10)
(12, 2, 3, 10)
Input/Output
(36, 9, 28, 34)
Algorithm:
Program:
a_882= (1,2,3)
b_882 = (4,5,6)
c_882= (7,8,9)
print("Original list:")
print(a_882)
print(b_882)
print(c_882)
print("The sum of tuples","")
print(tuple(map(sum, zip(a_882,b_882,c_882))))
Input/Output:
Problem:
Algorithm:
L_882= [(), (), ('',), ('a', 'b'), ('a', 'b', 'c'), ('d')]
L_882 = [i for i in L_882 if i]
print(L_882)
Input/Output:
Problem:
Write a Python program to count the elements in a list until an element is a tuple
Algorithm:
Program:
num_882 = [10,20,30,(10,20),40]
c_882 = 0
for i in num_882:
if isinstance(i, tuple):
break
c_882+= 1
print("Number of element before tuple: ",c_882)
Input/Output:
Problem:
Program:
res = list(zip(*temp_882))
Input/Output:
Problem:
Algorithm:
Program:
list_882=[1,3,3,2,4,4]
l_882=[]
count_882=0
for i in list_882:
if i not in l_882:
count_882+=1
l_882.append(i)
print("No of unique items are: ",count_882)
Input/Output:
Problem:
Python Program to print all Possible Combinations from the three Digits
Algorithm:
Program:
def comb_882(L):
for i in range(3):
for j in range(3):
for k in range(3):
if (i!=j and j!=k and i!=k):
print(L[i], L[j], L[k])
Input/Output:
Problem:
Write a Python program (using function) to print the even numbers from a given list.
Algorithm:
Program:
def even(a_882):
for i in a_882:
if(i % 2 == 0):
print(i)
print("Even Numbers from list: ")
l_882= [1,2,3,4,5,6]
even(l_882)
Input/Output:
Problem:
Write a Python function (using function) that checks whether a passed string is palindrome or not.
Algorithm:
def pal(wd_882):
k_882= wd_882[::-1]
if(wd_882== k_882):
print("Palindrome Number")
else:
print("Not a Palindrome")
wd_882= input("Enter a word :")
pal(wd_882)
Input/Output:
Problem:
Write a Python function (using function) that checks whether a given number is prime or not
Algorithm:
if number_882 > 1:
for i in range(2, number_882):
if (number_882 % i) == 0:
print(number_882, "is not a prime number")
break
else:
print(number_882, "is a prime number")
else:
print(number_882, "is not a prime number")
Input/Output:
Result: Hence the Procedural Programming has been successfully implemented and
compiled successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Write a Python class named SRMIST with six attributes school, dept1, dept2, dept2 and
dept3. Add a new attribute specialization and display the entire attribute and their values of
the said class. Now remove the dept1 and dept2 attribute and display the entire attribute
with values.
Algorithm:
Program:
class SRMIST:
school = 'SRMIST'
dept1 = 'Computer Science'
dept2 = 'Artificial Intelligence'
dept3 = 'Mechanical Engineering'
dept4 = 'Biotech'
print("Original attributes and their values of the Student class:")
for attr, value in SRMIST.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nAfter adding the specialization, attributes and their values with the said
class:")
SRMIST.specialization = 'Blockchain'
for attr, value in SRMIST.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
print("\nAfter removing the dept1,dept2 attributes and their values from the said
class:")
del SRMIST.dept1
del SRMIST.dept2
#delattr(Student, 'student_name')
for attr, value in SRMIST.__dict__.items():
if not attr.startswith('_'):
print(f'{attr} -> {value}')
Input/Output:
Problem:
Write a Python program to crate four empty classes, CTECH, CINTEL, NWC and DSBS.
Now create some instances and check whether they are instances of the said classes or not.
Also, check whether the said classes are subclasses of the built-in object class or not.
Algorithm:
class CTECH:
pass
class CINTEL:
pass
class NWC:
pass
class DSBS:
pass
student1 = CTECH()
marks1 = CINTEL()
stu=NWC()
ma=DSBS()
print(isinstance(student1, CTECH))
print(isinstance(marks1, CTECH))
print(isinstance(stu, CTECH))
print(isinstance(ma, CTECH))
print(isinstance(marks1, CINTEL))
print(isinstance(student1, CINTEL))
print(isinstance(stu, CINTEL))
print(isinstance(ma, CINTEL))
print("\nCheck whether the said classes are subclasses of the built-in object class or
not.")
print(issubclass(CTECH, object))
print(issubclass(CINTEL, object))
print(issubclass(NWC, object))
print(issubclass(DSBS, object))
Input/Output:
Problem:
Write a program to print the names of the departments students by creating a Dept class. If
no name is passed while creating an object of the Dept class, then the name should be
"SCO", otherwise the name should be equal to the String value passed while creating the
object of the Dept class.
Algorithm:
Program:
class Dept:
def __init__(self, *args):
if len(args) == 1:
self.dept=args[0]
elif len(args) == 0:
self.dept="SCO"
def deptname(self):
print(self.dept)
d1=Dept()
d1.deptname()
d2=Dept("CSE")
d2.deptname()
Input/Output:
Problem:
Create a class named 'Rectangle' with two data members- length and breadth and a function
to calculate the area which is 'length*breadth'. The class has three constructors which are :
having no parameter - values of both length and breadth are assigned zero.
having two numbers as parameters - the two numbers are assigned as length and breadth
respectively.
having one number as parameter - both length and breadth are assigned that number.
Now, create objects of the 'Rectangle' class having none, one and two parameters and print
their areas.
Algorithm:
Program:
class rectangle:
length=0
breadth=0
if len(args) == 2:
self.length=args[0];
self.breadth=args[1]
elif len(args) == 1:
self.length=args[0]
self.breadth=args[0]
else:
self.length=0
self.breadth=0
def area(self):
return self.length*self.breadth;
r1=rectangle(5,10)
print(r1.area())
r2=rectangle(10)
print(r2.area())
r3=rectangle()
print(r3.area())
Input/Output:
Problem:
Create a class named 'PrintDT' to print various numbers of different datatypes by creating
different functions with the same name 'python_data’ having a parameter for each datatype.
(example : tuple, list, string)
Algorithm:
class PrintDT:
def py_data(self,list):
self.list=[]
print(self.list)
def py_data(self,tuple):
self.tuple=()
print(tuple)
def py_data(self,str):
self.str=''
print(str)
p=PrintDT()
p.py_data([1,2,3])
p.py_data(('a',[8,4,6],"mouse"))
p.py_data('amit')
Input/Output:
Problem:
A student from SRMIST has his/her money deposited Rs.15000, Rs.30000 and Rs. 40,000
in banks-CUB, HDFC and Indian Bank respectively. We have to print the money deposited
by him/her in a particular bank.
Create a class named 'Banks_SRMIST' with a function 'getBalance' which returns 0. Make
its three subclasses named 'CUB', 'HDFC' and 'Indian_Bank' with a function with the same
name 'getBalance' which returns the amount deposited in that particular bank. Call the
function 'getBalance' by the object of each of the three banks.
Algorithm:
Program:
class Banks_SRMIST:
def getBalance():
return 0
class CUB(Banks_SRMIST):
def getBalance(balance):
return balance
class HDFC(Banks_SRMIST):
def getBalance(balance):
return balance
class Indian_Bank(Banks_SRMIST):
def getBalance(balance):
return balance
Banks_SRMIST()
print(CUB.getBalance(15000))
print(HDFC.getBalance(30000))
print(Indian_Bank.getBalance(40000))
Input/Output:
Problem:
Program:
class Time():
def displayTime(self):
print ("Time is",self.hours,"hours and",self.mins,"minutes.")
def displayMinute(self):
print ((self.hours*60)+self.mins)
a = Time(2,40)
b = Time(1,30)
c = Time.addTime(a,b)
c.displayTime()
c.displayMinute()
Input/Output:
Problem:
Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units
by creating a class named 'Triangle' with a function to print the area and perimeter.
Algorithm:
Program:
class Triangle:
def findPerimeter(self, s1, s2, s3):
return (s1 + s2 + s3)
u = Triangle()
Input/Output:
Result: Hence the Object Oriented Programming has been implemented and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Algorithm:
Program:
import tkinter as tk
from tkinter import *
from tkinter import messagebox
def hello1():
msg = messagebox.show_882info( "Confirmation","Inserted Sucessfully")
def hello2():
msg = messagebox.show_882info( "Confirmation","Updated Sucessfully")
def hello3():
msg = messagebox.show_882info( "Confirmation","Deleted Sucessfully")
def hello4():
msg = messagebox.show_882info( "Confirmation","Select Button")
root_882=tk.Tk()
root_882.title('Reg Detail_882')
root_882.geometry('300x200')
l1_882=tk.Label(root_882,text="RegNo")
l1_882.grid(row=0)
t1_882=tk.Entry(root_882)
t1_882.grid(row=0,column=1)
l2_882=tk.Label(root_882,text="Name:")
l2_882.grid(row=1)
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1)
v = StringVar(root_882, value='CSE')
l3_882=tk.Label(root_882,text="Dept")
l3_882.grid(row=2)
t3_882=tk.Entry(root_882,textvariable=v)
t3_882.grid(row=2,column=1)
l4_882=tk.Label(root_882,text="Gender")
l4_882.grid(row=3)
radio1_882=IntVar()
radio2_882=IntVar()
rb1_882=Radiobutton(root_882,text='MAle',variable=radio1_882,value=0)
rb1_882.grid(row=3,column=1)
rb2_882=Radiobutton(root_882,text='Female',variable=radio1_882,value=1)
rb2_882.grid(row=3,column=2)
l5_882=tk.Label(root_882,text="Age")
l5_882.grid(row=4)
spin_882 = Spinbox(root_882,from_=15,to=20)
spin_882.grid(row=4,column=1)
b1_882=tk.Button(root_882, text='Insert',command=hello1)
b1_882.grid(row=5,column=0)
b2_882=tk.Button(root_882, text='Update',command=hello2)
b2_882.grid(row=5,column=1)
b3_882=tk.Button(root_882, text='Delete',command=hello3)
b3_882.grid(row=6,column=0)
b4_882=tk.Button(root_882, text='Select',command=hello4)
b4_882.grid(row=6,column=1)
root_882.mainloop()
Input/Output:
Algorithm:
Program:
import tkinter as tk
from tkinter import *
from tkinter import messagebox
def hello1():
msg = messagebox.show_882info( "Confirmation","Inserted Sucessfully")
def hello2():
msg = messagebox.show_882info( "Confirmation","Updated Sucessfully")
def hello3():
msg = messagebox.show_882info( "Confirmation","Deleted Sucessfully")
def hello4():
msg = messagebox.show_882info( "Confirmation","Select Button")
root_882=tk.Tk()
root_882.title('tk')
root_882.geometry('300x200')
l1_882=tk.Label(root_882,text="Custid")
l1_882.grid(row=0)
t1_882=tk.Entry(root_882)
t1_882.grid(row=0,column=1)
l2_882=tk.Label(root_882,text="Customer Name:")
l2_882.grid(row=1)
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1)
v = StringVar(root_882, value='adyar')
l3_882=tk.Label(root_882,text="Branch")
l3_882.grid(row=2)
t3_882=tk.Entry(root_882,textvariable=v)
t3_882.grid(row=2,column=1)
l4_882=tk.Label(root_882,text="account type")
l4_882.grid(row=3)
radio1_882=IntVar()
radio2_882=IntVar()
rb1_882=Radiobutton(root_882,text='saving',variable=radio1_882,value=0)
rb1_882.grid(row=3,column=1)
rb2_882=Radiobutton(root_882,text='non-saving',variable=radio1_882,value=1)
rb2_882.grid(row=3,column=2)
l5_882=tk.Label(root_882,text="Amount")
l5_882.grid(row=4)
w_882 = Scale(root_882, from_=0, to=200, orient=HORIZONTAL)
w_882.grid(row=4,column=1)
b1_882=tk.Button(root_882, text='Insert',command=hello1)
b1_882.grid(row=5,column=0)
b2_882=tk.Button(root_882, text='Update',command=hello2)
b2_882.grid(row=5,column=1)
b3_882=tk.Button(root_882, text='Delete',command=hello3)
b3_882.grid(row=6,column=0)
b4_882=tk.Button(root_882, text='Select',command=hello4)
b4_882.grid(row=6,column=1)
root_882.mainloop()
Input/Output:
Algorithm:
Program:
import tkinter as tk
from tkinter import *
root_882=tk.Tk()
root_882.title('Employee Detail_882')
l1_882=tk.Label(root_882,text="Empid")
l1_882.grid(row=0)
t1=tk.Entry(root_882)
t1.grid(row=0,column=1)
l2=tk.Label(root_882,text="Employee Name:")
l2.grid(row=1)
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1)
l3_882=tk.Label(root_882,text="Job")
l3_882.grid(row=2)
t3_882=tk.Entry(root_882)
t3_882.grid(row=2,column=1)
emty=IntVar()
def emtype():
print(emty.get())
g=tk.Label(root_882,text="Employee type")
g.grid(row=3,column=0)
g1=Radiobutton(root_882,text="Regular",variable=emty,width=25,value=1,command=emtype)
g1.grid(row=3,column=1)
g2=Radiobutton(root_882,text="Temporary",variable=emty,width=25,value=2,command=emtype)
g2.grid(row=3,column=2)
age=tk.Label(root_882,text="Salary")
age.grid(row=4,column=0)
age=Spinbox(root_882,from_=1, to = 30)
age.grid(row=4,column=1)
insert_882=tk.Button(root_882,text="insert_882",width=10,command=root_882.destroy)
insert_882.grid(row=5,column=0)
update_882=tk.Button(root_882,text="update_882",width=10,command=root_882.destroy)
update_882.grid(row=5,column=1)
delete_882=tk.Button(root_882,text="delete_882",width=10,command=root_882.destroy)
delete_882.grid(row=6,column=0)
select=tk.Button(root_882,text="Select",width=10,command=root_882.destroy)
select.grid(row=6,column=1)
root_882.mainloop()
Input/Output:
Algorithm:
Program:
import tkinter as tk
from tkinter import *
root_882=tk.Tk()
root_882.title('Booking_882')
l1_882=tk.Label(root_882,text="bookingid")
l1_882.grid(row=0)
t1_882=tk.Entry(root_882)
t1_882.grid(row=0,column=1)
l2_882=tk.Label(root_882,text="Passenger Name:")
l2_882.grid(row=1)
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1)
l3_882=tk.Label(root_882,text="Flight")
l3_882.grid(row=2)
t3_882=tk.Entry(root_882)
t3_882.grid(row=2,column=1)
fli=IntVar()
def flidis():
print(fli.get())
g=tk.Label(root_882,text="Source")
g.grid(row=3,column=0)
g1=Radiobutton(root_882,text="Delhi",variable=fli,width=25,value=1,command=flidis)
g1.grid(row=3,column=1)
g2=Radiobutton(root_882,text="Mumbai
Destination",variable=fli,width=25,value=2,command=flidis)
g2.grid(row=3,column=2)
g2=Radiobutton(root_882,text="Chennai",variable=fli,width=25,value=3,command=flidis)
g2.grid(row=3,column=3)
g2=Radiobutton(root_882,text="Kolkata",variable=fli,width=25,value=4,command=flidis)
g2.grid(row=3,column=4)
age=tk.Label(root_882,text="Duration")
age.grid(row=4,column=0)
age=Spinbox(root_882,from_=1, to = 30)
age.grid(row=4,column=1)
insert_882=tk.Button(root_882,text="insert",width=5,command=root_882.destroy)
insert_882.grid(row=5,column=0)
update_882=tk.Button(root_882,text="update",width=5,command=root_882.destroy)
update_882.grid(row=5,column=1)
delete_882=tk.Button(root_882,text="delete",width=5,command=root_882.destroy)
delete_882.grid(row=6,column=0)
select=tk.Button(root_882,text="Select",width=5,command=root_882.destroy)
select.grid(row=6,column=1)
root_882.mainloop()
Input/Output:
Algorithm:
Program:
import tkinter as tk
from tkinter import *
root_882=tk.Tk()
root_882.geometry("750x250")
root_882.title('Movie Booking_882')
l1_882=tk.Label(root_882,text="Movie booking id")
l1_882.grid(row=0)
t1_882=tk.Entry(root_882)
t1_882.grid(row=0,column=1)
l2_882=tk.Label(root_882,text="Person Name:")
l2_882.grid(row=1)
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1)
l3_882=tk.Label(root_882,text="Movie Name")
l3_882.grid(row=2)
t3_882=tk.Entry(root_882)
t3_882.grid(row=2,column=1)
boo=IntVar()
def tick():
print(boo.get())
g=tk.Label(root_882,text="Class")
g.grid(row=3,column=0)
g1=Radiobutton(root_882,text="A",variable=boo,width=25,value=1,command=tick)
g1.grid(row=3,column=1)
g2=Radiobutton(root_882,text="b",variable=boo,width=25,value=2,command=tick)
g2.grid(row=3,column=2)
g=tk.Label(root_882,text="Time of Show")
g.grid(row=3,column=3)
g1=Checkbutton(root_882, text='7:15 pm')
g1.grid(row=3,column=4)
g2=Checkbutton(root_882, text='9 am')
g2.grid(row=3,column=5)
age=tk.Label(root_882,text="No. of Tickets")
age.grid(row=4,column=0)
age=Scale(root_882, from_=1, to= 20, orient=HORIZONTAL)
age.grid(row=4,column=1)
insert_882=tk.Button(root_882,text="insert",width=5,command=root_882.destroy)
insert_882.grid(row=5,column=0)
update_882=tk.Button(root_882,text="update",width=5,command=root_882.destroy)
update_882.grid(row=5,column=1)
delete_882=tk.Button(root_882,text="delete",width=5,command=root_882.destroy)
delete_882.grid(row=6,column=0)
select=tk.Button(root_882,text="Select",width=5,command=root_882.destroy)
select.grid(row=6,column=1)
root_882.mainloop()
Input/Output:
Algorithm:
import tkinter as tk
from tkinter import *
root_882=tk.Tk()
root_882.geometry("400x200")
root_882.title('Annual Rate_882')
l1_882=tk.Label(root_882,text="Annual Rate:")
l1_882.grid(row=0,sticky='w')
t1_882=tk.Entry(root_882)
t1_882.grid(row=0,column=1,sticky='w')
l2_882=tk.Label(root_882,text="Number of Payments:")
l2_882.grid(row=1,sticky='w')
t2_882=tk.Entry(root_882)
t2_882.grid(row=1,column=1,sticky='w')
l3_882=tk.Label(root_882,text="Loan Principle:")
l3_882.grid(row=2,sticky='w')
t3_882=tk.Entry(root_882)
t3_882.grid(row=2,column=1,sticky='w')
l2_882=tk.Label(root_882,text="Monthly Payments:")
l2_882.grid(row=3,sticky='w')
t2_882=tk.Entry(root_882)
t2_882.grid(row=3,column=1,sticky='w')
l2_882=tk.Label(root_882,text="Remaining Loan:")
l2_882.grid(row=4,sticky='w')
t2_882=tk.Entry(root_882)
t2_882.grid(row=4,column=1,sticky='w')
final=tk.Button(root_882,text="Final balance",width=10,command=root_882.destroy)
final.grid(row=5,column=0,sticky='w')
monthly=tk.Button(root_882,text="Monthly Payment",width=15,command=root_882.destroy)
monthly.grid(row=5,column=1)
qui=tk.Button(root_882,text="Quit",width=5,command=root_882.destroy)
qui.grid(row=5,column=2,sticky=tk.N)
root_882.mainloop()
Input/Output:
Algorithm:
Program:
master = Tk()
myText=StringVar()
master.title('Form_882')
Label(master, text="Form",bg='light green').grid(row=0,column=1)
Label(master, text="Name",bg='light green').grid(row=1)
Label(master, text="Course",bg='light green').grid(row=2)
Label(master, text="Semester,",bg='light green').grid(row=3)
Label(master, text="Form No.",bg='light green').grid(row=4)
Label(master, text="Contact No.",bg='light green').grid(row=5)
Label(master, text="Email id.",bg='light green').grid(row=6)
Label(master, text="Address",bg='light green').grid(row=7)
master.configure(bg='light green')
e1_882 = Entry(master)
e2_882 = Entry(master)
e3_882 = Entry(master)
e4_882 = Entry(master)
e5_882 = Entry(master)
e6_882 = Entry(master)
e7_882 = Entry(master)
e1_882.grid(row=1, column=1)
e2_882.grid(row=2, column=1)
e3_882.grid(row=3, column=1)
e4_882.grid(row=4, column=1)
e5_882.grid(row=5, column=1)
e6_882.grid(row=6, column=1)
e7_882.grid(row=7, column=1)
b = Button(master, text="Submit",bg='RED')
b.grid(row=8,column=1)
mainloop()
Input/Output:
Algorithm:
Program:
expression = ""
def press(num):
global expression
expression = expression + str(num)
equation.set(expression)
def equalpress():
try:
global expression
total = str(eval(expression))
equation.set(total)
expression = ""
except:
equation.set(" error ")
expression = ""
def clear():
global expression
expression = ""
equation.set("0")
if __name__ == "__main__":
gui = Tk()
gui.title("Calculator_882")
gui.geometry("270x150")
equation = StringVar()
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=70)
clrscr = Button(gui, text=' C ', fg='black', bg='grey',
command=clear, height=1, width=7)
clrscr.grid(row=2, column=0)
percent.grid(row=2, column=3)
Input/Output:
Algorithm:
Program:
Algorithm:
Program:
Input/Output:
Algorithm:
Program:
Algorithm:
Program:
Algorithm:
Program:
import tkinter as tk
from tkinter import ttk
r_882= tk.Tk()
r_882.title('Time Converter_882')
r_882.geometry("380x210")
label1_882=tk.Label(r_882,fg="#fff",text="Welcome to Real Time Currency
Converter",bg="#187498",font='Helvetica 12 bold',justify='center',width=38)
label1_882.place(x=0,y=0)
label2_882=tk.Label(r_882,text="1 USD = 78.93 Indian Rupee",font='Helvetica 12
bold',justify='center')
label2_882.place(x=81,y=40)
label3_882=tk.Label(r_882,text="Date : 2022-06-15",font='Helvetica 12
bold',justify='center')
label3_882.place(x=120,y=65)
n_882= tk.StringVar()
c1_882= ttk.Combobox(r_882, width = 13,justify='center', textvariable = n_882)
c1_882['values'] = (' USD ')
c1_882.place(x = 40, y = 120)
c1_882.current(0)
n2_882= tk.StringVar()
c2_882= ttk.Combobox(r_882, width = 13,justify='center', textvariable = n2_882)
c2_882['values'] = (' INR')
c2_882.place(x = 230, y = 120)
c2_882.current(0)
e1_882=tk.Entry(r_882,justify='center',width=13)
e1_882.place(x=50,y=150)
e2_882=tk.Entry(r_882,justify='center',width=13)
e2_882.place(x=240,y=150)
b1_882=tk.Button(r_882,text="Convert",bg='blue',fg="#fff")
b1_882.place(x=160,y=165)
r_882.mainloop()
Input/Output:
Algorithm:
Program:
root.title("Tab_882")
root.resizable(0,0)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
tabControl = ttk.Notebook(root)
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tabControl.add(tab1, text="Tab 1")
tabControl.add(tab2, text="Tab 2")
tabControl.pack(expand=1, fill="both")
label_frame = LabelFrame(tab2, text="The Snake")
label_frame.pack(expand=YES, fil=BOTH)
disabledCheckBox = Checkbutton(label_frame, text="Disabled", font="Ariel 10
bold").place(x=10, y=10)
unCheckedCheckBox = Checkbutton(label_frame, text="Uncheked", font="Ariel 10
bold").place(x=190, y=10)
enabledCheckBox = Checkbutton(label_frame, text="Enabled", font="Ariel 10
bold").place(x=350, y=10)
blueCheckBox = Checkbutton(label_frame, text="Blue", font="Ariel 10 bold").place(x=10,
y=40)
goldCheckBox = Checkbutton(label_frame, text="Gold", font="Ariel 10 bold").place(x=190,
y=40)
redCheckBox = Checkbutton(label_frame, text="Red", font="Ariel 10 bold").place(x=350,
y=40)
progressBarLabelFrame = LabelFrame(label_frame, text="ProgressBar", font="Ariel 10 bold")
progressBarLabelFrame.place(x=10, y=70)
runProgressButton = Button(progressBarLabelFrame, text="Run Progress", font="Ariel 10
bold").grid(
row=0, column=0
)
startProgressBar = Button(progressBarLabelFrame, text="Start Progresbar", font="Ariel 10
bold").grid(
row=1, column=0
)
stopProgressBar = Button(progressBarLabelFrame, text="Stop Progresbar", font="Ariel 10
bold").grid(
row=2, column=0
)
stopAfterSecond = Button(progressBarLabelFrame, text="Stop Aftersecond", font="Ariel 10
bold").grid(row=3, column=0)
progress = ttk.Progressbar(
label_frame, orient=HORIZONTAL,style="green.Horizontal.TProgressbar", length=490,
mode="determinate",maximum=4, value=2
)
progress.pack(ipady=20)
progress.place(x=0, y=230)
root.config(menu=menubar)
root.mainloop()
Input/Output:
Result: Hence the Event Driven Programming has been implemented and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Create the below table and execute the insert, update and the below select statements.
i) Write a query to display the total number of recipes available with the description “Chinese”
ii) Write a query to display the id, name of the recipes with chef_id 'BL000002'.
iii) Write a query to display the description of the recipes whose name begins with 'P'.
Algorithm:
Program:
import sqlite3
conn_882=sqlite3.connect('week4.db')
print("Opened database successfully")
conn_882.execute("CREATE TABLE recipes(id INT PRIMARY KEY NOT NULL,name
VARCHAR,description TEXT,category_id INT,chef_id text,created DATETIME);")
print("Table created successfully")
conn_882.execute("INSERT INTO recipes VALUES(101,'Chicken
Mugali','Indian',01,'BL00001','2022-02-14');")
conn_882.execute("INSERT INTO recipes VALUES(102,'Hakka
noodels','Chinese',02,'BL00002','2022-02-14');")
conn_882.execute("INSERT INTO recipes VALUES(103,'Octopus
Soup','Chinese',03,'BL00003','2022-02-14');")
conn_882.execute("INSERT INTO recipes VALUES(104,'Pasta','Italian',04,'BL00004','2022-02-
14');")
conn_882.commit()
print("Records inserted successfully");
print("\nDisplaying the table \n")
for rows in conn_882.execute("SELECT * from recipes;"):
print(rows)
print("\nPART A\n")
for rows in conn_882.execute("SELECT * from recipes WHERE description='Chinese';"):
print(rows)
print("\nPART B\n")
for rows in conn_882.execute("SELECT id,name from recipes WHERE chef_id='BL00002';"):
print(rows)
print("\nPART C\n")
for rows in conn_882.execute("SELECT description from recipes WHERE name LIKE 'P%';"):
print(rows)
conn_882.close()
Input/Output:
Problem:
Create a table movie of the below structure and assume data types.Movie_ID, Movie_Name, Genre, Language,
Rating ,Do the following queries
a. Update the movies rating by 10% and display it
b. Delete the movies with movie_id 102
c. Select movies whose rating is more than 3.
Algorithm:
Program:
import sqlite3
conn_882=sqlite3.connect('week4.db')
print("Opened database successfully")
conn_882.execute("CREATE TABLE movie(Movie_ID INT PRIMARY KEY NOT NULL,Movie_Name
VARCHAR,Genre TEXT,Language text,Rating FLOAT);")
print("Table created successfully")
conn_882.execute("INSERT INTO movie VALUES(101,'Interstellar','Sci-fi','English',8.3);")
conn_882.commit()
conn_882.execute("INSERT INTO movie VALUES(102,'The Batman','Superhero','English',8.2);")
conn_882.commit()
conn_882.execute("INSERT INTO movie VALUES(103,'Top Gun','Action','English',8.0);")
conn_882.commit()
print("Records inserted successfully");
print("\nDisplaying the table \n")
for rows in conn_882.execute("SELECT * from movie;"):
print(rows)
print("\nPART A\n")
conn_882.execute("UPDATE movie SET rating=rating+0.1*rating;")
print("Rating updated successfully")
for rows in conn_882.execute("SELECT * from movie;"):
print(rows)
print("\nPART B\n")
conn_882.execute("DELETE from movie WHERE Movie_Id=102;")
print("\nRecord Deleted Successfully")
print("\nPART C\n")
for rows in conn_882.execute("SELECT * from movie WHERE rating>3;"):
print(rows)
conn_882.close()
Input/Output:
Problem:
Create a course database with the following fields Product(ID, Prod_name,
Supplier_id,Unit_price,Package,OrderID),OrderItem(ID,Order_id,Product_id,Unit_price,Quantity) using
Foreign key
d. Display the total quantity of every product in the stock
e. Sort the Unit_price based on the supplier_id
f. Display the Product_name along with order_id and supplier_id
Algorithm:
Program:
import sqlite3
conn_882=sqlite3.connect('course.db')
print("Opened database successfully")
conn_882.execute("CREATE TABLE Product(ID INT PRIMARY KEY NOT NULL,Prod_name
VARCHAR,Supplier_id text,Unit_price FLOAT,Package TEXT,order_ID text);")
conn_882.execute("CREATE TABLE OrderItem(ID INT PRIMARY KEY NOT NULL,Unit_price
FLOAT,order_ID text,Product_ID TEXT,quantity INT, FOREIGN KEY(order_ID) REFERENCES
Product(order_ID));")
print("Tables created successfully")
conn_882.execute("INSERT INTO Product VALUES(1,'Car','s01',3450.7,5,'o01');")
conn_882.execute("INSERT INTO Product VALUES(2,'Bike','s02',2450.3,4,'o02');")
conn_882.execute("INSERT INTO OrderItem VALUES(1,3450.7,'o01','p01',8);")
conn_882.execute("INSERT INTO OrderItem VALUES(2,2450.3,'o02','p02',10);")
conn_882.commit()
print("Records Inserted Successfully")
print("Showing Table Product\n")
for rows in conn_882.execute("SELECT * from Product"):
print(rows)
print("\nShowing Table OrderItem\n")
for rows in conn_882.execute("SELECT * from OrderItem"):
print(rows)
print("\nPart A\n")
for rows in conn_882.execute("SELECT Product.Prod_name,OrderItem.quantity FROM
Product,OrderItem where Product.order_ID=OrderItem.order_ID;"):
print(rows)
print("\nPart B\n")
for rows in conn_882.execute("SELECT Unit_Price FROM Product ORDER BY Supplier_id"):
print(rows)
print("\nPart C\n")
for rows in conn_882.execute("SELECT Prod_name,order_ID,Supplier_id FROM PRODUCT"):
print(rows)
conn_882.close()
Input/Output:
Problem:
Write a SQL lite3 statement to create a table named as job including columns job_id,job_title,Min-
salary,Max_salary.job_id column does not contain any duplicate value at the time of insertion
Algorithm:
Program:
import sqlite3
conn_882=sqlite3.connect('week4.db')
print("Opened database successfully")
conn_882.execute("CREATE TABLE job(job_id INT PRIMARY KEY NOT NULL,job_title
text,Min_salary INT,Max_salary INT);")
print("Table created successfully")
conn_882.execute("INSERT INTO job VALUES(01,'Front End Developer',60000,200000);")
conn_882.execute("INSERT INTO job VALUES(02,'Back End Developer',50000,150000);")
conn_882.commit()
print("Records inserted successfully");
print("\nDisplaying the table\n")
for rows in conn_882.execute("SELECT * from job;"):
print(rows)
conn_882.close()
Input/Output:
Problem:
Write a SQL lite3 statement to create a table names as job_history including columns employee_id, start_date,
end_date, job_id and department_id and make sure that, the employee_id column does not contain any
duplicate value at the time of insertion and the foreign key column job_id contain only those values which are
exists in the jobs table.
Algorithm:
import sqlite3
conn_882=sqlite3.connect('week4.db')
print("Opened database successfully")
conn_882.execute("CREATE TABLE job(job_id INT PRIMARY KEY NOT NULL,job_title
text,Min_salary INT,Max_salary INT);")
conn_882.execute("CREATE TABLE job_history(employee_id INT PRIMARY KEY NOT
NULL,start_date text,end_date text,job_id INT,depatment_id INT, FOREIGN KEY(job_id)
REFERENCES job(job_id));")
print("Tables created successfully")
conn_882.execute("INSERT INTO job VALUES(01,'Front End Developer',60000,200000);")
conn_882.execute("INSERT INTO job VALUES(02,'Back End Developer',50000,150000);")
conn_882.execute("INSERT INTO job_history
VALUES(101,'1/Jan/2022','10/May/2022',01,454);")
conn_882.execute("INSERT INTO job_history
VALUES(102,'1/Jan/2021','31/Dec/2021',02,654);")
conn_882.commit()
print("Records inserted successfully");
print("\nDisplaying the table job\n")
for rows in conn_882.execute("SELECT * from job;"):
print(rows)
print("\nDisplaying the table job_history\n")
for rows in conn_882.execute("SELECT * from job_history;"):
print(rows)
conn_882.close()
Input/Output:
Result: Hence the Declarative Programming has been implemented and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Create Simple Client Server Application using TCP Socket where server issue a command which will be executed at
the client slide as a process of remote command execution.
Algorithm:
Client
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Connect the host and port together
Step 6: Close the socket when done
Server
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Bind the port and host
Step 6: Now wait for client connection
Step 7: Establish the connection with the client
Program:
Client.py
import socket # Import socket module
import os
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
cmd1= s.recv(1024)
cmd1=str(cmd1,'utf-8')
print(cmd1)
os.system(cmd1)
s.send(b'Command Executed')
s.close() # Close the socket when done
Server.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c,addr = s.accept() # Establish connection with client.
print ('Got connection from', addr)
c.send(b'id')
print (c.recv(1024))
c.close() # Close the connection
Problem:
Write a Socket-based Python server program that responds to client messages asfollows: When it
receives a message from a client, it simply converts the message into alluppercase letters and
sends back the same to the client. Write both client and serverprograms demonstrating this.
Algorithm:
Client
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Connect the host and port togetherq
Step 6: Close the socket when done
Server
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Bind the port and host
Step 6: Now wait for client connection
Step 7: Establish the connection with the client
Program:
Client.py
import socket
# Import socket module
import os
s = socket.socket()
# Create a socket object
host = socket.gethostname()
# Get local machine name
port =12345
# Reserve a port for your service.
s.connect((host, port))
s.send(b"Sending request to UpperCase this line")
res1 = s.recv(1024)
print(res1)
s.close()
# Close the socket when done
Server.py
import socket
# Import socket module
s = socket.socket()
# Create a socket object
host = socket.gethostname()
# Get local machine name
port =12345
# Reserve a port for your service.
s.bind((host, port))
# Bind to the port
print(f'Server started at{host}:{port}')
s.listen(5)
# Now wait for client connection.
while True:
c, addr = s.accept()
# Establish connection with client.
print ('Got connection from', addr)
req1 = c.recv(1024)
req1 =str(req1,'utf-8')
str1 = req1.upper()
# print(str1)
str1 =bytes(str1,'UTF-8')
c.send(str1)
c.close()
# Close the connection
Input/Output:
Problem:
Write a ping-pong client and server application. When a client sends a ping message to the server, the server will
respond with a pong message. Other messages sent by the client can be safely dropped by the server.
Algorithm:
Client
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Connect the host and port togetherq
Step 6: Close the socket when done
Server
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Bind the port and host
Step 6: Now wait for client connection
Step 7: Establish the connection with the client
Program:
Client.py
# echo-client.py
import socket
# Import socket module
import os
s = socket.socket()
# Create a socket object
host = socket.gethostname()
# Get local machine name
port =12345
# Reserve a port for your service.
s.connect((host, port))
s.send(b"ping")
res1 = s.recv(1024)
print(res1)
s.close()
# Close the socket when done
Server.py
# echo-server.py
# If port is in use try kill -9 $(lsof -t -i tcp:12345)
import socket
# Import socket module
s = socket.socket()
# Create a socket object
host = socket.gethostname()
# Get local machine name
port =12345
# Reserve a port for your service.
s.bind((host, port))
# Bind to the port
print(f'Server started at{host}:{port}')
s.listen(5)
# Now wait for client connection.
while True:
c, addr = s.accept()
# Establish connection with client.
print ('Got connection from', addr)
req1 = c.recv(1024)
req1 =str(req1,'utf-8')
if(req1=="ping"):
c.send(b'pong')
# print(str1)
c.close()
# Close the connection
Input/Output:
Problem:
Write a Socket based program server-client you simulate a simple chat application where the server is multithreaded
which can serve for multiple clients at the same time.
Algorithm:
Client
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Connect the host and port togetherq
Step 6: Close the socket when done
Server
Step 1: import the socket module
Step 2: Create a socket object
Step 3: Choose a local machine name
Step 4: Reserve a part for your service
Step 5: Bind the port and host
Step 6: Now wait for client connection
Step 7: Establish the connection with the client
Program:
Client.py
import socket
ClientMultiSocket = socket.socket()
host ='127.0.0.1'
port =2004
print('Waiting for connection response')
try:
ClientMultiSocket.connect((host, port))
except socket.error as e:
print(str(e))
res = ClientMultiSocket.recv(1024)
print(str(res,'utf-8'))
while True :
Input =input('Hey there: ')
ClientMultiSocket.send(str.encode(Input))
res = ClientMultiSocket.recv(1024)
print(res.decode('utf-8'))
ClientMultiSocket.close()
Server.py
import socket
import os
from _thread import *
ServerSideSocket = socket.socket()
host ='127.0.0.1'
port =2004
ThreadCount =0
try:
ServerSideSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Socket is listening..')
ServerSideSocket.listen(5)
def multi_threaded_client(connection):
connection.send(str.encode('Server is working :)'))
while True:
data = connection.recv(2048)
response ='Server message: '+ data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(response))
connection.close()
while True:
Client, address = ServerSideSocket.accept()
print('Connected to: '+ address[0] +':'+str(address[1]))
start_new_thread(multi_threaded_client, (Client, ))
ThreadCount +=1
print('Thread Number: '+str(ThreadCount))
ServerSideSocket.close()
Input/Output:
Result: Hence the Network Programming has been implemented and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Modify the provided ReverseHelloMultithreaded file so that it creates a thread (let's call it Thread 1). Thread 1
creates another thread (Thread 2); Thread 2 creates Thread 3; and so on, up to Thread 50. Each thread should print
"Hello from Thread <num>!", but you should structure your program such that the threads print their greetings in
reverse order. When complete, ReverseHelloTest should run successfully.
Program:
ThreadCount = 0
def req_thread(num): # define a square calculating function
if num<=0:
return 0
req_thread(num-1)
print(f'Hello from Thread {num+1}! I am Thread {num} :)')
t = time.time()
th1 = threading.Thread(target=req_thread, args=(50, ))
th1.start()
th1.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
Input/Output:
Problem:
To make sure that the producer won’t try to add data into the buffer if it’s full and that the consumer won’t try to
remove data from an empty buffer.
Program:
import threading
import time
# Declaring Semaphores
mutex = threading.Semaphore()
empty = threading.Semaphore(CAPACITY)
full = threading.Semaphore(0)
items_produced = 0
counter = 0
counter += 1
buffer[in_index] = counter
in_index = (in_index + 1)%CAPACITY
print("Producer produced : ", counter)
mutex.release()
full.release()
time.sleep(1)
items_produced += 1
# Consumer Thread Class
class Consumer(threading.Thread):
def run(self):
global CAPACITY, buffer, in_index, out_index, counter
global mutex, empty, full
items_consumed = 0
item = buffer[out_index]
out_index = (out_index + 1)%CAPACITY
print("Consumer consumed item : ", item)
mutex.release()
empty.release()
time.sleep(2.5)
items_consumed += 1
# Creating Threads
producer = Producer()
consumer = Consumer()
# Starting Threads
consumer.start()
producer.start()
Result: Hence the Concurrent Programming has been implemented and compiled
successfully
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Aim : To implement Parallel Programming
Problem:
The Dining Philosopher Problem – The Dining Philosopher Problem states that K philosophers seated around a
circular table with one chopstick between each pair of philosophers. There is one chopstick between each
philosopher.
Program:
import threading
import time
# Since the subclass overrides the constructor, it must make sure to invoke the base
class constructor (
# Thread.__init__()) before doing anything else to the thread.
def __init__(self, index, forkOnLeft, forkOnRight):
threading.Thread.__init__(self)
self.index = index
self.forkOnLeft = forkOnLeft
self.forkOnRight = forkOnRight
def run(self):
while (self.running):
# Philosopher is thinking (but really is sleeping).
time.sleep(30)
print('Philosopher %s is hungry.' % self.index)
self.dine()
def dine(self):
# if both the semaphores(forks) are free, then philosopher will eat
fork1, fork2 = self.forkOnLeft, self.forkOnRight
while self.running:
fork1.acquire() # wait operation on left fork
locked = fork2.acquire(False)
if locked: break # if right fork is not available leave left fork
fork1.release()
print('Philosopher %s swaps forks.' % self.index)
fork1, fork2 = fork2, fork1
else:
return
self.dining()
# release both the fork after dining
fork2.release()
fork1.release()
def dining(self):
print('Philosopher %s starts eating. ' % self.index)
time.sleep(30)
print('Philosopher %s finishes eating and leaves to think.' % self.index)
def main():
forks = [threading.Semaphore() for n in range(5)] # initialising array of semaphore
i.e forks
# here (i+1)%5 is used to get right and left forks circularly between 1-5
philosophers = [Philosopher(i, forks[i % 5], forks[(i + 1) % 5])
for i in range(5)]
Philosopher.running = True
for p in philosophers: p.start()
time.sleep(100)
Philosopher.running = False
print("Now we're finishing.")
if __name__ == "__main__":
main()
Input/Output:
Problem:
Program:
def Reader():
global x
print('Reader is Reading!')
lock.acquire() # Acquire the lock before Reading (mutex approach)
print('Shared Data:', x)
lock.release() # Release the lock after Reading
print()
def Writer():
global x
print('Writer is Writing!')
lock.acquire() # Acquire the lock before Writing
x += 1 # Write on the shared memory
print('Writer is Releasing the lock!')
lock.release() # Release the lock after Writing
print()
if __name__ == '__main__':
for i in range(0, 10):
randomNumber = random.randint(0, 100) # Generate a Random number between 0 and
100
if randomNumber > 50:
Thread1 = thread.Thread(target=Reader)
Thread1.start()
else:
Thread2 = thread.Thread(target=Writer)
Thread2.start()
Thread1.join()
Thread2.join()
Input/Output:
Result: Hence the Parallel and Concurrent Programming has been implemented and
compiled successfully
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Problem:
Algorithm:
Program:
print(fib(5))
Input/Output:
Problem:
Write a Python program to find the numbers of a given string and store them in a list, display the numbers
which are bigger than the length of the list in sorted form. Use lambda function to solve the problem.
Input :
Original string: SOC 23 CTech 5 DSBS8 NWC 56 CINtel 20 5
Input/Output
Numbers in sorted form:
20 23 56
Algorithm:
Input/Output:
Problem:
Write a Python program to sort a given list of strings(numbers) numerically using lambda.
Algorithm:
Program:
def sort_numeric_strings(nums_str):
result = sorted(nums_str, key=lambda el: int(el))
return result
nums_str = ['4','12','45','7','0','100','200','-12','-500']
print("Original list:")
print(nums_str)
print("\nSort the said list of strings(numbers) numerically:")
print(sort_numeric_strings(nums_str))
Input/Output:
Problem:
Write a Python program to calculate the average value of the numbers in a given tuple of tuples using
lambda.
Algorithm:
Program:
def average_tuple(nums):
result = tuple(map(lambda x: sum(x) / float(len(x)), zip(*nums)))
return result
nums = ((10, 10, 10), (30, 45, 56), (81, 80, 39), (1, 2, 3))
print ("Original Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of
tuples:\n",average_tuple(nums))
nums = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
print ("\nOriginal Tuple: ")
print(nums)
print("\nAverage value of the numbers of the said tuple of
tuples:\n",average_tuple(nums))
Input/Output:
Problem:
Write a Python program to find the nested lists elements, which are present in another list using lambda.
Algorithm:
Program:
Problem:
Write a Python program to convert a given list of strings into list of lists using map function.
Algorithm:
Program:
def strings_to_listOflists(str):
result = map(list, str)
return list(result)
print(strings_to_listOflists(colors))
Input/Output:
Problem:
Write a Python program to convert all the characters in uppercase and lowercase and eliminate duplicate
letters from a given sequence. Use map() function.
Algorithm:
Program:
def change_cases(s):
return str(s).upper(), str(s).lower()
chrars = {'a', 'b', 'E', 'f', 'a', 'i', 'o', 'U', 'a'}
print("Original Characters:\n",chrars)
Input/Output:
Problem:
Write a Python program to add two given lists and find the difference between lists. Use map() function.
Algorithm:
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
print("Original list:")
print(nums1)
print(nums2)
result = map(lambda x, y: x + y, nums1, nums2)
print("\nResult: after adding two list")
print(list(result))
result1 = map(lambda x, y: x - y, nums1, nums2)
print("\nResult: after subtracting two list")
print(list(result1))
Input/Output:
Problem:
Algorithm:
Program:
def filter_vowels(letter):
Input/Output:
Problem:
Write a python program to calculate factorial of given number ( use reduce function)
Algorithm:
Step 1:Define a function manually which calculates factorial ,multiplying each value in range 1 to n
Step 2: Pass the number and the manual function in reduce function
Step 3: Print the result of reduce
Program:
import functools
def mult(x,y):
print("x=",x," y=",y)
return x*y
Input/Output:
Result: Hence the Functional Programming has been implemented and compiled
successfully.
18CSC207J-Advanced Programming Practice
SRM Institute of Science & Engineering- Kattankulathur Campus
School of Computing
Program:
Input/Output:
Program:
import sympy as sym
a = (sym.Rational(1, 2)+sym.Rational(1,3))
print(sym.simplify(a))
Input/Output:
Program:
import sympy as sym
x = sym.Symbol('x')
y = sym.Symbol('y')
a = sym.expand((x+y)**6)
print(a)
Input/Output:
Program:
from sympy import *
x = symbols('x')
a = (sin(x)/(cos(x)))
s=trigsimp(a)
print(format(s))
Input/Output:
Program:
Input/Output:
Problem: Develop a python code for to carry out the operations on the given algebraic manipulation for
the given expression a2 −ab+ab−b2=a2−b2 by using the symbolic programming paradigms principles.
Program:
import sympy as sym
a = sym.Symbol('a')
b = sym.Symbol('b')
lhs=sym.simplify(a**2-a*b+a*b-b**2)
rhs=sym.simplify(a**2-b**2)
print('lhs is ',lhs)
print('rhs is ',rhs)
Input/Output:
Problem:
Give the Symbolic program for the expression given below:
a. ∬a 2 da
Program:
Input/Output:
Problem:
Give the Symbolic program for the expression given below:
b.2x+y 2
Program:
import sympy as sym
x = sym.Symbol('x')
y = sym.Symbol('y')
a = sym.simplify(2*x+y**2)
print(a)
Input/Output:
Problem:
Give the Symbolic program for the expression given below:
c. 1/10 + 1/5
Program:
Input/Output:
Problem:
Give the Symbolic program for the expression given below:
d. d/dx(sin(x))
Program:
Problem:
Implement using pyDatalog:
Assume given a set of facts of the form father(name1,name2) (name1 is the father
of name2).
a. Define a predicate brother(X,Y) which holds iff X and Y are brothers.
b. Define a predicate cousin(X,Y) which holds iff X and Y are cousins.
c. Define a predicate grandson(X,Y) which holds iff X is a grandson of Y.
d. Define a predicate descendent(X,Y) which holds iff X is a descendent of Y.
e. Consider the following genealogical tree:
a
/\
bc
/\|
def
What are the answers generated by your definitions for the queries:
brother(X,Y)
cousin(X,Y)
grandson(X,Y)
descendent(X,Y)
Program:
Problem:
Encode the following facts and rules in pyDatalog:
Bear is big
Elephant is big
Cat is small
Bear is brown
Cat is black
Elephant is
gray
An animal is dark if it is
black An animal is dark if it
is brown
Write a query to find which animal is dark and big.
Program:
pyDatalog.create_terms('X,Y,Z,bear,elephant,cat,small,big,brown,black,gray,da
rk')
+big('elephant')
+big('bear')
+small('cat')
+black('cat')
+brown('bear')
+gray('elephant')
dark(X)<=black(X) or brown(X)
print(big(X),dark(X))
Input/Output:
X
-
bear
elephant X
---
cat
Problem:
Input/Output:
X|Y
|-
80 | shyam
70 | carol
85 | priya
45 | raju
90 | ram
X
-
shyam
X
-85
X
raju
Program:
Input/Output:
Problem:
Write a automata code for the Language that accepts all and only those strings
that contain 001
Program:
from automata.fa.dfa
import DFA dfa = DFA(
states={'q0', 'q1', 'q2', 'q3'}, input_symbols={'0', '1'},
transitions={
'q0': {'0': 'q1', '1': 'q0'},
'q1': {'0': 'q2', '1': 'q0'},
'q2': {'0': 'q2', '1': 'q3'},
'q3': {'0': 'q3', '1': 'q3'}
},
initial_state='q0', final_states={'q3'}
)
for i in range(1,4):
num = input("Enter the string :")
if(dfa.accepts_input(num)):
print("Accepted")
else:
print("Rejected")
Input/Output
Problem:
from automata.fa.dfa
import DFA dfa = DFA(
Input/Output
Problem:
Write a automata code for L(M) ={0,1}*
Program:
from automata.fa.dfa
import DFA dfa = DFA(
states={'q0'}, input_symbols={'0', '1'},
transitions={
'q0': {'0': 'q0', '1': 'q0'}
},
initial_state='q0', final_states={'q0'}
)
for i in range(1,8):
num = input("Enter the string :")
if(dfa.accepts_input(num)):
print("Accepted")
else:
print("Rejected")
Input/Output
Problem:
Write a automata code for L(M)=a + aa*b.
Program:
Input/Output
Problem:
Σ * -- accepts all combinations of ‘1’ and ‘0’ including nullstring:
Program:
dfa = DFA(
states={'q0'}, input_symbols={'0', '1'}, transitions={
'q0': {'0': 'q0', '1': 'q0'}
},
initial_state='q0 ',
final_states={'q0 '}
)
for i in range(1,8):
num = input("Enter the string:")
if(dfa.accepts_input(num)):
print("Accepted")
else:
print("Rejected")
Input/Output
Enter the string :101
Accepted
Enter the string :1111
Accepted
Enter the string :34
Rejected