Pyth
Pyth
IMPORTANT
Python mei dynamic casting hota hai, i.e depending on the data the
datatype is decided and changes the type as per need.
Datatypes in python:- int,float,str,bool,complex.
Syntax: grammar of programming.
*****That resume does not exist***** resume maker according to your job
description
Python follows loose syntax: more than one ways of writing code(syntax)
Semi-colon end of the instruction
data=bool(input("Enter:"))
print(data,type(data))
is code mei presence of information will be true and absence of
information will be false.
No increment and decrement operators in python
~ 1.reversal of sign
2.do -1
~10 = -11
Sequence, branch, loop programming in 3no pe khada hai
Oops: approach of thinking from bottom to top
First thinking about output, then following the process and at the end work
with the input
Python does not have do while loop
Whiledigit saperation, infinite loop, menu driven
For auto iteration, list, string, patterns, series.it does not support
fraction based integer
While loop is faster.
Else under a loop will only execute if the loop is not interrupted
Eg:
i=0
while(i<5):
print(i)
if i==3:
break
i+=1
else:
print("normally executed")
output:
0
1
2
3
How python can handle a do while loop?
Ansusing infinite while and giving a exit condition(similar to word)
Match case is important
sum=0
Tea,Coffee,Water=0,0,0
print('1.Tea (10) \n2.Coffee(20) \n3.Water(15)')
while True:
choice=int(input('Enter your choice:'))
if choice==1:
sum+=10
Tea+=1
elif choice==2:
sum+=20
Coffee+=1
elif choice==3:
sum+=15
Water+=1
elif choice==0:
break
else :
print("invalid choice")
print('Tea:',Tea)
print('Coffee:',Coffee)
print('Water:',Water)
print('profit:',sum)
DAY 2
Data structrures: way of storing data such that it can be accessed faster and
better
1.Conventional : stack, queue, linked list, graph
2.Prinitive data structures: list, tuples, set, dictionary heterogenous(can store
any and multiple types of data)
List [], duplicates allowed, index access, dynamic(increase or decrease in size) i.e
mutableused by programer
Tuple (), duplicates allowed, index access, Static(immutable)python uses
maximum for security since cannot be modified.
Set{}, no duplicates, no indexed access, dynamicused for filteration, union,
intersection, difference and symmetric difference type works
Dictionary {k:v}, key cannot be duplicated, value can be duplicated, dynamic,
key based accessused in maps
Dynamic(run time pe size increase ya decrease kar sakte ho)(mutable)
append(x) will add a single element, extend (l) will append an entire list
a.insert(index,value)
index>list(+ve) will add at extreme right
index>list(-ve) will add at extreme left
flat the list:
x=[]
for i in m:
for j in i:
x.append(j)
print(x)
efficient way:
m3=[]
for i in m:
m3.extend(i)
print(m3)
l.remove(x) removes element on its first occurrence and gives error if element
not present
l.pop(i) removes element at the given index, if index not given… removes the
last element. If index given is not present then there will be a error.
l.clear() removes all data
sorted is temporary, sort() is permanent
sorted returns the result.
Sort()it doesnot return anything makes changes internally.
#keep accepting element form user until blank is given,add all elements in list, print sum
of all numbers:
a=[]
while True:
x=(input())
if x=="":
break
else:
a.append(int(x))
print(a)
print(sum(a))
#keep accepting element form user until blank is given,add all elements in list,print all
elements greater than average
a=[]
while True:
x=(input())
if x=="":
break
else:
a.append(float(x))
avg=sum(a)/len(a)
print(avg)
for i in a:
if i>avg:
print(i)
N elements ka question aya toh list ka use hona hi hai
Tuple:
It cannot change values inside of it, but we can replace an entire tuple
Tuple ke andaragar list hogi toh list apni properties nahi chhodti... list within tuple
is still dynamic.
T=(10,20,[30,34])
T[2] mei changes ho sakte hai.
Set: sets are unordered
Union |
Intersection &
Symmentric diff ^
Diff -
Set can be auto-iterated but cannot be accessed by index
#print count of each unique element in sorted order
l=[11,22,11,33,44,22,66,77,99,11,22,33]
ul=sorted(set(l))
print(ul)
for i in ul:
print(i,"-->",l.count(i))
Dictionary:
#read a number and print in words
words={1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}
no=int(input())
tno=0
while no>0:
digit=no%10
no=no//10
tno=tno*10+digit
while tno>0:
digit=tno%10
tno=tno//10
print(words[digit],end=" ")
#rotating array
l=[11,22,33,44,55]
for i in range(len(l)):
x=l.pop(0)
l.append(x)
print(l)
l=[11,22,33,44,55]
for i in range(len(l)):
x=l.pop()
l.insert(0,x)
print(l)
error: any state due to which one cant have normal flow of code
exception: reporter of the error
exception handling: Trying to continue either alternate or normal flow of code in
the presence of error
try: suspicious code
except: code to report handle error
else: code that will run iff no error
finally: code will execute in all situation
Day 3
Functions: code written away from the script when needed called from the
script when needed, when called, control gets transferred code gets
executed and comes back to the script.
Reuse, modular programming and faster development advantages of
functions
By default in python all functions are overloaded and hence polymorphic
in nature wrt datatype.
#iterator
#iterate over a sequnce list,tuple,string
#iter() & next()
#generator
#will iterate over generated value on runtime
#function that stops at regular interval
# ex:tools controls to change—image editing
#function that runs in intervals
Yield where to stop
Function polymorphism
#decorator
#reuses old function with new cover
Old function + new Wrapper new functionality
new way of calling
Function polymorphism
OOPS:
It is thinking method that starts with objective (o/p), process (to get o/p), input. It
is bottom to top approach. More natural hence faster and hence maximum used.
Implementation happens on the basis of class and object
Class vs object
Class:
Virtual idea,frame work, has properties, has operations on operations
Object:
Physical entity,implemented code, has values, has methods to access
values
Jab sirf class bana rehta hai…tab koi memory allocation nahi hoti…Memory
allocation tab hi hoti hai jab object banta hai.
class Employee:
#constructor
def __init__(self,id,name,exp):
self.id=id
self.name=name
self.exp=exp
yash=Employee(1,"Yash",4)
print(yash.id)
Class <Name>:
Methods:
Data:
#abstarction ----visibilities
# public :default,anyone can access from anywhere
#<var>
#private :hidden,not reflected but if known can access
_<var>
# strong private:truly secure,cant access outside class
__<var>
Access specifiers:
1.public self.property
2.privateself.__property..it is accessible only in the same class..not even its
childclass
3.protected self._property ..it is accessible in its child class too
class mobile:
def __init__(self,brand,price,color,imei):
#public properties
self.brand=brand
self.price=price
self.color=color
self.__imei=imei
m1=mobile("Apple",10000,"White",123456789)
print(m1.__imei)
this code will give error:
Traceback (most recent call last):
File "C:\Users\ATHRVA\OneDrive\Desktop\tnp\code\oops.py", line 109, in
<module>
print(m1.__imei)
^^^^^^^^^
AttributeError: 'mobile' object has no attribute '__imei'
m1=mobile("Apple",10000,"White",123456789)
print(m1.getImei())
It will display imei
Inheritance:
To inherit, use super().__init__(brand,price)
class SmartPhone(Phone):
def __init__(self,brand,price,camera):
super().__init__(brand,price)
self.camera=camera
s=SmartPhone("Apple",100000,"64mp")
print(s.brand)
parent methods are accessible…no need to use super keyword for them
A language is object oriented when it follows the concepts of oops i.e the 4
pillars
Java is not a purely object oriented programing language
Python is a purely object oriented language
Types of inheritance:
Single level : 1:1 and 1:M (parent:child)
Multi level : 1:1:1:1…
Multiple Inheritance : M:1 if 2 of the parents have same property then…the
child inherits the one that is passed first.
Polymorphism:
2 types of polymorphism:
1.compile-time polymorphism Method overloading Python doesnot support
method overloading.
2.run time polymorphism Mehod over-riding
class Parent:
def walk(self):
print("Parent is walking...")
class Child(Parent):
def walk(self):
print("Child is walking")
c=Child()
c.walk()
output:
C:\Users\ATHRVA\AppData\Local\Programs\Python\Python311\python.exe C:\Users\
ATHRVA\OneDrive\Desktop\tnp\code\oops.py
Child is walking
If same method name with different functionalities in parent and child classes…
then the method 0verriding function says that the method in the child is
executed if the object of child is created with and the method with same name is
called.
Operator overloading:
Decorators:
Abstraction:
From abc import ABC, abstractmethod
Abstract class ka object nahii ban sakta
Class bhub(ABC): This Is a abstract class
from abc import ABC,abstractmethod
class A(ABC):
@abstractmethod
def greet(self):
pass
agar @abstract method se decorator hoga toh voh method abstract method hai
methods mei sirf pass hi hoga…there will be no body in a abstract method
1. We can make a class 'abstract' by implementing one or more abstract
methods in it.
2. We cannot create objects of an abstract class
3. An abstract class can have abstract as well as non-abstract methods in it.
4. Abstract methods does not have any body.
5. A child class of abstract class is also abstract.
6. To make a child class non-abstract, we have to override all abstract methods.
Day 5 (DSA)
1.Static DS:
Allocation of memory done at compile time
Easy to give/get
Static in nature(Cannot change)
Less memory efficient
2.Dynamic DS:
Allocation done at run time
Needs commands and clearity
Changes as per need
More memory efficient
1.Linear:
Data accessed one after another
Simple to code
Slow to access
Stack, queue, linked-list
2.Non-linear:
Data accessed directly of guided
Complex to code
Fast to access
Tree, graph
Data structures: Way of storing data in such a manner that accessing and
updating becomes easy/faster.
Stack:
One sided
LIFO
Operations:
1. createStack(size)
2. push(e)
3. pop(): e
4. peek():e
5. isEmpty():Boolean
6. isFull(): Boolean
7. printStack()
initially: top=-1
pushtop +=1 stack[top]
if top=maxSize-1isFull:true
Applications of stack:
1. Recursion
2. In expression conversion and evaluation
3. In redo/undo
4. In graph traversal(DFS)
5. Wellness check {{{ }}}
6. Convert decimal to binary
Why there is infix prefix and postfix infix for humans, prefix for software and
postfix for hardware
Do practice of all infix,prefix and postfix operations
1.a*b/c-d*e
postfix:
ab*/c-d*e
A/c-d*e ab*c/-d*e
A-d*eA-de* A-BAB- ab*c/de*-
Prefix:
2.(a+b)/(c-d*e)/f
Postfix:
(ab+)/(cde*-)/f
ab+cde*-//f ab+cde*-/f/
prefix:
+ab/(c-*de)/f
+ab/-c*de/f
//+ab-c*def
Linked list
Linked list is considered as the most powerful datastructure
Applications:
1. Data supply chain
2. Games- Staging, progress, kinematics
3. Used in creating any datastructure hence most powerful
4. Dynamic memory allocation free space allocation/allotment
5. Polynomial addition
Tree
Applications:
1. Hierarchical storage
2. Autocorrect
3. Autocomplete
4. Storing and searching large scale data
5. Load balancing
Graphs
Applications:
1.
Queue:
FIFO
Rear --------------------------------- Front
Double ended(front:remove, rear:append)
Types:
Linear pure fifo
Circularuses limited space for unlimited access by reuse
Prioityworks in RTOS(Real time operating system)
Double endedworks from both side(entry and exit cab be done through
both sides)
Applications:
Scheduling of tasks/job
Buffering message, media, update
If front > rear: queue is empty
Rear=(Rear+1)% maxSize
Front=(Front+1)%maxSize
Enqueuecount+1
Dequeuecount-1
If count==0 empty
If count==maxSize full
Priority queue:
Does not follow lifo/fifo follows only priority)
Used in RTOS(real time operating system)
Removes element on basis of priority
Dequeue() max priority task comes out
Circular:
Doubly:
Doubly Circular:
Applications:
Storage/space handling(HDD/SSD)
Data supply(Reels)
Navigation across pages(Hyperlink)
Games: 1.Navigation/stages
2.Aim/kinematics
Polynomial addition
Structure of a node:
Class Node:
def __init__(self,data):
self.data=data
self.next=None
InsertLeft
insertRight
deleteLeft
deleteRight
Search
Display
Circular ll:
Has root and last
Application:
Circular buffer for reuse of space
Play list / songs
Data filteration in staging
Music generation
Singly linked list can travel only in one direction making it slow to access
Doubly ll is double ended…i.e it uses noes tha has references for either sides
hence can access previous and next nodes
Trees:
Hierarchical
Mostly dynamic but can also be static
Starts with the root, grows with branches and ends with nodes.
At most / at least one root in a tree, root is 1 st node on tree
Applications:
a. Hierarchical storage (g drive)
b. Sorting and searching large data
c. Auto correct and auto complete
d. Tree used in geo data Map for storage
Types of trees:
Tree pe conceptual questions karke jaannaaaaaaaaaaaaaa
Complete Tree: all leaf nodes are at same depth
Nearly Complete tree: all other than 1 leaf node is +/- k depth
Strict binary tree: Node must either have 2 child nodes or 0
Binary Search Tree: child(left)< parent & child(right)>= parent
10,5,11,32,28,9,6,2,8,10,66,23,19
Deletion of node:
Case 1:
Leaf- cut it from parent and remove
Parent with single child:
Only child will take over parent’s position
Parent with subtree(left and right):
Inorder next takes over parent position
AVL tree:
Self balancing tree
Insertion in BST form but keeps it in balance
Balance factor: height of left subtree - height of right subtree
Due balance factor height of tree remains in control causing faster access.
Speed of search is associated with depthhigher depthlower speed
AVL is nearly balanced means +1,0,-1
Insert one node at a time using bst
After every insertion calculate BF and stop at 1 st unbalanced point(-2 or +2)
Plot 3 node path from unbalanced to newly inserted and see apply rotation
B+ Similar to B but in this data is stored in leaf and all leaf nodes are
connected to each other
Graphs:
Every tree is a graph, every graph is not a tree.
Graph without cycle is a tree
Weight of a graph: Any unit that can be used to take a decision, eg: cost t travel,
delay, bandwidth, queue length etc.
Path
Cycle
Adjacent nodedirect edge
DFS: uses stack, explores a path, one node at a time, vertical search
1) Accept graph and initialize stack and accept source
2) Mark source as visited and push on stack
3) Till stack is not empty:
a. Search any unvisited neighbour of element at tos, mark it visited
and push on stack
b. If no visited found pop and continue
BFS: uses queue, explores all nodes from given ode, horizontal search
1) Accept graph, source and initialize queue
2) Mark source visited and enqueue it
3) Till queue is not empty:
a. Search all unvisited neighbours of element at queue front mark
them visited and enqueue
b. Remove element from queue front(dequeue)
Real life examples of every thing
Dijkistra’s algorithm
Minimum Spanning Tree:
Input:graphs
Output:tree
Keep only non-cyclic, edges with minimum cost
Used in:
o power/flow/water distribution
o Road construction
o Railways
o Mails
Algorithm:
Pillars of algorithm:
Inputdata, dataset, problem set
Outputresult/response
Finitenessfixed steps and time
Definitenesseach step should be defined clearly
Effectivenesseach step should help to solve problem or solve the problem
analysis
Priori done before implementation, using pen paper
Posterioridone after implementation, using softwares
Why these 2?
for improvement
for checking exact end results (testing predicted complexity)
O(2n+4)=O(2n)+O(4)
= O(n)
Searching :
Result: index of found
Response: -1 if not found
Linear search:
Sorting:
A single element is always sorted
Bubble sort:
2. Neighbours are compared for sort
3. Logial: heaviest element is bubbled on top in each pass thus called bubble
sort
a. Means it is sent to top
Selection Sort:
1. All are compared to minimum
2. Logic:in each pass we will select minimum element and then place it a ith
location for ith pass
Insertion Sort:
1. Unsorted element compared to sorted and placed properly
2. Logic: in this array is divided in 2 parts
Sorted ,unsorted
In each pass an element from unsorted is inserted at correct location is
sorted part
Quick sort:
1. Works on pivot
a. Pivot is ref that can be 1st, last,mid
b. After taking pivot as ref rearrange everything wrt pivot such that:
i. All elements before pivot, element<pivot
ii. All elements after pivot<elements
Merge Sort: