Computer
Computer
Table:STUDENT
Primary key Candidate key Alternate key (array attribute except primary key
TABLE:DETAILS
Roll no. Mark1 Mark2 Mark3 Average
1 5 5 5 5
2 1 2 3 2
Foreign key
Q2) create a table student with the given attributes roll number , name, gender
Ans: create table student (rollno.int, name char(20),gender char(3));
Sum(salary) Min(salary)
18,500 4500
Count(ecode) CONSTRAINTS: condition or check applicable on a field or set of fields with the help of
5 create command constraints are used.
• Unique constraint
• Primary key constraint
• Default constraint
• Check constraint
• Foreign key constraint
• Not null constraint
Eg:
1. Unique constraint: create table student (roll no. int unique, name char (20), gender char (20));
2. Primary key constraint: create table employee (id int primary key, name char (20), branch char
(30),salary int);
3. Default constraint: create table groups (name char (20), albums int, gender char (10) DEFAULT ‘pop’);
4. Check constraint: create table shows (name char (30), ost int, views int CHECK (views >10000));
5. NOT NULL constraint: create table shop (ITEMS char (30), price int NOT NULL, quantity int);
6. Foreign key constraint: create table ITEMS (name char(20),price int, quantity int, due date, customer id
int, foreign key(models) REFERENCES product(models) on delete cascade on update cascade);
TABLE:store
b). To display itemno and item name of those items from store table whose rate is more than rupees 15
ans: select item no., item from store where (rate>15);
c). To display minimum rate of items for each supplier individually as per scode from table
Ans: select min(rate) from store, suppliers where (store. scode = suppliers. scode) group by sname;
5/5/2020
ORDER BY CLAUSE:
EG: select name, city from student order by name;
GROUP BY CLAUSE:
Can be used in select statement to collect data across multiple records and group the results by one or
more columns.
EG: select name, count(*) as “number of employee” from student where (marks>350) group by city;
JOINTS:
It is a query that fetches data from two or more tables based on a condition
EG: select name, age from student details where name=”suga” and student.rollno.=detailsroll no.;
➔right joints and left joints
HAVING CLAUSE:
EG: select name ,age from idols group by album having fans>10,000;
7/5/2020 COMPUTER NETWORKS
It is a collection of inter connected autonomous computing devices to share information or resources.
ADVANTAGE OF NETWORKS:
❖ Sharing of resources(sharing among users programs or applications or data)
❖ Improved communication (enhanced communication: A computer network enables fast.reliable and
secured communication between users) EG: internet email
❖ Cost reduction(sharing resources also reduces communication cost)
❖ Reliability of data
TERMINOLOGIES OF NETWORK:
❖ Client(sends a request)
❖ Server(sharing of data, responses to client requests)
❖ Node (computer devices connected to networking group of nodes are called as workstations)
❖ NIC-network inferface card
➢ Acts as interpreter, helps communication between server and client
➢ MAC=media access control
➢ IP address: internet protocol address
✓ Always unique
✓ To procure IP address of: ”ipconfig” in command prompt(cmd).
8/5/2020
TRANSMISSION MEDIA
❖ Guided /wired ➔twisted pair, coaxial, fibre optic
❖ Unguided/wireless
TRANSMISSION MEDIA
GUIDED UNGUIDED
ED
11/5/2020
1) Internet is a network of physical objects embedded with electronics, software, sensors, and network
connectivity.
2) Client is a host computer that request for some service from a server
3) PAN- personal area network
4) The three wired types of network are twisted pair cable, coaxial cables, fibre optic cable.
5) Network interface unit is a device attached to each of the workstations and a server helps the
workstation to establish are the important connections with the network
6) Bandwidth describes the maximum data transfer.
❖ BRIDGE: bridge is a device that connects two networks together only handles the network which follow
some protocols.
❖ PROTOCOL: rules or procedure to govern network communication
❖ ROUTER: same function as bridge, but it can handle the networks with different protocols. A router is a
network device that forwards data from one network to another.
❖ GATEWAY: network device which connects dissimilar networks.
12/5/2020
it is a utility to view the number of loops and response time to get to a remote system or website.it is a very
similar to ping except that identifies which network pathways it takes along each hop rather than the time it
takes for each packet to return
SPEED TEST: used to check the download and upload spped of network connection
CLOUD COMPUTING:
Cloud computing is internet based computing where shared resources software and information are
provided to computers
It is the technology of distributed data processing in which some scalable information resources and
capacities are provided as a service to multiple external customers
TYPES OF CLOUDS:
❖ Public cloud
❖ Private cloud
❖ Community cloud
❖ Hybrid cloud
➔PUBLIC CLOUD: used by multiple organisations service provided by common portal people using this
service are called as tenants. It is hosted and managed by third party service provides eg. Google
drive,icloud,etc…
➔PRIVATE CLOUD: these are the clouds for exclusive use by a single organisation and typically controlled
managed and hosted in private data centres eg.VPN
➔COMMUNITY CLOUD: these are the clouds used by a group of related organisations who wish to make use
of common cloud computing environment eg. Universities in a given region a community
➔HYBRID CLOUD: it is a combination of private cloud & public cloud
➔INTERNET OF THINGS: it is a technology that connects the things (the smart devices) to the internet over
wired/wireless connections
RFID: radio frequencies identification
Smart technology: automatic doors, temperature adjustment, stopping a vehicle
13/5/2020
Differences between PUBLIC & PRIVATE
PUBLIC PRIVATE
❖ Common cloud service made available to ❖ Consists of computing resources used
Multiple subscribers exclusively owned by one business or
organisations
❖ Cloud resources are owned and operated by ❖ Services and infrastructure are always
third pary cloud service provider and maintained on a private network and the
delivered over the internet hardware and software are dedicated solely
to one organisation
❖ EG: Microsoft azure, google drive, amazon ❖ Used by government agencies, financial
cloud institutions mid and large sized organisations
14/5/2020
WORKING OF AN EMAIL
EMAIL client sending server get mx record of the domain from dns server
SMTP
Recipient inbox receiving server
It is a mechanism of data transfer over internet to provide a safe passage for the transmission of data
It intercepts the data so that third party cannot view the data being transmitted.
15/5/2020
SMTP-simple mail transfer protocol
It is used for sending emails across the internet by default the SMTP protocol works on these ports.
➔port25-the default SMTP non-encrypted port
➔port 465-encrypted port
1)if only one bit of the transmitted data gets changed from 1 to 0 or 0 to1
2)if 2 or more non-consecutive bits when data gets changed
3)if two or more consecutive bits in data get changed from 0 to 1 or 1 to 0
TWO DIMENSIONAL
It is an enhanced.it works with multiple data
0
1 1 0 1 0 0 0 1 1
1
Ex:find rows & column parity row parity
1 1 0 0 1 0 0 1 0
0 0 1 0 0 0 0 0 1
0 0 1 1 1 1 0 0 0
1 0 0 1 0 0 0 1 1
CHECKSUM:
Checksum refers to a sum of data bits calculated from digital data i.e used to ensure the data integrity at the
receiver’s end.
EG:k=4
Data segments with m=8 bits
19/5/2020
1)consider following data units that are to be transmitted along with checksum information
CYBERCRIME: cybercrime is any criminal offense that is facilitated by or involves the use of electronic
communication or information systems including electronic devices
COMPUTER FORENSIC: digital or computer forensic refers to the methods used for interpretation of computer
media for digital evidence.
ONLINE FRAUD: fraud commited using the internet is called as online fraud. few examples are non-delivered
goods, stealing information, non-existent companies, etc
CYBERLAW: cyberlaw is a generic term which refers to all the legal and regulatory aspectives of internet and the
worldwide web.
3/6/2020
IP address
Internet protocol version(IPV)
(i)IPV4
(ii)IPV6
(i)IPV4 addresses are 32 bits long and it is the most widely internet protocols used to contact devices to the
internet
(ii)IPV6 addresses are 128 bits
IPV4:
69 89 31 226
01000101 01011001 00011111 11100010
1st octet 2nd octet 3rd octet 4th octet
IPV6:
0021 : 0001 : AC10 :030A :0000 :0000 :0000:9878
ADDRESS SIZE:
IPV4:32-bits
IPV6:128-bits
ADDRESS FORMAT:
IPV4:4 segments, dotted decimal notation
IPV6:8 segments, hexadecimal notation
NUMBER OF ADDRESSES:
IPV4:232
IPV6:2128
ROUTING: it is a process of efficiently selecting a path in the network along with data packets will travel to their
destination
A router maintains a table called routing table that stores routing table that stores routing information based on
which the router determines the best path to a network. Routers are not concerned with host they only deal
with networks and the best path to reach them
NOTE:
ICP is a connection-oriented protocol
IP is a connectionless protocol responsible for providing addresses of each computer & performing routing
UDP (user datagram protocol) it is a connection less protocol
Fetchmany(_
Eg. data=cursor.fetchmany(4)
Count=cursor.rowcount
Print(“total no. of rows retrived from resultset:”,count)
For row in data:
Print(row)
Fetchone()
data=cursor.fetchone()
count=cursor.rowcount
print(“total no.of rows retrived from resultset:”,count)
print(data)
print(“\n again fetching one record”)
data=cursor.fetchone()
count=cursor.rowcount
print(“total no. of rows retrived from resultset:”,count)
print(data)
5/6/2020
Creating a table
Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user=”learner”,passwd=”past”,database=”test”)
Mycursor=mydb.cursor()
Mycursor.execute(“create table cust(name varchar(25),address varchar(35)”)
Mydb.commit()
6/6/2020
2)to check weather the database has been created or not using python interface
[in sql=show<databse>]
Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user’”learner”,passwd=”fast”)
Mycursor=mydb.cursor()
Mycursor.execute(“show school”)
For a in mycursor:
Print(a)
3)roll no.,name,age,city,marks:
Import mysql.connector
Mydb=mysql.connector.connect(host=”local host”,user=”learner”,passwd=”fast”,database=”school”)
Mycursor=mydb.cursor()
Mycursor.execute(“create tabe school(roll no int,name char(30),age int,city char(10),marks int)
Mydb.commit()
5)To display all the records of the student table using python
Import mysql.connector
Mydb=mysql.connector.connection(host’”localhost”,user=”learner”,passwd=”slow”,database=”school”)
Mycursor=mydb.cursor()
Count=cursor.rowcount()
Print(“total number of rows retrived in result”,count)
For row in data:
Print(row)
elif x==3:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
sql="update student set name="I-hope" where roll no=1"
mycursor.execute()
mydb.commit()
print(mycursor.rowcount,"record inserted")
elif x==4:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
n="delete from student where name="kim""
mycursor.execute(n)
mydb.commit()
print(mycursor.rowcount,"record deleted")
elif x==5:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
elif x==6:
break
9/6/2020
1)which method is used to retrive all rows and which method is used to retrieve single row?
Ans: fetchall()method = all rows
Fetchone() method = single row
2)what is the name of a special control structure that facilitates the row by row processing of records in the
result set during python mysql connectivity
Ans: database cursor
10/6/2020
1)which command is used for cleaning up the environment?
Close()
2)a resultset is an object that is returned when a cursor object is used to carry a form of query a table
True
11/6/2020 RECURSION
RECURSION
Recursion is a technique for solving a large computational problem by repeatedly applying the same procedures
to reduce it to successively smaller problems.
NOTE
In iteration the code is executed repeatedly, using the same memory space that is the memory space allocated
once is used for each pass of the loop
In recursion since it involves function call in each step fresh memory is allocated for each recursive call hence
the recursive function runs slower than iteration
Program:
#function to find the factorial of a number using recursion
def recur_factorial(n):
if n==1:
return n
else:
return n*recur_factorial(n-1)
if num<0:
print("sorry,factorial for a negative number does not exist")
elif num==0:
print("the factorial of 0 is 1")
else:
print("the factorial of",num,"is",recur_factorial(num))
5*recur_factorial(5-1)
4*recur_factoria(4-1)
3*recur_factoria(3-1)
2*recur_factoria(2-1)
2*1=2
3*2=6
4*6=24
5*24=120
Project 2:
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
for i in range(nterms):
print(recur_fibo(i))+
12/6/2020
WRITING A RECURSIVE FUNCTION:
Every recursive function must have two cases;
i)The recursive case(inductive case)
ii)The base case(stopping case),always required.
The base case is a small problem that we know how to solve and is a case causes recursion to end
The recursive case is a general one where it calls the same function recursively
The base case is the keys whose solution is pre known and it is used without computation
13/6/2020
1)write a python function to sum all the numbers in a list
Sample list=[4,6,3,5,6]
sum=0
if i in range(len(samplelist)):
sum=sum+samplelist[i]
print(sum)
def sum(sl):
total=0
for in sl:
total=total+i
return(total)
print(total)
16/6/2020
Ex 6.1
10 12 14 21 23 28 31 37 42 44 49 53
0 1 2 3 4 5 6 7 8 9 10 11
ary=[12,15,21,28,32,33,36,43,45]
item=int(input("enter search item:"))
res=binsearch(ary,item,0,len(ary)-1)
if res>=0:
print(item,"found at index",res)
else:
print("sorrry",item,"not found in the array")
Ans:def binsearch(ar,key):
low=0
high=len(ar)-1
while low<=high:
mid=int((low+high)/2)
if key == ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
else:
return-999
ar=[12,15,21,25,28,32,33,36,43,45]
item=int(input("enter search item:"))
res=binsearch(ar,item)
if res>=0:
print(item,"found at index:",res)
else:
print("sorry",item,"not found in array")
Data visualisation refers to the graphical or visual representation of information and data using visual elements
like charts, graphs and maps etc.. data visualisation is immensely useful in decision making
Impoting pyplot:
Import matplotlib.pyplot
Import matplotlib.pyplot as pl
Numpy array is simply a grid that contains values of same homogeneous type
22/6/2020
Creating arrays with numerical range using arrang()
<arrayname>=numpy.arrange([start,]stop[,step][,dtype])
Eg: arr6=np.arrange(1,7,2,np.float)
Arr6
Array([1,3,5],dtype=float 32)
Eg: al=np.limspace(2.5,5,6)
Al
Array([2.5,3,3.5,4,4.5,5])
Linestyle(or)ls=[‘solid’]’dashed’,’dashdot’,’dotted’]
Eg.plt.plot(x,a,linewidh=2,linestyle=’dashed’)
Plot()method syntax:
Plot(<data>[,<data 2>] [,….<colorcode and markertype>] [,<linewidth>] [,<linestyle>] [,<marker>]
[,<markersize>] [,<markeredgecolor>]
#linechart
import matplotlib.pyplot as plt
x1=[10,20,30]
y2=[20,40,10]
x2=[10,20,30]
y2=[40,10,30]
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('two or more lines with different widths and colors with suitable legends')
plt.plot(x,y,color='blue',linewidth=3,label='line1-width-3')
plt.plot(x2,y2,color=”red”,linewidth=5,label=’line2-width-5’)
plt.legend()
plt.show()
24/6/2020
Bar chart
A bar graph is a graphical display of data using bars of different height
Ex:
import matplotlib pyplot as plt
cities=['delhi','mumbai','bangalore','hyderabad']
population=[23456123,20083104,18456123,13411093]
plt.bar(cities,population)
plt.xlabel('cities')
plt.ylabel('population')
plt.show()
ex:
1) the python library providing interface and functionality for 2D graphics is matplotlib
2) line charts are creatd by using plot() function
3) pyplot is a collection of methods.
25/6/2020
CREATING A HORIZONTAL BAR CHART:
Horizontal bar chart is created by barh() function
Eg:
import matplotlib pyplot as plt
cities=['delhi','mumbai','bangalore','hyderabad']
population=[23456123,20083104,18456123,13411093]
plt.barh(cities,population)
plt.xlabel('population')
plt.ylabel('cities')
plt.show()
PIE CHART
The pie() function plots a single data only. It will calculate the share of individual elements of the data range being
plotted vs the whole of the data range. The default shape of a pie chart is oval but you can always change to circle
by using axis() of plot, sending ”equal” as argument to it. That is, issue following command before you use pie()
function : matplotlib.pyplot.axis(“equal”)
Ex:
Import matplotlib.pyplot as plt
Contri=[17,8.8,12.75,14]
Plt.pie(contri)
#Ex 1
import matplotlib.pyplot as plt
stream= ['medical','non-medical','commerce with maths','commerce with IP','humanities']
students=[32,41,55,60,50]
colors=['red','gold','yellowgreen','blue','lightcoral']
explode=(0.1,0,0,0,0)
plt.pie(students,explode=explode,labels=stream,colors=colors)
plt.title("grouping of students on the basis of allocated streams")
plt.show()
#Ex 2
import matplotlib.pyplot as plt
labels= 'python','c++','ruby','java'
sizes=[215,130,245,210]
colors=['gold','yellowgreen','lightcoral','light skyblue']
explode=(0.1,0,0,0,0)
plt.pie(sizes,explode=explode,labels=labels,colors=colors,shadow=True,startangle=140)
plt.axis("equal")
plt.show()
Anatomy of a chart
Anatomy generally refers to the study of bodily structure or various parts of a plot that you can create using pyplot.
26/6/2020
2)By default legends are shown in right upper corner part of the plot.
6)You can save the figure by using pyplot savfig in which format
➔ saved in .pdf, .png, .eps
29/6/2020
1)Consider the following zone-width sales in crores and draw a pie chart by using pyplt interface and display labels
Sales=[234,345,547,287,198]
Zones=[“EAST”,”WEST”,”NORTH”,”SOUTH”,”CENTRAL”]
2)Write a program to plot a bar chart in python to display the result of a school for five consecutive years
YEARS=[2015,2016,2017,2018,2019]
List of pass percentage(p)=[98.50,70.25,55.20,90.5,61.50]
DATA STRUCTURE
1) simple data structures:
(i)array or linear lists
2) compound data structure:
(i) linear data structures:
(a) stack, (b)queue, (c)linked list
(ii)non linear data structure:
(a) tree
stacks: stack data structure refers to the lists stored and accessed in a special way, where LIFO (last in first out)
technique is followed in stack, insertions and deletions take place only at one end, called the top.
QUEUES: queues data structures are FIFO(first in first out) lists, where insertions take place at the ‘rear’ end of
the queues and deletions take place at the ‘front’ end of the queues.
Ex: stack: 4 50 NO
TOP 3 40 INSERTION
2 30 TOP++ VALID IF IT IS
1 20 TRUE
0 10
ONLY 50 CAN BE RESTORED HENCE IT FOLLOWS LIFO WHEN 50 IS REMOVED 40 BECOMES TOP
Ex: Queue
0 20 30
FRONT REAR
(DELETION) (INSERTION)
FRONT
1/7/2020
18 TOP
32 32 32
top=none (b)push ‘32’ (c) push ‘18’ (d) pop 1 element
(a)stack empty
29, element popped
29 TOP
32 32 TOP
(e)push ‘29’ (f)pop 1 element
2/7/2020
PROGRAM: python program to implement stack operations
def isEmpty(stk):
if stk==[ ]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top =len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack Empty")
else:
top=len(stk)-1
print(stk[top],"<==top")
for a in range(top-1,-1,-1):
print(stk[a])
Stack= [ ]
top=None
while True:
print("The Stack Operations are:")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Push(Stack,item)
elif ch==2:
item=Pop(Stack)
if item=="Underflow":
print("Underflow!EmptyStack")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(Stack)
if item=="Underflow":
print("Underflow!EmptyStack")
else:
print("Topmost item is",item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice")
3/7/2020
STACK APPLICATION
1)Reversing a line
2)Polished string
Expressions in Infix, Prefix, Postfix notations:
a) Infix= A+B
Prefix= +AB
Postfix= AB+
b) Infix= (A-C) X B
Prefix= X – ACB
Postfix= AC – BX
Eg: Convert A+(BXC) to postfix ➔ postfix= ABCX+
Eg: Convert (A + B) / (C - D) to postfix
➔(AB+) / (CD-)
➔AB+CD-/
(BODMAS RULE)
Brackets ()
Of exp
DECREASES
Division ÷ or /
Multiplication X
Addition +
Subtraction -
EG:
((A + B) X C / D + E ^ F) / G to Postfix (* = X)
➔((AB +) X C / D + (EF) ^) / G
➔((AB +) X C / D + (EF^)) / G
➔((AB+C) X / D + (EF^)) / G
➔((AB + C X D /) + (EF ^) / G
➔(AB + C X D / EF ^ + G /
➔AB + C X D / EF ^ + G /
4/7/2020
EG:
A + (B X C – (D / E ^ F) X G) X H to postfix (* = X)
➔(A + (B X C - (D / E ^ F) X G X H)
➔(A + (BC X – (DE / ^ F) X G X H)
➔(ABC X + - (DEF ^ /) X G X H)
SYMBOL SCANNED STACK EXPRESSION
( (
A ( A
+ (+ A
( (+( A
B (+( AB
* (+(* AB
C (+(* ABC
- (+(- ABC*
( (+(-( ABC*
D (+(-( ABC*D
/ (+(-(/ ABC*D
E (+(-(/ ABC*DE
^ (+(-(/^ ABC*DE
F (+(-(/^ ABC*DEF
) (+(- ABC*DEF/
* (+(-* ABC*DEF^/
G (+(-* ABC*DEF^/G
) (+ ABC*DEF^/G*-
* (+* ABC*DEF^/G*-
H (+* ABC*DEF^/G*-H
) ABC*DEF^/G*-H*+
NOTE:
1)When highest priority operator enters the stack the already existing lowest priority operator stays in the stack.
2)When the lowest priority operator enters the stack the already existing highest priority operator comes out of
the stack going to the expression.
3)When a close bracket occurs, LIFO is followed the first out operator goes to the expression.
4)If some priority operator enters the existing some priority operator it goes to the expression.
7/7/2020
1)(A * (B + (C + D) * (E + F) / G * H)
SYMBOL SCANNED STACK EXPRESSION
( (
A ( A
* (* A
( (*( A
B (*( AB
+ (*(+ AB
( (*(+( AB
C (*(+( ABC
+ (*(+(+ ABC
D (*(+(+ ABCD
) (*(+( ABCD+
* (*(+(* ABCD+
( (*(+(*( ABCD+
E (*(+(*( ABCD+E
+ (*(+( ABCD+E
F (*(+*(+ ABCD+EF
) (*(+* ABCD+EF+*
/ (*(+/ ABCD+EF+*
G (*(+/ ABCD+EF+*G
) (* ABCD+EF+*G/+
* (* ABCD+EF+*G/+*
H (* ABCD+EF+*G/+*H
) (* ABCD+EF+*G/+*H*
+ * /
3 3 = 4 ˭ 5 5
2 2 2 5 5 20 20 20 4
The priority order of NOT and OR
10/7/2020
QUEUES:
Capacity=4
Ex) (i) queue empty (ii) enqueue ‘a’ (iii) enqueue ‘b’ (iv) enqueue ‘c’ (v)dequeue (vi)enqueue ‘d’
(vii) enqueue ‘e’ (viii)dequeue (ix)dequeue (x)dequeue (xi)dequeue
0 1 2 3
(i)
(ii) a
(iii) a b
(iv) a b c
(v) b c
(vi) b c d
(vii) b c d(OVERFLOW)
(viii) c d
(ix) d
(x)
(xi) UNDERFLOW
11/7/2020
PROGRAM TO IMPLEMENT QUEUE OPERATIONS:
def cls():
print("\n"*100)
def isEmpty(qu):
if qu==[ ]:
return True
else:
return False
def Enqueue(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1
def Dequeue(qu):
if isEmpty(qu):
return "Underflow"
else:
item=qu.pop(0)
if len(qu)==0:
front=rear=None
return item
def Peek(qu):
if isEmpty(qu):
return "Underflow"
else:
front=0
return qu[front]
def Display(qu):
if isEmpty(qu):
print("Queue Empty")
elif len(qu)==1:
print(qu[0],'<==front rear')
else:
front=0
rear=len(qu)-1
print(qu[front],"<==front")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<==rear")
queue= [ ]
front=None
while True:
print("The Queue Operations are:")
print("1.Enqueue")
print("2.Qequeue")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Enqueue(queue,item)
input("press ENTER to continue")
elif ch==2:
item=Dequeue(queue)
if item=="Underflow":
print("Underflow!EmptyQueue")
else:
print("Dequeue-ed item is",item)
input("press ENTER to continue")
elif ch==3:
item=Peek(queue)
if item=="Underflow":
print("Queue is Empty")
else:
print("Frontmost item is",item)
elif ch==4:
Display(queue)
input("press ENTER to continue")
elif ch==5:
break
else:
print("Invalid choice")
input("press ENTER to continue")
13/7/2020
Types of queues:
1)Circular queues:
Circular queues are the queues implemented in circular form rather than a straight line.
APPLICATIONS OF STACK:
1)Reverse of a sequence
2)Infix to postfix conversion
APPLICATIONS OF QUEUE:
1)Resource sharing
while True:
print("1.Push")
print("2.Pop")
print("3.Dispaly")
ch= int(input("Enter your choice(1-3):"))
if (ch==1):
a=input("Enter any number:")
s.append(a)
elif (ch==2):
if (s== [ ]):
print("Stack Empty")
else:
print("Deleted element is:",s.pop())
elif (ch==3):
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
print(s.reverse())
else:
print("Invalid Choice")
input("press Enter to continue")
16/7/2020
Eg: Implementing list as a queue
a=[ ]
while True:
print("1.Insert")
print("2.Delete")
print("3.Dispaly")
ch= int(input("Enter your choice(1-3):"))
if (ch==1):
b=input("Enter any number:")
sa.append(b)
elif (ch==2):
if (a== [ ]):
print("Queue is Empty")
else:
print("Deleted element is:",a.pop())
elif (ch==3):
l=len(a)
for i in range(0,1):
print(a[i])
else:
print("Invalid Choice")
input("press Enter to continue")
def celsius():
x=int(input("Enter the value to convert into celsius:"))
c=(x-32)*(5/9)
print("fahrenheit==>celisius=",c)
def fahrenheit():
y=int(input("Enter the value to convert into fahrenheit:"))
f=(y*(9/5))+32
print("celsius==>fahrenheit=",f)
2)
Eg: a=1
def f():
a=10
print(a)
output : 1
➔ for k in range(10,20):
while k % 5 == 0:
print(k)
20/7/2020
HTTP requests are used on web by web clients for communicating with web servers. HTTP requests are
made in two forms:
(i)GET REQUEST: This HTTP request is made to request data from the server. This request sends a URL
to the webserver and the webserver returns the asked webpage’s HTML, which the web client displays
in the browser as a webpage.
(ii)POST REQUEST: This HTTP request is made to submit data to be processed to the webserver. This
request is made by the web clients when it has data(filled via forms or for upload), which the
webserver has to process. The POST request carries the data from web client to the webserver.
Easy all
Easy all
Register
Sell
Work
Manage.py
ii)Name the files that are found in project web application folder
ans) __init__.py settings.py urls.py wsg.py
21/7/2020
1)What is the command to install Django?
Ans: pip install Django
5)Which file is used to manage django project and administrative tasks are performed by it?
Ans: manage.py
9)Whenever a web client have to access a webpage, it makes a HTTP GET request and sends URL of the
webpage.
27/7/2020
28/7/2020
Random module
Command: import random
Exercise 4.2
What could be the minimum possible and maximum possible numbers by following code?
import random
print(random.randint(3,10)-3)
Ans: maximum possible number=7
Minimum possible number=0
29/7/2020
Urllib functions
(i)urllib.request.urlope(<URL>)
(ii)<urlopen’s return val>.read()
(iii)<urlopen’s return val>.getcode()
(iv)<urlopen’s return val>.headers
(v)<urlopen’s return val>.info()
(vi)<copy>.geturl()
import webbrowser
Program to get HTTP request information from the given URL and open it within the python
program.
import urllib
import webbrowser
import urllib.request
weburl=urllib.request.urlopen('http://www.google.com')
html=weburl.read()
data=weburl.getcode()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info
print("The URL is",url)
print("HTTP Status code is:",data)
print("Headers returned \n",hd)
print("the info() returned : \n",inf)
print("NOW opening the URL",url)
webbrowser.ope_new(url)
import urllib.request
Data=urllib.request.urlopen(‘http://www.google.com’)
Print(Data.read())
30/7/2020
CIRCLE MODULE:
import math
def area(radius):
return math.pi*radius **2
def circumference(radius):
return 2*math.pi*radius
RECTANGLE MODULE:
import math
def area(x,y):
return x*y
def rectangle(x,y):
return 2*(x+y)
__mainprogram__
import circle
import rectangle
elif(x==3):
width=int(input("enter the width:"))
length=int(input("enter the length:"))
print("the area of rectangle is",rectangles.area(width,length))
elif(x==4):
width=int(input("enter the width:"))
length=int(input("enter the length:"))
print("the area is ",rectangle.perimeter(width,length))
elif(x==5):
exit()
SECOND PROGRAM:
#rect.py
class rectangle:
def __init__(self):
print("rectangle")
def area(self,length,width):
self.l=length
self.w=width
print("area of rectangle is :",self.l*self.w)
#sq.py
class square:
def __init__(self):
print("square")
def area(self,side):
self.a=side
print("area of square is:",self.a*self.a)
#tri.py
class triangle:
def __init__(self):
print("triangle")
def area(self,base,height):
self.b=base
self.h=height
ar=(1/2)*self.b*self.h
print("area of triangle is:",ar)
#main.py
from module import rect
from module import sq
from module import tri
3/8/2020
Newobject=ClassName()
There is a special function named __init__() that gets called whenever we create a new instance of a
class. It exists by default even though we don’t see it. However we can define our own __init__()
function inside the class,
➔self.new_variable=new_variable
Model=”Delorean”
Color=”silver”
Mpg=88
➔class car(object):
Condition=”new”
def __init__(self,model,color,mpg):
self.model=model
self.color=color
self.mpg=mpg
my_car=car(“Delorean”,”silver”,88)
my_car.condition
4/8/2020
1)We can use python source file as a module by exciting an import statement.
2)dir() function when applied to a module gives us the name of all that is defined in the module.
1)What is possible outputs are expected to be displayed on at the time of execution of the program
from the following code:
import random
ar=[20,30,40,50,60,70]
from= random.randint(1,3)
to= random.randint(2,4)
for k in range(from,to+1):
print(ar[k],end=”#”)
Ans: 30#40#50#