0% found this document useful (0 votes)
15 views90 pages

Python Programming Basics Guide

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)
15 views90 pages

Python Programming Basics Guide

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

IDE : Integrated Development Environment:

Any software where you can code the source code (English like code-high level language) and it assists
with decoding of the source code into object code.

Input and Output of Data:


Output : Display : PRINT
Input : (Take a value from the user) : INPUT

Data Storage :
1. Constants (That may not change within the program) e.g., pi=3.1416
2. Variables (That may change within the program, mostly the values taken from the user)
Data Types:
Python can automatically select data types, but it is a good approach to mention the data types.
NOTE : If you are taking data from the user, and you have not mentioned a data type, string data type
will be selected as default.
1. String
a) Alphabets (haseeb)
b) Alphabets + numbers (haseeb123)
c) Alphabets + numbers + symbols (haseeb4@[Link])
d) Non-calculative data (phone number, ids, serial numbers)
2. Integer
a) Whole number (56,99,101)
3. Float
a) Fractional Part (56.55,99.01,101.98)
4. Boolean
a) Two states.
5. Date
a) Date(Formats)
6. Time
a) Time (Formats)

Arithmetic Operators:
1. = (Assign a value)
2. == (compare two values if they are equal)
3. All the Boolean operators (true or false) (1st letter would be capital) (True, False)
4. > ( Greater than)
5. < (Less than)
6. >=
7. <=
8. != (un equal to)

Logical Operators:
1. AND (both the conditions to be satisfied)
2. OR (either one of the conditions to be satisfied)
3. NOT (Exclude)

NOTE : THERE IS NO NEED TO DECLARE ANY DATA STRUCTURE IN PYTHON… 😊

OUTPUT :
print(“hello how are you”) (string are encapsulated in double quotations) ….. Display : hello how are you
print (num1) (variables, constants or any data structure is never encapsulated in double quotations)

INPUT :
Num1=input(“please enter a number”)

“34” + “55” = “3455”

Program 1: (Strings Example) (Concatenation)


num1=input("please enter a number")
num2=input("doosra number enter kroooooo :)")
result=num1+num2
print(result)

Program 2: (Addition with data types)


num1=int(input("please enter a number"))
num2=int(input("doosra number enter kroooooo :)"))
result=num1+num2
print(result)

Home work :
1) Subtract two numbers
2) Divide two numbers

Topic 1:
Conditional Statements:
1. If
2. Case (Does not exists in python)
IF : Whenever there is a need of two possible outcomes of a condition,
Structure :

#lets take two numbers and find out highest of the numbers
num1=int(input("please enter 1st number"))
num2=int(input("please enter second number"))
if num1>num2:
print("largest number is,",num1) #true outcome
else:
print("largest number is,",num2) #false outcome

NOTE : Every condition in python is always followed by a colon :


IMPORTANT NOTE : Indentation is very important.
NOTE : For heading or sub headings normally called comments we use a # in python.

Let’s try and find out the highest of three numbers.


If you have more than one condition, then rather than using simple if statement we will use, nested if
statements, that is extend if statement by using elif.

num1=int(input("please enter 1st number"))


num2=int(input("please enter second number"))
num3=int(input("please enter third number"))
if num1>num2 and num1>num3:
print("Largest number is: ",num1)
elif num2>num1 and num2>num3:
print("Largest number is: ",num2)
else:
print("Largest number is: ",num3)

Homework: [Link]
Convert codes from pseudocode to python:
Example 1,2,3
Example 15,16,17,18

Project 1:
Create a calculator, to add, subtract, multiply and divide on user’s choice.
Take two numbers from the user, and perform the required operation.

Grades Table:
Take marks from a student, display A* if the marks entered are greater than 90, A if the marks entered
are greater than 80, B if the marks entered are greater than 70, and “please try again” if the marks
entered are less than 70.
(YOU GOT 10 Minutes to do it)
marks=int(input("Please enter your marks"))
if marks>90:
print("A*")
elif marks>80:
print("A")
elif marks>70:
print("B")
else:
print("please try again")

NOTE:
You can end an if statement by elif as well:
marks=int(input("Please enter your marks"))
if marks>90:
print("A*")
elif marks>80:
print("A")
elif marks>70:
print("B")
elif marks<70:
print("please try again")

Project 1: Solution:
num1=int(input("please enter 1st
number"))
num2=int(input("please enter second
number"))
choice=input("please enter your choice,
+,-,*,/")
if choice=="+":
result=num1+num2
elif choice=="-":
result=num1-num2
elif choice=="*":
result=num1*num2
else:
result=num1/num2
print("Your choice was:",choice,"and the
result is:",result)

alternate:
#DECLARE num1,num2,result : INTEGER
num1 = int(input("ek number enter krna
"))
num2 = int(input("ek aur number enter
krna "))
choice = input("please select an
operation, +,-,*,/")
if choice == "+":
result = num1 + num2
elif choice == "-":
result = num1 - num2
elif choice == "*":
result = num1 * num2
elif choice == "/":
result = num1 / num2
if choice == "+":
name = "SUM"
elif choice == "-":
name = "SUB"
elif choice == "*":
name = "MULTIPLY"
elif choice == "/":
name = "DIVISION"
#The sum of 15 and 20 is 35
print("The",name,"of",num1,"and",num2,"is
",result)

Loops/Iterations/Repetitions:
Whenever you need a program to run again and again, till a justified point.
When you have huge amount of numbers to handle, or infinite numbers, you use loops.

1) While (Pre conditioned loop)


2) For (Counter Control loop)

While : pre conditioned loop: condition will be given at the start of the loop: conditions given are
depicting a true state.

1. Whole numbers (0-99)


NEW CONCEPT : counting : used to increment or decrement values:
Count=count+1
1,2,3,4,5,99

count=0 #initialization
while count < 100:
print(count)
count=count+1

2. Print 1st 100 Even Numbers(2-200)


3. count=2
while count<=200:
print(count)
count=count+2
Method 2:
count=0
while count<=198:
count=count+2
print(count)
4. Print 1st 100 Odd Numbers(1-199)
count=1
while count<=199:
print(count)
count=count+2
5. Find out the average of 10 numbers?
New Concept : totaling

Total=0
Total = total + num

total=0#this going to sum


count=0#this is going to help me run the
loop as many times as i want to
while count<=9:
num=int(input("please enter a
number"))
total=total+num
count=count+1
average=total/10
print("The average of the numbers entered
is: ",average)
Highest & Lowest:

Highest=0

If num>highest:

Highest=num

Lowest=9999

IF num<lowest:

Lowest=num

#highest of 10 numbers
#lowest of 10 numbers
highest=-1
lowest=999999
count=0
while count<=9:
num=int(input("please enter a
number"))
if num>highest:
highest=num
if num<lowest:
lowest=num
count=count+1
print("Highest number is: ", highest)
print("Lowest number is: ",lowest)

Todays Project : HOMEWORK😊

Take 10 numbers, from the user, add the numbers, find out the highest and lowest of the numbers,
output the average of the numbers, sum of the numbers, highest of the numbers, lowest of the
numbers, and the range i.e., the difference between highest and lowest number.

10 minutes:
count=0
highest=-1
lowest=99999
total=0
while count<=9:
num=int(input("number enter karooo :)"))
total=total+num
if num>highest:
highest=num
if num<lowest:
lowest=num
count=count+1
average=total/10
range=highest-lowest
print("The sum of the numbers is: ",total)
print("The average of the numbers is: ",average)
print("The highest number is: ",highest)
print("The lowest number is: ",lowest)
print("The range is: ", range)

Homework:

Example 7-12

Question 1 from practice questions, both parts.

Project :

Try creating a simple game of your own choice using a while loop.

1) Guess the correct number.

Validate using While loop:

Automatic checking for errors, the data entered meets specific criteria…! 😊
Example:

Take marks from the students, find out the average of the marks entered, reject all invalid entries, count
how many entries were invalid.

Output highest and lowest marks as well.

There are total of 10 students in the class.

Output the grade based on the marks.

Marks should be in between 0 to 100 inclusive.

total=0
invalidentries=0
count=0
while count<=9:
marks=int(input("please enter your marks"))
while marks<0 or marks>100:#validation #RANGE CHECK
#6 Types Minimum!
marks=int(input("Invalid marks entered, please
re-enter in between 0 and 100 inclusive"))
invalidentries=invalidentries+1
total=total+marks
if marks>=90:
print("A*")
elif marks>=80:
print("A")
elif marks>=70:
print("B")
else:
print("You need to work hard")
count=count+1
average=total/10
print("Average is: ",average)
print("Invalid Entries are: ",invalidentries)

FOR Loop:

There is no need of a counter.

No NEXT statement.

All you need to do is to start the loop only and give the range for how many times the loop should run.

for count in range(10):


print(count)
this will print from 0 to 9

for count in range(1,10):


print(count)
this will print from 1 to 9.

Lets try printing 1st 100 whole numbers:

for count in range(0,100):


print(count)
# SKIP YOUR HOME WORK :)

HOME WORK 1: Try printing 1st 50 even numbers and odd numbers using for loop.

for count in range(2,101,2):


print(count)

for count in range(1,100,2):


print(count)

For Loop Practice 1:

Take 50 numbers, and output the average of the numbers.

total=0
for x in range(5):
num=int(input("number enter karo"))
total=total+num
avg=total/5
print(avg)

[Link]:

Major Homework apart from projects mentioned above:

Solve example 1-20, and all exam style questions, put all the codes in word document.

NOTE : please don’t take screenshots, copy the code.


Question 5 (B):

fastest=0
slowest=9999
totalfinal=0
for count in range(1,6):
time=int(input("please enter time"))
finalspeed=int(200/time)
print("Final speed of car ", count, " is ",
finalspeed,"km/h")
if finalspeed>fastest:
fastest=finalspeed
if finalspeed<slowest:
slowest=finalspeed
totalfinal=totalfinal+finalspeed
avgspeed=totalfinal/5
print("Highest Speed is: ",fastest)
print("Lowest Speed is: ",slowest)
print("Average speed is: ",avgspeed)

Picking identifiers from a string:

x=0
y=10
print(f"my name is {x} and {y}")
my name is 0 and 10

Question7:

totalitemcost=0
for x in range(10):
itemtype=int(input("please input the item
type"))
partscost=float(input("please input the cost"))
if itemtype==1:
itemcost=partscost*1.5
elif itemtype==2:
itemcost=partscost*2.5
elif itemtype==3:
itemcost=partscost*5.0
print("Your item cost is: ",itemcost)
totalitemcost=totalitemcost+itemcost
averagecost=totalitemcost/10
print("Average cost is: ",averagecost)

[Link] :

Example 1-20, all exam style questions. (Complete document in python)

Arrays:

Data Structure:

1) Variables
2) Constants
3) Array

A data structure that can store multiple values, of same data type.

Basically, it acts as a LIST. [TABLE]

Haseeb Asd
Asdaq Asd
Ibraeem Sdgs
Hijab Asdf
Ahmed Asda
Reem Asd
Afeera Ads
Haider Asd

As index: position where the data is being saved : 8

Dimension: Number of columns : 2

An array that has only 1 dimension : 1D Array

An array that has more than 1 dimension : 2D Array

50 numbers:

Set up an array that has 50 indexes.


50 names and emails.

Set up an array that has 50 indexes and 2 dimensions.

PRINT (“Please enter 5 game names”)

INPUT Games[1]

INPUT Games[2]

INPUT Games[3]

INPUT Games[4]

INPUT Games[5]

GTA
TEKKEN
Xyz
COD
FIFA

I can use these later.

games=[]
for x in range(5):
gamename=input("Please enter game name?")
[Link](gamename)
print(games)

let’s take 10 numbers from the user, store them into the array, and find out the average of the numbers.

0.11
1.12
2.
3.
4.
5.
6.
7.
8.
9.
Total=0+11+12
nums=[]
total=0
for x in range(10):
num=int(input("please enter
10 numbers"))
[Link](num)
total=total+nums[x]
avg=total/10
print(nums)
print(avg)

Store marks of 15 students in an array, find out the highest and lowest marks, the average marks.
Output the grade based on the marks. Count how many students got As and A*s.
marks=[]
highest=-1
lowest=101
total=0
count1=0
count2=0
for x in range(5):
num=int(input("please enter your
marks"))
[Link](num)
if marks[x]>highest:
highest=marks[x]
if marks[x]<lowest:
lowest=marks[x]
total=total+marks[x]
if marks[x]>=90:
Grade="A*"
count1=count1+1
elif marks[x]>=80:
Grade="A"
count2=count2+1
else:
Grade="You need to work hard,
always score more than 80"
print("Your Grade is: ", Grade)
average=total/5
print("Average Marks is: ", average)
print("Highest: ",highest)
print("Lowest: ",lowest)
print("Total A*'s are: ",count1)
print("Total A's are: ",count2)

Store 5 numbers in an array, then take a value from the user, compare if the value exists in the array or
not, if it does, output the value followed by an appropriate prompt, else output “the value isn’t there”.

1) LINEAR SEARCH

nums=[]
for x in range(5):
number=int(input("please enter 5
numbers"))
[Link](number)
searchvalue=int(input("please enter a
number you wanna search"))
for x in range(5):
if nums[x]==searchvalue:
print(nums[x])
print("I found it")
else:
print("Not found at: ",x)
# this is why we need FLAG
LOOPING.......
#set up an array to store marks of
5 students
#output the highest,lowest and
average marks
#output the grades based on the
marks
#A*,A,Try again
marks=[]*5
total=0
highest=0
lowest=9999
for x in range(5):
number=int(input("please enter
your marks"))
[Link](number)
total = total + marks[x]
if marks[x] > highest:
highest=marks[x]
if marks[x] < lowest:
lowest=marks[x]
if marks[x]>=90:
grade="A*"
elif marks[x]>=80:
grade="A"
else:
grade="try again"
print("Grade is:",grade)
avg=total/5
print("Average is:",avg)
print("Highest is:",highest)
print("Lowest is:",lowest)
#set up an array to store marks of 5 students
#output the highest,lowest and average marks
#output the grades based on the marks
#A*,A,Try again
marks=[]*5
total=0
highest=0
lowest=9999
grade=[""]*5
name=[]*5
for x in range(5):
studentname=input("please enter your name")
[Link](studentname)
number=int(input("please enter your marks"))
[Link](number)
total = total + marks[x]
if marks[x] > highest:
highest=marks[x]
if marks[x] < lowest:
lowest=marks[x]
if marks[x]>=90:
grade[x]="A*"
elif marks[x]>=80:
grade[x]="A"
else:
grade[x]="try again"
avg=total/5
print("Average is:",avg)
print("Highest is:",highest)
print("Lowest is:",lowest)
for x in range(5):
print("Name:",name[x],"has scored",marks[x],"with grade",grade[x])
Search through the array:

1) Populate the array (enter some data into the array)


2) Search through the array index after index
3) Check if the record is found
4) Or whole array has been searched through

NOTE : Understand and use flag looping 😊

Linear Search:
#Searching through the array:
nums=[]*5
for x in range(5):
num=int(input("please enter a
number"))
[Link](num)
count=0
found=False
searchvalue=int(input("please enter a
number you are looking for"))
while count<5 and found==False:
if searchvalue==nums[count]:
found=True
else:
count=count+1
if found==True:
print("yayyy i found it")
print("i found it at: ",count)
else:
print("i didnt found it")
Bubble Sort:

An algorithm used to sort an array into an order, ascending, descending or alphabetical.


[Link]

[Link]

why there is a need to use flag looping:

swap=False

that is swap = false or top =0


num=[101,99,103,1,7]
top=5
swap=True
while top!=0 and swap!=False:
swap=False
for count in range(top-1):
if num[count]>num[count+1]:
temp=num[count]
num[count]=num[count+1]
num[count+1]=temp
swap=True
top=top-1
print(num)

Set up an array to store 10


numbers, take all the values from
the user, and check either 1631
exists in the array or not, using
linear search, output appropriate
prompt, then sort the array into
descending order, output the
contents of the sorted array as
well.
nums=[]*10
for x in range(10):
num=int(input("please enter 10
numbers"))
[Link](num)
searchvalue=1631
found=False
index=0
while index<10 and found==False:
if searchvalue==nums[index]:
found=True
else:
index=index+1
if found==True:
print("i found it")
else:
print("naheee mila")
swap=True
top=10
while top!=0 and swap!=False:
swap=False
for count in range(top-1):
if nums[count]>nums[count+1]:
temp=nums[count]
nums[count]=nums[count+1]
nums[count+1]=temp
swap=True
top=top-1
for x in range(10):
print(nums[x])

2D Arrays 😊
Linear search and bubble sort
practice…!

NOTE : write the bubble sort code,


from scratch 5 times…!
1) Constants (fixed value)
Num=3.5
2) Variables (user-defined values)
Num=input(“please enter a
number”)
3) Arrays (store multiple values)
[Link](num) (you can add
as many numbers as you can)

2D Array :
We will have two dimensions..:)
For example you want to store names:

nums=[""]*5

For example you want to store integer values:

nums=[0]*5

For example you want to store floating values:

nums=[0.0]*5

2d ARRAY:

Remember : CO ORDINATES AND ROWS & COLUMNS…!

Set up a 1D array to store 3 names from the user, and output the names…!

names=[]*3

for x in range(3):
name=input("please enter your name")
[Link](name)
print(names)

Lets set up a 2D array, with 5 rows and 5 columns.


rows, cols=(5,5)
information=[[0]*cols]*rows
print(information)

rows, cols=(5,5)
information=[[0]*cols]*rows
for row in range(5):
for col in range(5):
print(information[row][col])

Set up a 2D array to store names and passwords of 5 employees and output the data as well.

Dimensions : 2

Indexes : 5

rows, cols=(5,2)
information=[[None]*cols for _ in
range(rows)]
for row in range(5):
name=input("please enter your name")
information[row][0]=name
password=input("please enter your
password")
information[row][1]=password
print(information)
Set up an 2D array to store 5 names and 5 passwords output the contents of the array.

Set up a 2D array for 3 rows and 7 columns and initialize all the array elements as “EMPTY”.

PRACTICE 2D Arrays 😊

Array Revision and python modules on array:

students=["haseeb","ibraheem","hijab","a
sdaq"]
print(students)

students=["haseeb","ibraheem","hijab","a
sdaq"]
for x in range(4):
print(students[x])

students=[]
for x in range(4):
studentname=input("please enter your
name")
[Link](studentname)
for x in range(4):
print(students[x])

Operation 1: Append

Adds the element to the end of the array.


Operation 2: Clear

Removes all the elements from the array.

Operation 3: Copy

Returns a copy of the array.

Operation 4: Count

Returns the number of elements with the specified value.

students=["haseeb","hijab","ibraheem","h
ijab","asdaq","haseeb","haseeb"]
name=[Link]("hijab")
print(name)

Operation 5: Extend:

Add elements of a list or array into another. [Merge]

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](students)
print(teachers)

Operation 6: Index

Returns the index of the element in the array.

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
position=[Link]("ibraheem")
position2=[Link]("haider")
print(position)
print(position2)
Operation 7: Insert

Insert an element at a specific value.

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](0,"lenovo")
[Link](3,"hp")
print(students)

Operation 8 : Pop

Remove an element from a specified position. Always mention the position i.e., index.

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](0)
[Link](2)
print(students)

Operation 9 : Remove

Removes the element from the index. (You may use the element name)

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]("haseeb")
[Link]("asdaq")
print(students)

Operation 10 : Reverse
Reverses the order of array.

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]()
print(students)
[Link]()
print(teachers)

Operation 11 : Sort

Sorts the array

students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]()
[Link]()
print(students)
print(teachers)

# create a 2d array to store 5 names and


emails...! and output the contents of
the array
rows,cols=(5,2)
information=[[None]*cols for _ in
range(rows)]
for row in range(5):
name=input("Please enter your name")
email=input("Please enter your
email")
information[row][0]=name
information[row][1]=email
for row in range(5):
for col in range(2):
print(information[row][col])

rows,cols=(5,2)
information=[[None]*cols for _ in
range(rows)]
for row in range(5):
name=input("Please enter your name")
email=input("Please enter your
email")
information[row][0]=name
information[row][1]=email
print(information)

Practice 2D Arrays: 😊

Set up a 2D array, for 100 rows and 4 columns, set all elements of the array as “empty”.

rows=100
cols=4
data=[["empty" for _ in range(cols)]for
_ in range(rows)]
print(data)

Set up a 2D array to store names, emails and passwords for 5 clients. Output the contents of the array,
check either has123 exists in the passwords or not. If it does output “confirmed”, else “output password
does not match”.

rows=5
cols=3
data=[[None for _ in range(cols)]for _ in
range(rows)]
for row in range(5):
name=input("please enter your name")
email=input("please enter your email")
password=input("please enter your
password")
data[row][0]=name
data[row][1]=email
data[row][2]=password
found=False
index=0
while index<4 and found==False:
if data[index][2]=="has123":
found=True
else:
index=index+1
if found==True:
print("confirmed")
else:
print("password does not match")
for row in range(5):
for col in range(3):
print (data[row][col])

rows=5
cols=3
marks=[[None for _ in range(cols)]for _ in
range(rows)]
for row in range(5):
subject1=(int(input("please enter your
marks for subject 1 ")))
subject2 = (int(input("please enter your
marks for subject 2 ")))
subject3 = (int(input("please enter your
marks for subject 3 ")))
marks[row][0]=subject1
marks[row][1] = subject2
marks[row][2] = subject3
totalmarks=[0 for _ in range(rows)]
for row in range(5):
for col in range(3):
totalmarks[row]=totalmarks[row]
+marks[row][col]
average=totalmarks[row]/5
print("Average of Student ", row+1, " is ",
average)

(HOMEWORK…!)

Set up a 2D array to store marks of 5 students studying 3 subjects each, add the marks and store them
into a 1D array, find out the average of each student individually.

Set up a 2D array info to store names and emails for 5 employees, populate the array and sort the array
in order of emails using bubble sort.

Stacks:

Data Structure : ADT (Abstract Data Type)

It is used to store data.

LIFO (Last in First Out) (The data being added first would be the last one to be removed)
1) LIFO
2) Two pointers : top pointer, base pointer
3) Top pointer : last element of the stack
4) Base pointer : 1st element of the stack
5) If you want to add a data element the process is called ‘push’.
6) If you want to delete a data element the process is called ‘pop’.
7) Push : top + 1 (increment the top pointer) and then add the data element.
8) Pop : Remove the data element and then top – 1.
9) Whenever trying to push an element always make sure stack is not full.
10) Whenever trying to pop an element always make sure stack is not empty.
The element added 1st is the last one to be removed.

Code :

How can you check that stack is empty?

top pointer = -1

How can you check the stack is full?

top pointer = 5

that is the top pointer is equal to the total number of elements

How to add a data element?

Increment the top pointer

Add the data

How to remove the data element?

Store the data element in a temp

Decrement the top pointer

stack=[None for _ in range(5)] #setting a stack


as an array
toppointer=-1
stackfull=5
num=int(input("how many elements you want to
add in stack"))
while num<0 or num>5:
num=int(input("please enter a number in
between 0 and 5, re-enter"))
for x in range(num): #adding an element and
updating the pointers
if toppointer<stackfull:
numadd=int(input("please enter a number
you want to add"))
toppointer=toppointer+1
[Link](toppointer,numadd)
else:
print("stack is full, cannot push")
numremove=int(input("how many elements you want
to remove"))
while numremove<0 or numremove>5: # removing
and element and updating the pointers
numremove=int(input("please enter a number
in between 0 and 5, re-enter"))
for x in range(numremove):
if toppointer==-1:
print("stack is empty, cannot pop")
else:
temp=stack[toppointer]
stack[toppointer]=0
toppointer=toppointer-1
for x in reversed(range(5)):
print ("Index: ", x, " :", stack[x])

global stackdata
stackdata=[0]*10
global stackpointer
stackpointer=0
def printing():
global stackdata
global stackpointer
print("Stack Pointer: ", stackpointer)
print("Stack Data:")
for x in range(10):
print(stackdata[x])
def push(datatoadd):
global stackdata
global stackpointer
if stackpointer==10:
return False
else:
stackdata[stackpointer]=datatoadd
stackpointer=stackpointer+1
return True
def pop():
global stackdata
global stackpointer
if stackpointer==0:
return -1
else:
temp=stackdata[stackpointer-1]
stackdata[stackpointer-1]=0
stackpointer=stackpointer-1
return temp

for x in range(11):
numbers=int(input("please enter a
number"))
if push(numbers)==True:
print("Data added successfully")
else:
print("Stack is full cannot push")
printing()
for x in range(2):
result=pop()
if result==-1:
print("Stack is empty cannot pop")
else:
print("The deleted element is: ",
result)
printing()

Stacks Videos:

[Link]

Queues:

1) FIFO (First in First out principle)


2) The element being added first would be the first one to be removed.
3) Operations:
a) Enqueue : add an element
b) Dequeue : remove an element
4) Pointers
a) Front Pointer (this will point to the 1st element of the queue)
b) Rear Pointer (this will point to the last element of the queue)
5) CONCENTRIC BEHAVIOR OF QUEUES

NOTE : Always check the queue is not full when enqueuing and not empty when dequeuing.

1) How you can check the queue is full?


When rear pointer is equals to queue full, where queue full is the highest index of the array,
e.g., if array has a capacity to store 10 elements, queue full will be equal to 10.
2) How you can check the queue is empty?
When front pointer or rear pointer are equal to 0, means they are not pointing to anything, this
means queue is empty.
If you want to try writing out a code for queues, in which, you may set up a queue, and then add few
elements and remove few elements, you may try it.

Queues video

[Link]
1) Queue works on FIFO.
2) Operations :
a) Enqueue
b) Dequeue
3) Pointers
a) Front Pointer (Point to the 1st element of the queue)
b) Rear Pointer (Point to the last element of the queue)
4) Enqueue : Queue is not full
Queue will be full when rearpointer = queuefull (maximum number of elements in the queue,
according to array)
5) Dequeue : Queue should not be empty
Queue will be empty when rear pointer is equals t0 -1.
6) How to enqueue : Rearpointer +1, add the element.
7) How to dequeue: remove the element, you may store it into temp, set the index to zero,
frontpointer +1.
8) Concentric behavior of queues.
While removing or adding, it is possible that elements are at the start of the queue.
In that situation, if rear pointer or front pointer is equals to queuefull, then rather adding one
into the pointers, set the pointers to 1.

queue=[None for _ in range(5)]


queuefull=5
queuelength=0
frontpointer=0
rearpointer=-1
addelement=int(input("please enter how many
elements you want to add"))
while addelement<0 or addelement>5:
addelement=int(input("please enter in
between 0 and 5"))
for x in range(addelement):
if queuelength==queuefull:
print("queue is full, cannot
enqueue")
else:
if rearpointer==queuefull:
rearpointer=1
else:
rearpointer=rearpointer+1
element=int(input("please enter a
value you want to add"))
[Link](rearpointer,element)
queuelength=queuelength+1
removeelement=int(input("how many elements
you want to remove"))
while removeelement<0 or removeelement>5:
removeelement = int(input("please enter
a number in between 0 and 5"))
for x in range(removeelement):
if queuelength==0:
print("queue is empty, cannot
dequeue")
else:
temp=queue[frontpointer]
queue[frontpointer]=0
if frontpointer==queuefull:
frontpointer=1
else:
frontpointer=frontpointer+1
queuelength=queuelength-1
for x in range(5):
print ("Index Number: ", x, queue[x])

Queue with Subroutines :


Output:
"C:\Users\123\PycharmProjects\Introduction to Python\.idea\VirtualEnvironment\Scripts\
[Link]" "C:\Users\123\PycharmProjects\Introduction to Python\Introduction\About\
[Link]"
how many elements you want to store in the queue4
please enter a data element to add11
element added successfully
please enter a data element to add12
element added successfully
please enter a data element to add13
element added successfully
please enter a data element to add14
element added successfully
Index: 0 11
Index: 1 12
Index: 2 13
Index: 3 14
Index: 4 None
FrontPointer: 0
RearPointer: 3
how many elements you want to dequeue2
The element removed is: 11
The element removed is: 12
Index: 0 0
Index: 1 0
Index: 2 13
Index: 3 14
Index: 4 None
FrontPointer: 2
RearPointer: 3

Process finished with exit code 0

Code:

global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
queue=[None for _ in range(5)]
frontpointer=0
rearpointer=-1
queuefull=5
queuelength=0
def subprintkrwado():
global queue
global frontpointer
global rearpointer
for x in range(5):
print("Index: ",x," ",queue[x])
print("FrontPointer: ",frontpointer)
print("RearPointer: ",rearpointer)
def enqueue():
global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
if queuelength==queuefull:
print("Queue is full, cannot
enqueue")
return False
else:
if rearpointer==queuefull:
rearpointer=1
else:
rearpointer=rearpointer+1
num=int(input("please enter a data
element to add"))
[Link](rearpointer,num)
queuelength=queuelength+1
return True
def dequeue():
global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
if queuelength==0:
print("Queue is empty, cannot
dequeue")
return False
else:
temp=queue[frontpointer]
queue[frontpointer]=0
if frontpointer==queuefull:
frontpointer=1
else:
frontpointer=frontpointer+1
queuelength=queuelength-1
return temp
elements=int(input("how many elements you
want to store in the queue"))
while elements<0 or elements>5:
elements = int(input("please enter in
between 0 and 5"))
for x in range(elements):
if enqueue()==True:
print("element added successfully")
else:
print("Queue is full")
subprintkrwado()
removeelements=int(input("how many elements
you want to dequeue"))
while removeelements<0 or removeelements>5:
removeelements = int(input("please enter
in between 0 and 5"))
for x in range(removeelements):
elementremoved=dequeue()
if elementremoved==False:
print("Queue is empty, no more
elements to dequeue")
else:
print("The element removed is:
",elementremoved)
subprintkrwado()
# Linked List : (Notes)

#Set up of Linked List


data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)

With Modules:

#Set up of Linked List


global data
global pointers
global startpointer
global heapstartpointer
def printing():
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
printing()
printing()

Set up of linked list and adding an item:

# Linked List : (Notes)

#Set up of Linked List


data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)

numbers=int(input("please enter how many


numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter in
between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an
element you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp

for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
Setup, adding an element, and searching through a linked list:

# Linked List
#Set up of Linked List
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
#printing of setup
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
#adding an element into the linked list
numbers=int(input("please enter how many
numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter in
between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an
element you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp
#printing after adding
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
#searching through the linked list
searchvalue=int(input("please enter a value
you want to search"))
itempointer=startpointer
found=False
while itempointer!=-1 and found==False:
if data[itempointer]==searchvalue:
found=True
else:
itempointer=pointers[itempointer]
if found==True:
print("Item found at: ",itempointer)
else:
print("Item not found")

Modular Code:

# Linked List
#Set up of Linked List
global data
global pointers
global startpointer
global heapstartpointer
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
#printing of setup
def printing():
global data
global pointers
global startpointer
global heapstartpointer
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
printing()
#adding an element into the linked list
def addelement():
global data
global pointers
global startpointer
global heapstartpointer
numbers=int(input("please enter how
many numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter
in between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an
element you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp
addelement()
#printing after adding
printing()
#searching through the linked list
def searching():
searchvalue=int(input("please enter a
value you want to search"))
itempointer=startpointer
found=False
while itempointer!=-1 and found==False:
if data[itempointer]==searchvalue:
found=True
else:
itempointer=pointers[itempointer]
if found==True:
print("Item found at:
",itempointer)
else:
print("Item not found")
searching()

Complete Code for Linked List:

Setup, Search, Adding and Deleting:


# Linked List
#Set up of Linked List
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
#printing of setup
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ", heapstartpointer)
print("Start Pointer: ",startpointer)
#adding an element into the linked list
numbers=int(input("please enter how many
numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter in
between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an element
you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp
#printing after adding
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ", heapstartpointer)
print("Start Pointer: ",startpointer)
#searching through the linked list
searchvalue=int(input("please enter a value you
want to search"))
itempointer=startpointer
found=False
while itempointer!=-1 and found==False:
if data[itempointer]==searchvalue:
found=True
else:
itempointer=pointers[itempointer]
if found==True:
print("Item found at: ",itempointer)
else:
print("Item not found")
#delete an element
deleteelement=int(input("please enter an
element you want to delete"))
index=startpointer
if startpointer==-1:
print("List is empty")
else:
while data[index]!=deleteelement and index!
=-1:
oldindex=index
index=pointers[index]
if index==-1:
print("Element not found in the list")
else:
temppointer=pointers[index]
pointers[index]=heapstartpointer
heapstartpointer=index
pointers[oldindex]=temppointer
data[index]=None
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ", heapstartpointer)
print("Start Pointer: ",startpointer)

Binary Tree: [Records]

Introduction:

Visualize:

I want to store few names into the tree.

1) Ali
2) Haseeb
3) Ibraheem
4) Laiba
5) Zainab
6) Asad
7) Ahmed
8) Bilal

It takes the first value as the root node


and then compares all the incoming
values, with the root node. If the
incoming value is greater than the root
node it adds it to the right of the tree
and if it is less

than the root node it adds it to the left


of tree.

Every incoming values is first compares


with the root node and then every node
until it finds an appropriate place.
Records: (composite data type) (user-defined data type)

Example:

DECLARE Name : STRING

TYPE Information
DECLARE Name : STRING
DECLARE Subject : STRING
DECLARE Age : INTEGER
DECLARE DoB : DATE
DECALRE SalaryPaid : BOOLEAN
END TYPE

DECLARE Data : Information


[Link]=”CS”
[Link]=”Haseeb”

DECLARE Numbers : ARRAY[1:100] OF Information


//this will be able to store 100 * fields (5) elements

DECLARE Numbers : ARRAY[1:100] OF STRING


//this will be able to store 100 elements

Numbers[index].Age=10

Numbers[3].Age=15

Numbers[3].Name=”Haseeb”

NOTE : There is no concept of records in python 😊

We will be using classes to set records.


class information:
def __init__(self,n,a): #it
takes values from main program
[Link]=n
[Link]=a
#type information
#DECLARE name : STRING
#DECLARE age : INTGER

data=information("haseeb",15)
print([Link])
print([Link])

please practice classes to create records….

Let’s create a record (Data) to store names, emails and passwords.

Create two variables of Data, take values from the user, and output the values as well.
class data:
def __init__(self,n,e,p):
[Link]=n
[Link]=e
[Link]=p

value1=input("please enter your


name")
value2=input("please enter your
email")
value3=input("please enter your
password")
data1=data(value1,value2,value3)
print([Link])
print([Link])
print([Link])

class data:
def __init__(self,n,e,p):
[Link]=n
[Link]=e
[Link]=p
for x in range(2):
value1=input("please enter your name")
value2=input("please enter your email")
value3=input("please enter your password")
data1=data(value1,value2,value3)
print([Link])
print([Link])
print([Link])

create a record to store 4 fields as : name,age,salary,address for 10 teachers.

array

class teacherdata:
def __init__(self,n,a,s,add):
[Link]=n
[Link]=a
[Link]=s
[Link]=add

teachers=[]*2
for x in range(2):
val1=input("please enter your name ")
val2 = int(input("please enter your age "))
val3 = float(input("please enter you
salary"))
val4 = input("please enter your address ")
teacher=teacherdata(val1,val2,val3,val4)
[Link](teacher)

for x in range(2):
print(teachers[x].name)
print(teachers[x].age)
print(teachers[x].salary)
print(teachers[x].address)

Binary Tree:

Create a record which will have three fields, leftpointer,rightpointer,data

an array to represent binary tree

null pointer that we will set as -1

rootpointer

when the tree is empty, there will be no elements, rootpointer = nullpointer

free pointer

that will point to the latest element added

when the tree is empty, free pointer will point to nothing that is it will be equal to zero

and when the tree is full, it will point to the null pointer

left pointers act as linked list

and all the values of free pointer are updated using the left pointer rather than incrementing

Binary Tree Set Up :

class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r

tree=[]*6
nullpointer=-1
freepointer=0
rootpointer=-1
for x in range(5):
index=x+1
data=treenode(index,"",0)
[Link](data)
data2=treenode(-1,"",0)
[Link](6,data2)

for x in range(6):
print("Index: ",x,"-
>",tree[x].leftpointer,"->",tree[x].data,"-
>",tree[x].rightpointer)

class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r

#setting up binary tree


tree=[]*6
nullpointer=-1
freepointer=0
rootpointer=-1
for x in range(5):
index=x+1
data=treenode(index,"",0)
[Link](data)
data2=treenode(-1,"",0)
[Link](6,data2)
for x in range(6):
print("Index: ",x,"-
>",tree[x].leftpointer,"-
>",tree[x].data,"-
>",tree[x].rightpointer)
#adding an element into binary tree
newelement=input("please enter a data
item you want to add")
#checking the tree isn't full
if freepointer!=nullpointer:
newnodepointer=freepointer
freepointer=tree[freepointer].leftpoin
ter
tree[newnodepointer].data=newelement
tree[newnodepointer].leftpointer=-
1

tree[newnodepointer].rightpointer=-1
#checking if the tree was empty and
this is 1st data element
if rootpointer==nullpointer:
rootpointer=newnodepointer
for x in range(6):
print("Index: ",x,"-
>",tree[x].leftpointer,"-
>",tree[x].data,"-
>",tree[x].rightpointer)
#adding an element into binary tree

Complete Binary Tree:

class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r

#setting up binary tree


tree=[]*10
nullpointer=-1
freepointer=0
rootpointer=-1
for x in range(9):
index=x+1
data=treenode(index,"",0)
[Link](data)
data2=treenode(-1,"",0)
[Link](10,data2)
for x in range(10):
print("Index: ",x,"->",tree[x].leftpointer,"-
>",tree[x].data,"->",tree[x].rightpointer)
#adding an element into binary tree
for x in range(8):
newelement=input("please enter a data item you want to
add")
#checking the tree isn't full
if freepointer != nullpointer:
newnodepointer = freepointer
freepointer = tree[freepointer].leftpointer
tree[newnodepointer].data = newelement
tree[newnodepointer].leftpointer = -1
tree[newnodepointer].rightpointer = -1
#checking if the tree was empty and this is 1st data element
if rootpointer==nullpointer:
rootpointer=newnodepointer
else:
thisnodepointer=rootpointer
while thisnodepointer!=nullpointer:
previousnodepointer=thisnodepointer
if tree[thisnodepointer].data>newelement:
turnedleft=True

thisnodepointer=tree[thisnodepointer].leftpointer
else:
turnedleft=False

thisnodepointer=tree[thisnodepointer].rightpointer
if turnedleft==True:

tree[previousnodepointer].leftpointer=newnodepointer
else:

tree[previousnodepointer].rightpointer=newnodepointer
for x in range(10):
print("Index: ",x,"->",tree[x].leftpointer,"-
>",tree[x].data,"->",tree[x].rightpointer)
#search an element
searchelement=input("please enter an element to search")
index=rootpointer
while index!=nullpointer and tree[index].data!
=searchelement:
if tree[index].data>searchelement:
index=tree[index].leftpointer
else:
index=tree[index].rightpointer
if index==nullpointer:
print("The element is not in the tree")
else:
print("Element found at: ", index)

Homework:

Re-arrange the binary tree in modules.


OOP:

class dog:
def __init__(self,n,a):
self.__name=n
self.__age=a
def bark(self):
print(self.__name," says
woooooooffff")
def getage(self):
return self.__age

mydog=dog("Scooby",3)
print([Link]())
mydogage=[Link]()
print("Age: ",mydogage)

1. *Class and Object Creation*

python
# Define a class named `Person`
class Person:
# Constructor to initialize the person's name and age
def __init__(self, name, age):
[Link] = name
[Link] = age

# Method to display person's details


def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")

# Create an instance of the `Person` class


person1 = Person("Alice", 30)
person1.display_info() # Output: Name: Alice, Age: 30

2. *Inheritance*

python
# Define a base class named `Animal`
class Animal:
def __init__(self, name):
[Link] = name

def speak(self):
print(f"{[Link]} makes a sound")
# Define a derived class named `Dog` that inherits from `Animal`
class Dog(Animal):
def speak(self):
print(f"{[Link]} barks")

# Create an instance of the `Dog` class


dog = Dog("Buddy")
[Link]() # Output: Buddy barks

3. *Encapsulation*

python
# Define a class named `BankAccount`
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount
else:
print("Deposit amount must be positive")

def withdraw(self, amount):


if 0 < amount <= self.__balance:
self.__balance -= amount
else:
print("Invalid withdrawal amount")

def get_balance(self):
return self.__balance

# Create an instance of the `BankAccount` class


account = BankAccount(1000)
[Link](500)
[Link](200)
print(account.get_balance()) # Output: 1300

These examples cover basic concepts of OOP including classes, objects,


inheritance, and encapsulation.

Question 11:
import datetime
class Character:
#self.__CharacterName : STRING
#self.__DateOfBirth : DATE
#self.__Intelligence : REAL
#self.__Speed : INTEGER
def __init__(self,cn,db,integ,sp):
self.__CharacterName=cn
self.__DateOfBirth=db
self.__Intelligence=integ
self.__Speed=sp
def GetIntelligence(self):
return self.__Intelligence
def GetName(self):
return self.__CharacterName
def SetIntelligence(self,value):
self.__Intelligence=value
def Learn(self):

self.__Intelligence=self.__Intelligence*1.1
def ReturnAge(self):
return 2023-self.__DateOfBirth.year

class MagicCharacter(Character):
def __init__(self,elem,cn,db,integ,sp):
super(). __init__(cn,db,integ,sp)
self.__Element=elem
def Learn(self):
if self.__Element=="Fire" or
self.__Element=="Water":

super().SetIntelligence(super().GetIntelligence(
)*1.2)
elif self.__Element=="Earth":
super().SetIntelligence(super().GetIntelligence(
) * 1.3)
else:

super().SetIntelligence(super().GetIntelligence(
) * 1.1)

FirstCharacter=Character("Royal",[Link]
me(2019,1,1),70,30)
[Link]()
print("Name of the character is:
",[Link](),",the age is
",[Link]()," with intelligence
",[Link]())

FirstMagic=(MagicCharacter("Fire","Light",dateti
[Link](2018,3,3),75,22))
[Link]()
print("Name is: ",[Link](),"and age
is",[Link](),"with a intelligence
of",[Link]())

global DataArray
DataArray=[None for _ in range(100)]

def ReadFile():
try:
reader = open(r"C:\Users\123\Desktop\
[Link]", "r")
for x in range(100):
DataArray[x]=[Link]()
DataArray[x].rstrip('/n')
DataArray[x]=int(DataArray[x])
[Link]()
except IOError:
print("file not found")

ReadFile()
print(DataArray)
#left,right,mid,len

reader=open(r"file path","mode")
then use reader
same goes for writer and if you want to append

Question 1:
TheData=[20,3,4,8,12,99,4,26,4]
def searchsearch(TheData):
num=int(input("please enter a
number"))
found=False
index=0
while found==False and index<9:
if TheData[index]==num:
print("Found")
found=True
return True
else:
index=index+1
print("Not Found")
return False
searchsearch(TheData)

Question 3 File Handling:

def PrintArray(DataArray):
print(DataArray)
def
LinearSearch(DataArray,searchval
ue):
count=0
for x in range(25):
if
DataArray[x]==searchvalue:
count=count+1
return count
DataArray=[]
try:
reader=open(r"C:\Users\123\
Desktop\[Link]","r")
for Line in reader:
[Link](int(Line))
[Link]()
except IOError:
print("File not found")
PrintArray(DataArray)
searchnum=int(input("please
enter a number in between 0 and
100"))
while searchnum<0 or
searchnum>100:
searchnum =
int(input("please enter a number
in between 0 and 100"))
times=LinearSearch(DataArray,sea
rchnum)
print("The number",searchnum,"is
found",times)

Question 5: ADTS : STACKS (25 marks)


global StackData
global StackPointer
StackData=[0 for _ in range(10)] #integer
StackPointer=0 #integer

def output():
global StackData
global StackPointer
for x in range(10):
print(x,"=>",StackData[x])
print("Stack Pointer:",StackPointer)
def push(num): #integer
global StackData
global StackPointer
if StackPointer==10:
return False
else:
StackData[StackPointer]=num
StackPointer=StackPointer+1
return True
def pop():
global StackData
global StackPointer
if StackPointer==0:
return -1
else:
temp=StackData[StackPointer-1]
StackPointer=StackPointer-1
return temp

for x in range(11):#0-10,prints 11 times


number=int(input("please enter a
number you want to add"))
if push(number)==True:
print("Number Added
Successfully")
else:
print("Stack is full")
output()
pop()
pop()
output()
Searching & Sorting Altogether:
global numbers
global lowerbound
global upperbound
numbers=[92,56,32,19,6,3]
def insertionsort():
global numbers
global lowerbound
global upperbound
upperbound = len(numbers)
lowerbound = 0
for index in
range(lowerbound+1,upperbound):
key=numbers[index]
place=index-1
if numbers[place]>key:
while place>=lowerbound and
numbers[place]>key:
temp=numbers[place+1]
numbers[place+1]=numbers[place]
numbers[place]=temp
place=place-1
def printing():
global numbers
for x in range(len(numbers)):
print(x,"=>",numbers[x])
def bubblesort():
global numbers
swap=True
top=len(numbers)
while swap!=False and top!=0:
swap=False
for x in range(top-1):
if numbers[x]>numbers[x+1]:
temp=numbers[x]
numbers[x]=numbers[x+1]
numbers[x+1]=temp
swap=True
top=top-1
def linearsearch():
global numbers
searchvalue=int(input("please enter a
search value"))
found=False
index=0
while found==False and
index<len(numbers):
if numbers[index]==searchvalue:
found=True
else:
index=index+1
if found==True:
print("I found it at:",index)
else:
print("Not found")
def binarysearch():
global numbers
global lowerbound
global upperbound
lowerbound=0
upperbound=len(numbers)
searchvalue = int(input("please enter
a search value"))
found = False
while found==False and
lowerbound<=upperbound:
index=int((upperbound+lowerbound)/2)
if searchvalue==numbers[index]:
found=True
if searchvalue>numbers[index]:
lowerbound=index+1
if searchvalue<numbers[index]:
upperbound=index-1
if found==True:
print("I found it at:",index)
else:
print("Not found")

printing()
exit=False
while exit==False:
choice=int(input("Press 1 to search,
Press 2 to Sort, Press 3 to exit"))
if choice==1:
nextchoice1=int(input("Press 1
for Linear Search, Press 2 for Binary
Search"))
if nextchoice1==1:
linearsearch()
else:
binarysearch()
elif choice==2:
nextchoice2=int(input("Press 1
for Bubble Sort, Press 2 for Insertion
Sort"))
if nextchoice2==1:
bubblesort()
printing()
else:
insertionsort()
printing()
else:
print("Press Enter again")
exit=True

You might also like