0% found this document useful (0 votes)
19 views27 pages

Pyth

The document provides a comprehensive overview of Python programming concepts, including data types, syntax, memory management, and data structures. It covers object-oriented programming principles such as encapsulation, inheritance, and polymorphism, along with practical coding examples. Additionally, it discusses functions, exception handling, and the differences between various data structures like lists, tuples, sets, and dictionaries.

Uploaded by

mallard048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views27 pages

Pyth

The document provides a comprehensive overview of Python programming concepts, including data types, syntax, memory management, and data structures. It covers object-oriented programming principles such as encapsulation, inheritance, and polymorphism, along with practical coding examples. Additionally, it discusses functions, exception handling, and the differences between various data structures like lists, tuples, sets, and dictionaries.

Uploaded by

mallard048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

THIS FILE AS WELL AS THE CODES WITH THIS FILE IS

IMPORTANT

 Python is hybrid(interpreted and compiled)


Pyc is not a machine code,it is intermediate class code(it will be understood
only by pvm)
Machine delivered errors are easily solved in python since it is hybrid

 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

ASCII ka full form and significance


ASCII(8 BIT) < Unicode(16 bits)
Python was invented in 199
By default input mode in python is string
******Interview mei most basic concepts bhi kar ke jao*******
Tokens keywords: reserved words
identifier: symbolic reference/ symbolic name given to memory
location where data is stored. It identifies value in memory.
literal:
Prints and then it shifts to new line.
End and sep features

 Declaration vs dynamic initialization


Python supports dynamic declaration only i.e declaration and initialization
is done at the same time.

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

******do even most basic things too******


Python will share memory for common data.(multiple variables having
same data)
Python does not update memory location on change, it gives you a new
memory
Python mei auto Garbage collection(AGC) hota hai.

********MEMORY MANAGEMENT KI ACCHI TAYARI KARKE


JAAO*******

 KISI NUMBER KO RIGHT SHIFT (>>) KAROGE TOH DIVIDE BY 2 HOGA


(/2^N)
 LEFT SHIFT PE MULTIPLY BY 2 (* 2^N)
N:NO.OF SHIFTS

~  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
Whiledigit 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?
Ansusing 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)

Armstrong number and palindrome ke codes bohot important hai

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
mutableused by programer
Tuple (), duplicates allowed, index access, Static(immutable)python uses
maximum for security since cannot be modified.
Set{}, no duplicates, no indexed access, dynamicused for filteration, union,
intersection, difference and symmetric difference type works
Dictionary {k:v}, key cannot be duplicated, value can be duplicated, dynamic,
key based accessused in maps
Dynamic(run time pe size increase ya decrease kar sakte ho)(mutable)

Empty {} dictionary banata hai


{x} set
For empty set a=set() it will give set
Lists and strings both support -ve indexing
+for concatenation (appending list to another list)
*for repeatition of list
Updation of list ke liye index based iteration
To reverse a list l=l[: : -1]
List functions:
Sum(l),max(l),min(),sort()
Nested list:
m=[[10,20],[30,40,50],[70,80]]
print(m[1][2])

Create a list using list comprehention:


l=[x*4 for x in range(1,11)]
print(l)

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)

To convert 2 lists into a single dictionary:


mapped=dict(zip(s,n))
print(mapped)
Strings:
‘’’---- ‘’’  it is the most powerful way for creating strings as it can contain
multiple lines.

String is partially mutable in python  we can add contain to it but any


method are not making changes to string itself.
s=’athrva’
s.rfind(‘a’) 5(end se count karta hai lekin index value left se hi count
karta hai)

count each character in string in order


line=input()
sline=sorted(set(line))
sline.remove(" ")
for i in sline:
print(i,"-->",line.count(i))

print("total words:",len(input("Enter line:").split()))

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.

Python primitive are passed by value


Changes are only seen in function
If we need to use RND or make changes use case
Python data structures are passed by references
Changes are seen globally
If changes are at several places use case
#return control back to script
#return in python can pass 1 as well as n data
#1 data maintains primitive type
#n data uses tuple---security(reason)

Recursion: function calling itself


Not to be used as first option
o Makes code run slower,takes more memory,complex to
understand
Code looks smaller
Difference between default vale and key value parameter:

#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

Iterator are not generating any values


Generator generates values on regular interval on runtime

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

Object is physical implementation of class

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)

****for interview : opps,loops*****


4 pillars of oops:
Encapsulations: data + operation on data + example: cover + anything with it.
Buying laptops
Abstraction: hiding unwanted complex data and the way we store it and only
giving simple relevant access to needed info/data. ex: menu with item
description
Inheritance: process of creating something new by taking properties of pre-
existing .own properties + inherited properties. Ex: lastname of a person or
native
Polymorphism: Ability to exist in multiple form

Class <Name>:
Methods:
Data:

In python method causes data, i.e. wen a method is called


#self is reference of object calling
Self.xxxx means object.xxxx

#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.privateself.__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'

To get the imei…we will create a getter method


def getImei(self):
return self.__imei

m1=mobile("Apple",10000,"White",123456789)
print(m1.getImei())
It will display imei

Another way to get strong private members:


print(m1._mobile__imei)

#if you use this… you can impress the interviewer.

Inheritance:
To inherit, use super().__init__(brand,price)

What is friend class?


It is a class which is not inherited but still can access the members of
its friend classes
class Phone:
def __init__(self,brand,price):
self.brand=brand
self.price=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.

If we over-ride all the methods of a abstract class in a child class … as stated in


point 6 above...then why do we need the parent class?

 Class methods
 Instance methods
 Static 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

All data structures can be either(static or dynamic)


 Stack generally s
 Queue generally s
 Linked-list  generally d
 Tree generally d
 Graph generally s

Data structures: Way of storing data in such a manner that accessing and
updating becomes easy/faster.

ADT (Abstract data type):


list of operation on must code/support for a data structure
DS: complex term which need special ways of operations hence coder must code
methods and structure both

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
pushtop +=1 stack[top]
if top=maxSize-1isFull: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*eA-de* A-BAB- 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

Infix to postfix using stack:

1. Accept infix and init stack


2. Read infix left to right element by element
3. If read is ‘(’ push on stack
4. If read is ‘)’ pop everything from stack till ‘(’ Is not removed. copy all popped to postfix other
than ‘(’
5. If read is operator(+,-,*,/,%) push it on stack iff pre(new operator)>pre(operator on stack)
else pop everything from stack and copy to postfix till either stack becomes empty or
condition becomes true
6. If read is operated then copy to postfix
7. Continue step 2 to 6 till infix is not over
8. Copy remaining from stack to postfix
Infix to prefix using stack:

1. Accept infix and initialize stack


2. Read infix right to left element by element
3. If read is ‘)’ push on stack
4. If read is ‘(’ pop everything from stack till ‘)’ Is not removed. copy all popped to prefix other
than ‘)’
5. If read is operator(+,-,*,/,%) push it on stack iff pre(new operator)>=pre(operator on stack)
else pop everything from stack and copy to prefix till either stack becomes empty or
condition becomes true
6. If read is operated then copy to prefix
7. Continue step 2 to 6 till infix is not over
8. Copy remaining from stack top prefix
9. Reverse prefix

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
 Circularuses limited space for unlimited access by reuse
 Prioityworks in RTOS(Real time operating system)
 Double endedworks 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

In linear queue we cannot reclaim the dequeued spaces…thus circular queue


comes into picture

Rear=(Rear+1)% maxSize
Front=(Front+1)%maxSize
Enqueuecount+1
Dequeuecount-1
If count==0 empty
If count==maxSize full

Circular queue display function (Super important)😊:


def Display(self):
c=0
i=self.front
while c<self.count:
print(self.cir_queue[i],end="--")
i=(i+1)%self.MaxSize
c+=1

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

Ascending priority queue on dequeue , minimum comes out


min has highest priority
ranking system
Descending priority queue on dequeue , maximum comes out
max has highest priority
total system
For implementation:
R--------F
Put the data in order(sort accordingly)
Linked List:
Collection of nodes arranged in a sequential manner such that each node refers
to next
Linear dynamiccan create any other ds
Types:
Linear:

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

Root is not created but assigned


#root is the leftmost i.e 1st
#right most-- has 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

Stack using linked list (Dynamic Stack):


PushinsertLeft
PopdeleteLeft

Queue using Linked List (Dynamic Queue):


Enqueueinsert right
Dequeuedelete left

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

Tree Binary Tree


N child At most 2 child

Height/depth => length of longest running branch.


Depth and height of a tree will always be same
Depth and height of a node may be different

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

traversal: order in which one would visit each node


preorder: P L R
inorder: L P R
postorder: L R P

pre:10,5,1,8, 30,20(root pehele[10])


in:1,5,8,10,20,30 (Sequential)
post:1,8,5,20,30,10(root is last[10])

Threaded Binary tree:

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 depthhigher depthlower 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

(Iske upar yt dekho)


Splay: used is cache system
Left(zig),right(zag) zig , zag , zig zig , zag zag , zig zag, zag zig
Recently accessed is brought to root using rotations

Multiway search tree:


A node can have n elements
As computer grew with hardware and software one can store multiple elements
in a node.
Eg-> B/B+
B has order M, M must be odd only, M decides Max(M-1), Min(M/2), Split(M)
Insertion in leaf only, leaf splits n create parent, parent creates grandparent,
node keeps data in order
Slow in sequential access due to nature of data being stored in scattered manner

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 nodedirect 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

Prim’s and krushkal algorithm


Tree Implementation:
1.Static (Array):
 Root-0
 For each ith node 2i+1: Left child 2i+2:Right Child
 +ve:Simple,fast
 -ve:static so cant grow or shrink
2.Dynamic (DLL):
 Uses DLL node to create Tree
 +ve : Dynamic so memory is used effectively and on demand basis
 -ve : one can only traverse from top to bottom due to which one must use
recursion in traversal
3.Dynamic (Tree node):
Node can ref left child,right child and parent,3 way bond or between parent
https://colab.research.google.com/drive/1z0VAak8vQI-
99g_U5gECCoykjGZiBnJy#scrollTo=P1iTIwi2Y_4c

Algorithm:
Pillars of algorithm:
Inputdata, dataset, problem set
Outputresult/response
Finitenessfixed steps and time
Definitenesseach step should be defined clearly
Effectivenesseach step should help to solve problem or solve the problem

Input and output are the most important pillars

analysis
Priori done before implementation, using pen paper
Posterioridone after implementation, using softwares
Why these 2?
for improvement
for checking exact end results (testing predicted complexity)

Time complexity given more importance


T = time to execute
 Comments-0
 Operations-1
 Loop- n+k
n+k is the time in steps and not in any unit of time
Space complexity
Analysis cases:
Best case: min or no work
Worst case: for size of n, 2n, n^2  gives most efficient answer
Average case: for n around n/2 for quick answer

Asymptotic notationmathematical way of recording complexity

Big oh ->Best case fast, simple, less efficient


Theta -> Avg (worst + Best) slow, highly effiecient
Omega ->Best case hardly used

f(n):input rate number of inputs


g(n):growth rateamount of work or steps

big 0  f(n) <= c * g(n)


theta c1*g(n) <= f(n) <= c2*g(n)
omega f(n) >= c*g(n)
Q)Give big O complexity for summation of i=1 to n (i**2) ?
n=int(input()) //1
sum=0 //1
for i in range(0,n+1): //n+1
sum=i**2 //n
print(sum) //1

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:

You might also like