Code sheet
Built in functions and other stuff
To lower case .lower()
To upper case .upper()
To generate Import random
random variable
Random.randint(1 , 100) #bw 1 and 100
Increment i += 1
Decrement i -= 1
To break a loop Break
Left function String[:a]
Right function String[a:]
Mid function String[a:b]
To declare Def function(perimeter):
function
….
Return smthn
For loop For I in range( a , b , c):
Starts at a ends at b…..increments by c
Arrays
Array Array = []
To add to array Array.append(element)
To make 2d Array = [ [] for I in range(x)]
array
Binary Search() def binSearch(Target, arr):
upperBound = len(arr) - 1
lowerBound = 0
while lowerBound <= upperBound:
midIndex = (lowerBound + upperBound) // 2
midValue = arr[midIndex]
if midValue == Target:
print(f"Target is at index {midIndex}")
break
elif midValue < Target:
lowerBound = midIndex + 1
else:
upperBound = midIndex - 1
Swap() def swap(a, b):
print(a) #5
print(b) #9
temp = a
a = b
b = temp
print(a) # 9
print(b) # 5
return a, b
Sorting Algorithms
Bubble Sort() def BubbleSort(kashif):
maxComp = len(kashif) - 1
flag = False
while not flag: #while flag == False
flag = True
for i in range(maxComp):
if kashif[i] > kashif[i+1]:
kashif[i], kashif[i+1] = swap(kashif[i],
kashif[i+1])
flag = False
maxComp -= 1
Insertion Sort() def insertionSort(arr):
for i in range(len(arr)):
key = arr[i]
preKeyIndex = i - 1
while preKeyIndex >= 0 and arr[preKeyIndex] >
key:
arr[preKeyIndex + 1] = arr[preKeyIndex]
preKeyIndex -= 1
arr[preKeyIndex+1] = key
OOP
Initialising a class Book:
Class
# self.__name as string
#self.__author as string
#self.__pages as integer
def __init__(self, name, author, pages):
self.__bookName = name
self.__authorName = author
self.__numPages = pages
Setter Def setname(self , name):
self.__bookname = name
Getter Def getname(self):
Return self.__bookname
Acessing class Print(book1.getname())
function outside
Book1.setname(name)
class
Inheriting from class audioBook(Book):
a class
def __init__(self, title, author, narrator):
super().__init__(title, author)
self.narrator = narrator
def displayAudioDetails(self):
super().displayDetails() #CALL A FUNCTION
FROM PARENT CLASS WITHIN A CHILD CLASS
print(f"The book is read by {self.narrator}")
Queue
Enqueue() def Enqueue(data):
global Names
global HeadPointer
global TailPointer
if TailPointer >= lenQueue:
print("Queue full")
else:
Names[TailPointer] = data
TailPointer += 1
if HeadPointer == -1:
HeadPointer = 0
Dequeue() def Dequeue():
global Names
global HeadPointer
global TailPointer
if HeadPointer== -1:
print("Nothing to dequeue")
else:
dequeued = Names[HeadPointer]
Names[HeadPointer] == ""
HeadPointer += 1
print(f"Dequeued: {dequeued}")
if HeadPointer == TailPointer:
HeadPointer = -1
TailPointer = 0
Stack
Push() def Push(data):
global Names
global stackPtr
if stackPtr >= stackSize:
print("sorry bhai jgha nahien hai")
else:
Names[stackPtr] = data
stackPtr += 1
Pop() def Pop():
global Names
global stackPtr
if stackPtr == 0:
print("bhai kuchh hai hi nahien, kya pop kroon")
else:
popped = Names[stackPtr - 1]
print(popped)
Names[stackPtr - 1] = ""
stackPtr -= 1
File Handling
Opening a file filename = input("please enter a filename:")
try:
fr = open(filename , "r")
except:
print("file not found")
Reading a file def print_all(filename):
fr = open(filename,"r")
line = fr.readline().strip()
while line != "":
print(line)
line = fr.readline().strip()
fr.close()
Deleting smthn def delete_city(cityname):
from file
array_city = ["." for i in range(100)]
fr = open(filename , "r")
line = fr.readline().strip()
i = 0
while line != "":
array_city[i] = line
i = i + 1
line = fr.readline().strip()
fr.close()
fw = open(filename , "w")
i = 0
while array_city[i] != ".":
if array_city[i] != cityname:
fw.write(array_city[i] + "\n")
i = i + 1
fw.close()
Binary Tree
Initializing a class node():
binary tree
def __init__(self):
self.data = ""
self.leftptr = -1
self.rightptr = -1
def Initialize_binarytree():
global freeptr , rootptr
rootptr = -1
freeptr = 0
for i in range(8):
binarytree [i].data = ""
binarytree[i].leftptr = -1
binarytree[i].rightptr = i + 1
binarytree[9].left = -1
binarytree[9].right = -1
Adding a node def Add_Node():
global freeptr , rootptr
if freeptr != -1:
item = input("please enter a character to add:")
newptr = freeptr
freeptr = binarytree[freeptr].rightptr
binarytree[newptr].data = item
currentptr = rootptr
while currentptr != -1:
prevptr = currentptr
if item > binarytree[currentptr].data:
currentptr =
binarytree[currentptr].rightptr
turnedleft = False
else:
currentptr =
binarytree[currentptr].leftptr
turnedleft = True
if rootptr == currentptr:
rootptr = newptr
elif turnedleft == True:
binarytree[prevptr].leftptr = newptr
else:
binarytree[prevptr].rightptr = newptr
binarytree[newptr].leftptr = -1
binarytree[newptr].rightptr = -1
else:
print("node not available , add node")
Pre order def pre_order(rootptr):
traversal
if rootptr != -1:
print(binarytree[rootptr].data , end = " , ")
pre_order(binarytree[rootptr].leftptr)
pre_order(binarytree[rootptr].rightptr)
In order def in_order(rootptr):
traversal
if rootptr != -1:
in_order(binarytree[rootptr].leftptr)
print(binarytree[rootptr].data , end = " , ")
in_order(binarytree[rootptr].rightptr)
Post order def pre_order(rootptr):
traversal
if rootptr != -1:
print(binarytree[rootptr].data , end = " , ")
pre_order(binarytree[rootptr].leftptr)
pre_order(binarytree[rootptr].rightptr)