You are on page 1of 39

Python Comments

Comments starts with a #, and Python will ignore them:

Python Comments
#This is a comment
print("Hello, World!") #This is a comment

Creating Variables
Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

Variables in Python
x = 5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even
change type after they have been set.

Data Type can be define using comments


x = 4 # x is of type int
x = "Sally" # x is now of type str

Changing Data Types – Casting


If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Single or Double Quotes?
String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same as
x = 'John'

Case-Sensitive
Variable names are case-sensitive.

Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.

#convert from float to int:


b = int(y)

Random Number
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:
Generating Random number
Import the random module, and display a random number between 1 and 9:

import random

print(random.randrange(1, 10))

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example
Get the character at position 1 (remember that the first character has the
position 0):

a = "Hello, World!"
print(a[1])

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part
of the string.
MID Function
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

Pick one by one ALL Characters in a STRING


name = "MAK CS"
for x in range(len(name)):
print(name[x:x+1])

Slice From the Start


By leaving out the start index, the range will start at the first character:

Pick 5 characters from LEFT


Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Pick Characters from Right


By leaving out the end index, the range will go to the end:

Example
Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Upper Case Conversion


The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Lower Case Conversion


The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.lower())
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x < 10


true

or Returns True if one of the statements x < 5 or x < 4


is true

not Reverse the result, returns False if the not(x < 5 and x
result is true < 10)

Creating an ARRAY
Create a List/Array:

thislist = ["apple", "banana", "cherry"]


print(thislist)

Example
Return the third, fourth, and fifth item:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not
included).

Note: The first item has index 0.


Append Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

While Loop – Printing all elements in an ARRAY


Print all items, using a while loop to go through all the index numbers

thislist = ["apple", "banana", "cherry"]


i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

IF THEN ELSE
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Example
Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is


possible to specify the increment value by adding a third parameter: range(2,
30, 3):

Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Creating a Function
In Python a function is defined using the def keyword:

Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

Printing ALL Elements in an ARRAY using FUNCTION


def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Code for Recursion


def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

Create a Class
To create a class, use the keyword class:

Creating a CLASS
Create a class named MyClass, with a property named x:

class MyClass:
x = 5

The init () Function


The examples above are classes and objects in their simplest form, and are not
really useful in real life applications.

To understand the meaning of classes we have to understand the built-in


init () function.

All classes have a function called init (), which is always executed when the
class is being initiated.

Use the init () function to assign values to object properties, or other


operations that are necessary to do when the object is being created:

Class with PUBLIC Constructor


Create a class named Person, use the init () function to assign values for
name and age:

class Person:
def init (self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Note: The init () function is called automatically every time the class is
being used to create a new object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.

Let us create a method in the Person class:

Example
Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def init (self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.

The pass Statement


class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to avoid getting an
error.

Creating an EMPTY Class


class Person:
pass
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived
class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
class:

Inheritance Example
Create a class named Person, with firstname and lastname properties, and
a printname method:

class Person:
def init (self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname
method:

x = Person("John", "Doe")
x.printname()
Declaring Attributes as PRIVATE
class Person:
def init (self, fname, lname):
self. firstname = fname
self. lastname = lname

Create a Child Class


To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:

Person is parent and Student is Child


Create a class named Student, which will inherit the properties and methods
from the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.

Now the Student class has the same properties and methods as the Person
class.

Example
Use the Student class to create an object, and then execute
the printname method:

x = Student("Mike", "Olsen")
x.printname()

Add the init () Function


So far we have created a child class that inherits the properties and methods
from its parent.

We want to add the init () function to the child class (instead of


the pass keyword).

Note: The init () function is called automatically every time the class is
being used to create a new object.
Example
Add the init () function to the Student class:

class Student(Person):
def init (self, fname, lname):
#add properties etc.

When you add the init () function, the child class will no longer inherit the
parent's init () function.

Note: The child's init () function overrides the inheritance of the


parent's init () function.

To keep the inheritance of the parent's init () function, add a call to the
parent's init () function:

Example
class Student(Person):
def init (self, fname, lname):
Person. init (self, fname, lname)

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.

These exceptions can be handled using the try statement:

Exception Code
The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

Since the try block raises an error, the except block will be executed.

Without the try block, the program will crash and raise an error:

Example
This statement will raise an error, because x is not defined:
print(x)

Example
Print one message if the try block raises a NameError and another for other
errors:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

File Handling
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not
exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Example
f = open("demofile.txt", "r")
print(f.read())

Read Lines
You can return one line by using the readline() method:
Reading a Line from File
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Close Files
It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Example
Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Create a New
File
To create a new file in Python, use the open() method, with one of the following
parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Creating a Class with Constructor defined


class college:

def init (self, name, age):

self. name = name

self. age =

age def

grettunranmsee(lsf.elf)n: ame

Declaring parent class


class section(college): #college is the parent

Random Files
import pickle

class record:
def init (self,name,age):

self.name = name

self.age = age

student = [record("MAK",12),record("zaki",34),record("mino",33)]

studentfile = open('cedarfile.dat', 'w+b')

pickle.dump(student[0],studentfile)
pickle.dump(student[1],studentfile)

pickle.dump(student[2],studentfile)

studentfile.close()

readfile = open('cedarfile.dat','r+b')

newstudent = []
for x in range(3):

newstudent.append(pickle.load(readfile))

print(newstudent[2].name)

import pickle
class record:

def init (self, name, age, grno):

self.name = name

self.age = age

self.grno = grno

student = [record("mak",23,10),record("zaki",34,11),record("shah",55,23)]

f = open('randomfile.dat', 'w+b')

address = hash(student[1].grno)
f.seek(address)

pickle.dump(student[1],f)

f.close()

newstudent = record("",0,0)

f = open('randomfile.dat', 'rb')

address = hash(11)

f.seek(address)
newstudent = pickle.load(f)

print(newstudent.name)

Create a Record Data Type


class Student:
def init (self,fn,a):
self.FirstName = fn
self.age = a

Declaring a 2D Array having 2 columns 11 rows, STRING Datatype


FileData = [[""] *2 for i in range(11)] #string

Displaying a 2D Array having 2 columns and 10 rows using procedure

def OutputHighScores ():


for x in range(0, 10):

Output = FileData[x][0] + " " + FileData[x][1]

print(Output)

Applying a validation Check on user name for 3 characters only.


username = input("enter 3 character Name ")

while len(username) != 3:

username = input("Re-enter it should be only 3 characters ")

Writing a 2D array into a Text File using a Procedure


def WriteTopTen():

newfile = open('newhighscore','w')

for x in range(10):

newfile.writelines(FileData[x][0] + "\n")

newfile.writelines(FileData[x][1] + "\n")

newfile.close()

WriteTopTen()
#Bubble Sort
mylist = [23,1,20,15,100,18,19]
print(mylist)
ub = len(mylist)
swap = True
while swap == True and ub > 0:
swap = False
for index in
range(ub - 1):
if mylist[index] > mylist[index+1]:
temp = mylist[index]
mylist[index] = mylist[index +
1]
mylist[index + 1 ] = temp
swap = True
ub = ub - 1
print(mylist)

Linear Search

golden = [23,12,3,45,67,89,98,8,9,10] found =


False
ub = 9
index = 0
items = int(input("Enter Item to be Search "))
while found == False and index <= ub:
if golden[index] == items:
found = True index = index + 1 if found ==
True: print("Item Found ")
else:
print("item not found")

#String manipulation
name = "Muhammad Ali Khan"
x = len*name) # Calculating number of characters in string
print( name[:]) # all characters
print(name[9:12])
print(name[:12])
print(name[9:])
print(name[0:2])
print(name[:4])
print(name[9:])
#Count number of characters A and S in a
name numa = 0
nums = 0
name = input("Enter Your name ")
for x in range(len(name)):
if name[x] == "a":
numa = numa
+ 1 elif name[x] ==
nums = nums +
1"s":
print("Number of a characters = ", numa)
print("Number of s Characters = ", nums)

#Stack Code for PUSH

stack = [0] * 10
topofstack = -1
stackfull = 10
freepointer = 0
print(stack)
def push(item):
global topofstack , stack , stackfull
if topofstack <stackfull - 1:
topofstack = topofstack + 1
stack[topofstack] = item
else:
print("Stack is full ")

#Stack Code for POP


def pop():
global topofstack , freepointer ,
item if topofstack == freepointer - 1:
print("Stack is empty ")
else:
item = stack[topofstack]
stack[topofstack] = 0
topofstack = topofstack -1
#Queue Codes
queue = [None] *
10 frontpointer = 0
endofqueue = -1
queuefull = 10
queuelength = 0
print(queue)

def enQueue(item):
global queuelength ,
endofqueue if queuelength <
queuefull:
if endofqueue < len(queue) -
1: endofqueue = endofqueue
+1
else:
endofqueue = 0
queuelength = queuelength +
1 queue[endofqueue] = item
else:
print("Queue is FULL
") enQueue("MAK")
print(queue)

def deQueue():
global queuelength , frontpointer ,
item if queuelength == 0:
print("Queue is Empty
") else:
queue[frontpointer] = None
frontpointer = frontpointer +
1
queuelength = queuelength -1

deQueue()
deQueue()
print(queue)
#Linked List
mylist = [None] * 10 mylistpointer =
[None] * 10 freeP = 0
startP = -1
for x in range(10):
mylistpointer[x] = x +
1
mylistpointer[9] = -1

#Searching an item in a linked list

mylist = [27,19,36,None,None]
mylistpointer = [-1,0,1,4,5]
startpointer = 2
nullpointer = -1
def find(item):

found = False
itempointer = startpointer
while itempointer != nullpointer and found ==
Falseif: mylist[itempointer]
== item:
found = True
else: itempointer =
mylistpointer[itempointer] return
itempointer
print(find(27))

#Inserting an item in a linked List

def insert(item):
global startP , freeP , mylistpointer , mylist
if freeP == -1:
print("Linked list is
full") else:
tempP = startP
startP = freeP
freeP = mylistpointer[freeP]
mylist[startP] = item
mylistpointer[startP] = tempP
print(mylist)
insert(23)
insert(40)
insert(41)
print(mylist)
#Deleting an item from Linked List

def delete(itemdelete):
global startP , freeP
if startP == -1:
print("list is empty
") else:
index = startP
while mylist[index] != itemdelete and
index != -1:
oldindex = index
index = mylistpointer[index]
if index == -1:
print("item not found")
else: mylist[index] = None
temp = mylistpointer[index]
mylistpointer[index] = freeP
freeP = index
mylistpointer[oldindex] =
temp
#Object Oriented Programming

class college:
def __init__(self, name,
age): self.__name = name
self.__age = age
def getname(self):
return self.__name
class
section(college):
def __int__(self,name,age):
college.__init__(self,name,ag
e)

group1 =
section("mak",44)
print(group1.getname())

p1 = college("MAK",

36)

print(p1.getname())

#Polyporphism

class Shape:
def __init__(self,
name): self.name =
name

def area(self):
pass
def shapename(self):
print(self.name)

class Square(Shape):
def __init__(self, length):
Shape.__init__(self,"Square"
) self.length = length

def area(self):
return self.length**2

class Circle(Shape):
def __init__(self,radius):
Shape.__init__(self,"Circle
") self.radius = radius

def area(self): shape1 = Square(2)


return self.radius * self.radius * 3.1459 shape2 = Circle(2)
print(shape1.area())
print(shape2.area())
shape1.shapename()
shape2.shapename()
#Reading the whole text File
file = open('Pictures.txt','r')
line = file.readline()
while line != "":
print(line)
line =
file.readline()
file.close()
#Writing an array into text file
arraydata =
["MAK","Zaki","Nukhba","Zajnan"] file =
open('test.txt','w')
for x in range(4):
file.writelines(arraydata[x] + "\n")
file.close()
#Random Files test program
import pickle
class record:
def __init__(self,name,age):
self.name =
name self.age =
age

student =
[record("MAK",12),record("zaki",34),record("mino",33)]
studentfile = open('cedarfile.dat', 'w+b')

pickle.dump(student[0],studentfile)
pickle.dump(student[1],studentfile)
pickle.dump(student[2],studentfile)
studentfile.close()
readfile =
open('cedarfile.dat','r+b')
newstudent = []
for x in range(3):
newstudent.append(pickle.load(readfile))

print(newstudent[2].name)
import pickle
class record:
def __init__(self, name, age, grno):
self.name =
name self.age =
age self.grno =
grno
student =
[record("mak",23,10),record("zaki",34,11),record("shah",55,23)] f =
open('randomfile.dat', 'w+b')
address =
hash(student[1].grno)
f.seek(address)
pickle.dump(student[1],f)
f.close()
newstudent = record("",0,0)
f = open('randomfile.dat',
'rb') address = hash(11)
f.seek(address)
newstudent =
pickle.load(f)
print(newstudent.name)
#MJ21P4
class TreasureChest:
def
__init__(self,questionP,answerP,pointP):
self.__question = questionP
self.__answer =
answerP self.__point =
pointP
def getQuest(self):
return
self.__question def
checkans(self,ans):
if ans == self.__answer:
return True
else:
return False
def getpoints(self,attempts):
if attempts == 1:
return
self.__point elif
attempts == 2:
return self.__point//2
arrayTreasure = []
def readData():

f = open('TreasureChestData.txt','r')

dataquest = f.readline()
while dataquest != "":
dataans = int(f.readline())
datapoints = int(f.readline())
arrayTreasure.append(TreasureChest(dataquest,dataans,datapoints))
dataquest = f.readline()

f.close()
readData()

choice = int(input("Pick a treasure chest to


open")) if choice > 0 and choice < 6:
result =
False
attempts = 0
while result == False:
answer = int(input(arrayTreasure[choice-1].getQuest()))
result = int(arrayTreasure[choice-1].checkans(answer))
attempts = attempts + 1
print(int(arrayTreasure[choice-1].getpoints(attempts)))
#October/November 2021 Question 1`
def Unknown(X, Y):
if X < Y:
print(str(X + Y))
return Unknown(X + 1, Y) * 2
elif X == Y:
return 1
else:
print(str(X + Y))
return int(Unknown(X - 1, Y) / 2)
def Unknown(X,Y):
num = 1
while X !=
Y:
if X < Y:
print(str(X+Y))
X = X +1
num = num * 2
else:
print(str(X+Y))
X=X -1
num = num //2

return num
#open a text file for reading TreasureChestData
#store all data from text file in an array called Regatta
#print array , index by index

file = open('TreasureChestData.txt','r')
line = file.readline()
Regatta = []
while line !=
"":
Regatta.append(line)
line = file.readline()
file.close()
for x in range(len(Regatta)):
print(Regatta[x])

#create an array called MAKCS


#Store the following values
#Sarim , Ahmed , Moosa , Saad , Hamza ,Naseer
MAKCS = ["Sarim","Ahmed
","Moosa","Saad","Hamza","Naseer"] #create a Function called
Highbrow take name as Parameter #count number of A's in
that name
def Highbrow(name):
count = 0
for x in range(len(name)):
if name[x] == "A" or name[x] ==
"a": count = count + 1
return count

print(Highbrow("Azaaan"))

#Copy All data from text file into an array and display the Array index by index
file = open('TreasureChestData.txt','r')
line = file.readline()
Cedar = []
while line !=
"":
Cedar.append(line)
line = file.readline()
file.close()
for x in range(len(Cedar)): print(Cedar[x])
#create a procedure called Value that will ask
user #name age and marks
#store them in a text file called Test.txt
def Value():
name = input("Enter your Name")
age = int(input("Enter your Age"))
marks = int(input("Enter Marks "))
file = open('Test.txt','w')
file.writelines(name + '\n')
file.writelines(str(age) + '\n')
file.writelines(str(marks)+ '\n')
file.close()
Value()
#MayJune2022P4Question1
FileData = [[""] *2 for i in range(11)] #string
def ReadHighScores():
Filename = "HighScore.txt"
File = open(Filename, 'r')
for x in range(0, 10):
FileData[x][0] = File.readline().strip()
FileData[x][1] = File.readline()
File.close
def OutputHighScores ():
for x in range(0, 10):
Output = FileData[x][0] + " " + FileData[x][1]
print(Output)
ReadHighScores()

username = input("enter 3 character Name ")


while len(username) != 3:
username = input("Re-enter it should be only 3 characters ")

score = int(input("Enter Score of the players : "))


while score < 1 or score > 10000:
score = input("Reenter") def
newlist(username,score):
FileData[10][0] = username
FileData[10][1] = str(score)
index = 10
for x in range(10):
for y in range(index):
if int(FileData[y][1]) <
int(FileData[y+1][1]): nametemp =
FileData[y][0] FileData[y][0] =
FileData[y+1][0] FileData[y+1][0]=
nametemp scoretemp = FileData[y][1]
FileData[y][1] = FileData[y+1][1]
FileData[y+1][1]= scoretemp
index = index - 1
newlist(username,score)
def WriteTopTen():
newfile = open('newhighscore','w')
for x in range(10):
newfile.writelines(FileData[x][0] + "\n")
newfile.writelines(FileData[x][1] + "\n")
newfile.close()
WriteTopTen()
#Binary Tree Traversal

ArrayNodes = [[-1]*3 for i in range(20)] #INTEGER


ArrayNodes = [[1,20,5],[2,15,-1],[-1,3,3],[-1,9,4],[-1,10,-1],[-1,58,-1],[-1,-1,-1]]
FreeNode = 6
RootPointer = 0
def SearchValue(Root,ValueToFind): #RETURNS INTEGER
if Root == -1:
return -1
elif ArrayNodes[Root][1] == ValueToFind:
return Root
elif ArrayNodes[Root][1] == -1 :
return -1

if ArrayNodes[Root][1] > ValueToFind:


return SearchValue(ArrayNodes[Root][0],ValueToFind)
if ArrayNodes[Root][1] < ValueToFind:
return SearchValue(ArrayNodes[Root][2],ValueToFind)
def PostOrder(RootNode):
if ArrayNodes[RootNode][0] != -1:
PostOrder(ArrayNodes[RootNode][0])
if ArrayNodes[RootNode][2] != -1:
PostOrder(ArrayNodes[RootNode][2])
print(str(ArrayNodes[RootNode][1]))
PostOrder(0)
Value = SearchValue(0,150)
if Value == -1:
print("Value not Found ")
else : print("Index at which we found : ",
Value) def InOrder(RootNode):
if ArrayNodes[RootNode][0] != -1:
InOrder(ArrayNodes[RootNode][0])

print(str(ArrayNodes[RootNode][1]))
if ArrayNodes[RootNode][2] != -1:
InOrder(ArrayNodes[RootNode][2])

def PreOrder(RootNode):
print(str(ArrayNodes[RootNode][1]))
if ArrayNodes[RootNode][0] != -1:
PreOrder(ArrayNodes[RootNode][0])
if ArrayNodes[RootNode][2] != -1:
PreOrder(ArrayNodes[RootNode][2])
#Binary Search using Recursion
Python
def recursiveBinarySearch(lowerbound, upperbound, searchValue):
mid = lowerbound + int((upperbound - lowerbound)/2) if upperbound <
lowerbound:
return -1
else:
if Array[mid] < searchValue:
return recursiveBinarySearch(mid + 1, upperbound,
searchValue)
elif Array[mid] > searchValue:
return recursiveBinarySearch(lowerbound, mid - 1,
searchValue)
else:
return mid
#Insertion SORT Code
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr

#Inserting an item in tree

class TreeNode:
def init (self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

def insertNode(root, val):


if not root:
root = TreeNode(val)
return root
if val < root.val:
root.left = insertNode(root.left, val)
else:
root.right = insertNode(root.right, val)
return root
# create the initial tree
root = TreeNode(4)
root.left = TreeNode(2)
root.right = TreeNode(7)
root.left.left = TreeNode(1)
root.left.right = TreeNode(3)

# insert a new node with value 5


root = insertNode(root, 5)
#Searching an item in Binary Tree
class TreeNode:
def init (self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

def searchNode(root, val):


if not root:
return False
if root.val == val:
return True
elif val < root.val:
return searchNode(root.left, val)
else:
return searchNode(root.right, val)

You might also like