Você está na página 1de 91

ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

1) STRING
STEP 1: Python Program to Reverse a String without using Recursion
This is a Python Program to reverse a string without using recursion.

STEP 2: Problem Description


The program takes a string and reverses the string without using
recursion.

STEP 3: Problem Solution


1. Take a string from the user
2. Use string slicing to reverse the string
3. Print the reversed string
4. Exit

STEP 4: Program/Source Code


Here is source code of the Python Program to reverse a string
without using recursion. The program output is also shown below.
a=str(input("Enter a string: "))
print("Reverse of the string is: ")
print(a[::-1])

1
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

STEP 5: Program Explanation


1. User must enter a string
2. By giving the increment value as -1, string slicing is used to reverse
the string
3. The reverse string is printed

STEP 6: Runtime Test Cases

Case 1:
Enter a string: hello
Reverse of the string is:
olleh

Case 2:
Enter a string: test
Reverse of the string is:
tset

2
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

2) Python Membership and Identity Operators | in, not in,


is, is not
Membership Operators
Membership operators are operators used to validate the membership of a
value. It test for membership in a sequence, such as strings, lists, or tuples.
1. in operator : The ‘in’ operator is used to check if a value exists in a
sequence or not. Evaluates to true if it finds a variable in the specified
sequence and false otherwise.

# Python program to illustrate


# Finding common member in list
# using 'in' operator
list1=[1,2,3,4,5]
list2=[6,7,8,9]
for item in list1:
if item in list2:
print("overlapping")
else:
print("not overlapping")
Output: not overlapping
Same example without using in operator:

# Python program to illustrate


# Finding common member in list
# without using 'in' operator

# Define a function() that takes two lists


def overlapping(list1,list2):

c=0
d=0
for i in list1:
c+=1
for i in list2:
d+=1
for i in range(0,c):
for j in range(0,d):

3
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

if(list1[i]==list2[j]):
return 1
return 0
list1=[1,2,3,4,5]
list2=[6,7,8,9]
if(overlapping(list1,list2)):
print("overlapping")
else:
print("not overlapping")
Output: not overlapping
2. ‘not in’ operator- Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.

# Python program to illustrate


# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50 ];

if ( x not in list ):
print "x is NOT present in given list"
else:
print "x is present in given list"

if ( y in list ):
print "y is present in given list"
else:
print "y is NOT present in given list"
Identity operators
In Python are used to determine whether a value is of a certain class or type.
They are usually used to determine the type of data a certain variable contains.
There are different identity operators such as
1. ‘is’ operator – Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise.

# Python program to illustrate the use


# of 'is' identity operator
x=5

4
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

if (type(x) is int):
print ("true")
else:
print ("false")
Output: true
2. ‘is not’ operator – Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.

# Python program to illustrate the


# use of 'is not' identity operator
x = 5.2
if (type(x) is not int):
print ("true")
else:
print ("false")
Output: true

5
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

3) Array methods in python with examples


This is a question to discuss about the array methods which are there in
python by giving example of each.Array is a container which can hold a fix
number of items and these items should be of the same type. Most of the data
structures make use of arrays to implement their algorithms.

Tools and concepts


a)sort() Sorts the list.

b)index() Returns the index of the first element with the specified value.

c)reverse() Reverses the order of the list.

d)append() Adds an element at the end of the list.

Algorithm
step 1 :make a list using variable or constants only.

step 2 :apply the function to the list.

step 3 :prints the list after applying the function. ie the new list.

Program
1. sort ()

>>> v =['a' , 'u' , 'i' , 'e' , 'o' ]

>>> v.sort()

>>> print ('sorted with v')

sorted list : ['a' , 'e' , 'i' , 'o' , 'u']

2. index ()

>>> n = [ 100 , 200 , 300 , 400 ]

>>> index= n.index (100)

6
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

>>> print ('the index of 100 ' : , index)

The index of 100 : 0

3.reverse ()

>>> l = [ 1 , 2 , 3 , 4 ]

>>> l.reverse()

>>> print ("reverse list : l")

reverse list : [ 4 , 3 , 2 , 1 ]

4.append ()

>>> n = [ 1 , 2 , 3 , 4 ]

>>> n = append (5)

>>> print ('adding number n')

adding number : [ 1 , 2 , 3 , 4 , 5 ]

Flowchart
START

Input Number to make a list

Apply the function to the particular list

Print the new list

Output

7
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

4) FILE HANDLING
What is File Handling? Explain the file made with and example.
Explanation: In this question we have to explain what is file handling and how
is file handling and how files are made with an example.
Tools and Concepts: A file handling is one of the most important part of any
language, python supports file handling and allows user to handle files to read
and unite files.
There are two types of file which python supports:
a) Text File b) Binary File
A file represents a sequence of byte on the disk where a group of related data
is stored. File is created for permanent storage of the key function of working
with file in python’s the open() function.

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w'
exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if it
'a'
does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

open() – Python has a built-in function open() to open a file. This function
returns a file object, also called a handle, as it is used to read or modify the file
accordingly. We can specify the mode while opening a file. In mode, we specify
whether we want to read 'r', write 'w' or append 'a' to the file. We also
specify if we want to open the file in text mode or binary mode.

8
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Python File Methods


There are various methods available with the file object. Some of them have
been used in above examples.

Here is the complete list of methods in text mode with a brief description.

Method Description

Close an open file. It has no effect if the file is already


close()
closed.

Separate the underlying binary buffer from


detach()
the TextIOBaseand return it.

fileno() Return an integer number (file descriptor) of the file.

flush() Flush the write buffer of the file stream.

isatty() Return True if the file stream is interactive.

Read atmost n characters form the file. Reads till end


read(n)
of file if it is negative or None.

readable() Returns True if the file stream can be read from.

Read and return one line from the file. Reads in at


readline(n=-1)
most nbytes if specified.

Read and return a list of lines from the file. Reads in at


readlines(n=-1)
most n bytes/characters if specified.

Change the file position to offset bytes, in reference


seek(offset,from=SEEK_SET)
to from (start, current, end).

Returns True if the file stream supports random


seekable()
access.

tell() Returns the current file location.

Resize the file stream to size bytes. If size is not


truncate(size=None)
specified, resize to current location.

writable() Returns True if the file stream can be written to.

9
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Write string s to the file and return the number of


write(s)
characters written.

writelines(lines) Write a list of lines to the file.

Algorithm
Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for
reading the content of the file:

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

10
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Flow Chart

Start

Change Directory to
Desktop

Make directory test

Change directory to
test

Notepad Notepad f.py


Test.py

End in the values on


For line in f:
diff. lines

Print(line[0])

Python f.py f.close ()

Stop

11
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

5) DICTIONARY IN PYTHON

SORTING A PYTHON DICTIONARY BY KEY OR VALUE


In this, first we have to tell what a dictionary is in python, and secondly, we
have to sort a dictionary.

TOOLS AND CONCEPT:


Python’s dictionaries are kind of hash table type. They work like associative
arrays or hashes found in Perl and consist of key-value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on
the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({}) and values can be assigned and
accessed using square braces ([]).

ALGORITHM:
STEP 1: Input words in the strings.

STEP 2: Print the string.

STEP 3: Fetch a part of the string.

STEP 4: Print the string.

PROGRAMMING:
>>> dict [‘2’] = “This is two.”

>>> dict [‘six’] = “This is six.”

>>>dict [‘cat’] = “This is an animal.”

>>> tinydict = {‘Name’: ‘Ananya’, ‘Last name’: ‘Mishra’, ‘Code’: 3011}

>>> print (dict [‘2’])

This is two

>>> print (dict [‘six’])

12
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

This is six.

>>> print (dict [‘cat’])

This is an animal.

>>> print (tinydict)

{‘Name’: ‘Ananya’, ‘Last name’: ‘Mishra’, ‘Code’: 3011}

>>> print (tinydict.values ())

Dict_keys ([‘Name’, ‘Last name’, ‘Code’]) #sorting a dictionary by key

>>> print (tinydict.values ())

dict_values ([‘Ananya’, ‘Mishra’, ‘3011’]) #sorting a dictionary by value

>>> x = tinydict [‘Name’]

>>> print (x)

Ananya

FLOWCHART: START

Enter the values in the dictionary

Dict = {‘Name’: ‘Ananya’, ‘Last name’: ‘Mishra’, ‘Code’: 3011}

Print (dict)

X = dict [“Name”]

STOP

13
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

6) STEP 1:

 What is leap year? Enter year, check whether the given


year is leap or not.
STEP 2:
 OVERVIEW: A leap year contains one extra day to keep the year
synchronized with the astronomical or seasonal year. In this year month
of February has 29 days.
STEP 3:
 EXPLANATION: The following code can be executed by using the
assignment operator, comparision operator, arithmetic operator and if-
else operator.
STEP 4:
 CONCEPT: We take an input by declaring a variable. The modulus
operator is used to find out whether the given year is leap year or not. If
the given year is completely divisible, the modulus function returns 0.
We also use if-else, which results to true if the year is leap year
otherwise false.
STEP 5:
 TOOLS:
 Arithmetic Operator # %, modulus.
Divides left hand operand by right hand operand and returns
remainder.
 Comparision Operator # equals to
If the value of two operands are equal then the condition
becomes true.
If the value of two operands are not equal then the condition
becomes true.

STEP 6:
 PROGRAM:
14
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

>>> y = 2000
>>> if (y % 4 == 0 and y % 100! = 0 or y % 400 == 0):
… print( “leap year”)
… else
… print( “not a leap year”)

Leap
STEP 7:

 ALGORITHM:
 STEP 1: Start.
 STEP 2: Print “enter year to be checked”.
 STEP 3: Store the value entered by the user in a variable.
 STEP 4: Start an if loop with condition.
(y % 4 == 0 and y % 100! = 0 or y % 400 == 0).
 STEP 5: Print “leap year”.
 STEP 6: Else print not a leap year.
 STEP 7: Stop.

15
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

STEP 8:
 FLOWCHART:

START

TAKE A YEAR(Y)

(y % 4== 0 and no
PRINT “NOT A
y % 100! = 0 or
LEAP YEAR”
y % 400 == 0)

yes

PRINT “LEAP YEAR”

STOP

16
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Q7. Swapping of two numbers


Step 1. What is swapping? Initialize two numbers and show the
swapping of two numbers.

Step 2. Problem description: This program swaps two numbers.

Step 3. Explanation: To swap two numbers in python, you have to


ask from the user to enter value to enter value of two numbers to
swap those two numbers using the third variable . Swapping of two
number means placing the value of first variable to second variable
and the value of second variable to the first variable by using another
temporary variable.

Step 4. Tools and concept: To swap two numbers in python, first


store the value of the first number to a temporary variable say swap,
then store the value of the second variable to the first variable , and
then finally store the value of the temporary variable , swap, to the
second variable.

Step 5. Algorithm:

(a) Start

(b) Input two values from the user

(c) Create a temporary variable and swap the values

(d) Print the swapped values

Step 6. Programming:

a = 10

b = 20

c = ‘’

17
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

c=b

b=a

a=c

print(a)

20

print(b)

10

Step 7. Program explanation:

(a) The user is asked to enter value of two numbers.

(b) The values are swapped.

(c) The swapped values are displayed.

18
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 8. Flowchart:
Start

a = 10

b = 20

c = ‘’

Read a, b

c=b

b=a

a=c

print a

print b

Stop

19
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

8) Python Program
Question : To check if the given number is odd or even.
Step 1: Overview –
We can check if a given number is odd or even by using the modulus operator
and comparison operator. If a number is completely divisible by 2 and gives an
output of 0 when the modulus operator is used, then it is even otherwise odd.
Step 2: Explanation –
We declare a variable and assign a value to it. An if-else construct is used to
give the desired output , if and when the given value is even or odd, the output
will print “number is even” or “number is odd” respectively. The modulus
operator (%) will be used to check if the given number is completely divisible
by 2 and the output is 0.
Step 3: Tools, concept and mathematical function –
 Concept :
a) if-else – The if-else statement is used in python for decision
making. Here, the program evaluates the test expression and will
execute statements only if the test expression is true. If the test
expression is false the statement is not executed.
In python the body of the if statement is indicated by indention.
Body starts within indentation and the first un-indented line
marks the end. Python interprets non-zero values as true, none
and zero are interpreted as false.
b) Modulus operator (%) – Divides left hand operand by right hand
operand and returns remainder. For eg.- a = 10
b = 20
b % a = 10
 Tools : Arithematic operator : %
Comparison operator : ==
If-else construct.
Step 4: Algorithm –
Step 1: Start
Step 2: Input any number a
Step 3: Check if (a % 2 == 0)
20
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 4: If true, print “ a is an even number”


Step 5: If false, print “ a is an odd number”
Step 6: Stop
Step 5: Flowchart –

Start

Input
number (a)

Yes If a % No
2 == 0

Display “Even Display “Odd


number” number”

End
21
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 6: Program –
>>> a = 24
>>> if(a % 2 == 0):
…print( a, “is an even number”)
else:
…print(a, “is an odd number”)
Output: 24 is an even number

22
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

9) PYTHON PROGRAM TO MULTIPLY TWO NUMBERS


Step 1) This is a python program to multiply two given numbers.
Step 2) PROBLEM DESCRIPTION
The program takes two numbers and print the multiplication of two numbers.
STEP 3) PROBLEM SOLUTION
1. The program will ask the user to enter the numbers.
2. The program will ask the user to enter the numbers
3. Finally, it will print out the multiplication result.
4. Note that, we don’t need any extra modules to find out the
multiplication of two numbers. Character ‘*’ is used to find out the
multiplication of two numbers.
Step 4) Program/source code
1. #Python program to multiply two numbers using function
2.
3. def mul_Num(a,b):#function for find product
4. multiply=a*b;
5. return multiply; #return value
6.
7. num1=25 #variable declaration
8. num2=55
9. print("The product is", mul_Num(num1,num2))#call to function

step 5) PROGRAM EXPLANATION


This is a simple Python program to find the product of two integer numbers.
In the above program, we declared two different integer values such as 12 and
32 stored in variables num1, num2, respectively.
Then, we can find the product of given numbers using the * operator in Python
finally, we could display the result on the screen using the print() function in
Python language.

Step 6) RUNTIME TEST CASE


Enter the first number: 23
Enter the second number is: 32
23
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

The product of the given numbers is 736.

24
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

10) Calculate Circumference of Circle in Python


To calculate circumference of a circle in python, you have to ask from user to
enter the radius of a circle to calculate and print the circumference of that
circle as shown in the program given below.

Algorithm
1. Take the radius as an input from the user. Store the radius value in a
variable. If you want, you can also take the diameter from the user as an input
but the other formula is used widely.
2. Calculate the circumference of the circle by using the formula mentioned
above. We can use one constant to store the value of ‘Pi’, but we can also use
the ‘math‘ module. ‘math‘ module is an inbuilt module with lots of useful
constants and formulae. In this example, I will show you how to use ‘Pi‘ using
the ‘math’ module.
3. Find out the circumference and print out the result to the user.

Python Programming Code to Calculate Circumference of Circle


Following python program ask from user to enter radius of a circle to find and
print the circumference
>>> While True:
print("Enter 'x' for exit.");
rad = input("Enter radius of circle: ");
if rad == 'x':
break
else:
radius = float(rad);
circumference = 2*3.14*radius;
print("Circumference of Circle =",circumference,”/n”);

25
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Now type the radius of circle and press enter key to see the circumference
value of the circle

Enter ‘x’ for exit


Enter radius of circle: 5
Circumference of circle = 31.40000000000002

Enter ‘x’ for exit


Enter radius of circle: x
>>>

Explanation
1. First, take the radius as an input from the user. The radius is a floating value.
So, we are using ‘float(input())‘. input() method is used to read the user input
value. This value is of string type. We are wrapping this value with ‘float()‘ to
get the float type.
2. Calculate the circumference. The value of Pi is taking from the ‘math‘
module of python. ‘math.pi‘ gives the value of pi. Note that we are importing
this module at the start of the program. If you don’t import this module, it will
throw you one exception.
3. Print the value of the circumference. The value is formatted up to two
decimal places using %.2f

26
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

11) Python Program to Implement Linear Search

Step 1: Python Program to Implement Linear Search


This is a Python program to implement linear search.

Step 2: Problem Description


The program takes a list and key as input and finds the index of the key in the
list using linear search.

Step 3: Flow Chart of Solution

27
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 4: Problem Solution


1. Create a function linear_search that takes a list and key as arguemnts.
2. A loop iterates through the list and when an item matching the key is found,
the corresponding index is returned.
3. If no such item is found, -1 is returned.

Step 5: Program/Source Code


Here is the source code of a Python program to implement linear search. The
program output is shown below.

def linear_search(alist, key):


"""Return index of key in alist. Return -1 if key
not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1

alist = input('Enter the list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = linear_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key,
index))

Step 6: Program Explanation


1. The user is prompted to enter a list of numbers.
2. The user is then asked to enter a key to search for.
3. The list and key is passed to linear_search.
4. If the return value is -1, the key is not found and a message is displayed,
otherwise the index of the found item is displayed.

28
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 7: Runtime Test Cases


Case 1:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.

Case 2:
Enter the list of numbers: 5 2 1 5 -3
The number to search for: 2
2 was found at index 1.

Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.

29
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

12) BINARY SEARCH


STEP-1:
Python Program to Implement Binary Search

STEP-2:
Problem Description
The program takes a list and key as input and finds the index of the key in the
list using binary search.

STEP-3:
Problem Solution
1. Create a function binary_search that takes a list and key as arguments.
2. The variable start is set to 0 and end is set to the length of the list.
3. The variable start keeps track of the first element in the part of the list being
searched while end keeps track of the element one after the end of the part
being searched.
4. A while loop is created that iterates as long as start is less than end.
5. mid is calculated as the floor of the average of start and end.
6. If the element at index mid is less than key, start is set to mid + 1 and if it is
more than key, end is set to mid. Otherwise, mid is returned as the index of the
found element.
7. If no such item is found, -1 is returned.

STEP-4:
Flow Diagram
1 2 3 9 11 13 17 25 57 90
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

[min] [max]

30
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Suppose the data to be found is 57. The upper and lower bounds are min and max
resp.

mid= ( mid + max)/ 2 = (0 + 9)/ 2 = 4

a[mid] is a[4] which is compared with 57. As 11 is less than 57, lower bound min is
pointed to a[5].

Again mid is calculated => mid = (5 + 9)/ 2 = 7

a[mid] is a[7] which is compared with 57. As 25 is less than 57, lower bound min is
STEP-5:
pointed to a[8].

Program/Source
Again Code
mid is calculated => mid = (8 + 9)/ 2 = 8
def binary_search(alist,
a[mid] key): with 57. Hence it matches with 57.
is a[8] which is compared
"""Search key in alist[start... end - 1]."""
Search successful.
start =0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1

alist = input('Enter the sorted list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = binary_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

31
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

STEP-6:
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The user is then asked to enter a key to search for.
3. The list and key is passed to binary_search.
4. If the return value is -1, the key is not found and a message is displayed,
otherwise the index of the found item is displayed.

32
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

13) BUBBLE SORT

Step 1. Python Program to Implement Bubble Sort


This is a Python program to implement bubble sort.

Step 2. Problem Description


The program sorts a list by bubble sort.

Step 3. Problem Solution


1. Create a function bubble_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from
the length of the list – 1 to 1.
3. Create an inner loop with a loop variable that counts from 0 up to i – 1.
4. Inside the inner loop, if the elements at indexes j and j + 1 are out of
order, then swap them.
5. If in one iteration of the inner loop there were no swaps, then the list is
sorted and one can return prematurely.

Step 4. Program/Source Code


Here is the source code of a Python program to implement bubble sort. The
program output is shown below.
def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return

33
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', end='')
print(alist)

Step 5. Program Explanation


1. The user is prompted to enter a list of numbers.
2. The list is passed to the bubble_sort function.
3. The sorted list is displayed.

Step 6. Runtime Test Cases


Enter the list of numbers: 4 2 38 10 5
Sorted list: [2, 4, 5, 10, 38]

34
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

14) Python Program to Implement Insertion Sort

This is a Python program to implement insertion sort.

Problem Description
The program sorts a list by insertion sort.

Problem Solution
1. Create a function insertion_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from 1 to
the length of the list – 1.
3. Set temp equal to the element at index i.
4. Set j equal to i – 1.
5. Create a while loop that runs as long as j is non-negative and temp is smaller
than the element at index j.
6. Inside the while loop, set the element at index j + 1 equal to the element at
index j and decrement j.
7. After the while loop finishes, set the element at index j + 1 equal to temp.
Program/Source Code
Here is the source code of a Python program to implement insertion sort. The
program output is shown below.
definsertion_sort(alist):
foriin range(1, len(alist)):
temp = alist[i]
j=i-1
while (j >= 0 and temp <alist[j]):
alist[j + 1] = alist[j]
j=j-1
alist[j + 1] = temp

35
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x inalist]
insertion_sort(alist)
print('Sorted list: ', end='')
print(alist)

Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to the insertion_sort function.
3. The sorted list is displayed.

Runtime Test Cases

Case 1:
Enter the list of numbers: 5 1 6 2 4 3
Sorted list: [1,2,3,4,5,6]

Case 2:
Enter the list of numbers: 5 4 3 2 0 -
1
Sorted list: [-1, 0, 2, 3, 4, 5]

Case 3:
Enter the list of numbers: 3 4 1 4 5 0
7
Sorted list: [0, 1, 3, 4, 4, 5, 7]

36
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Flowchart

37
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

15) SELECTION SORT

1. Python Program to Implement Selection Sort


This is a Python program to implement selection sort.

2. Problem Description
The program sorts a list by selection sort.

3. Problem Solution
 Create a function selection sort that takes a list as argument.
 Inside the function create a loop with a loop variable i that counts from 0
to the length of the list – 1.
 Create a variable smallest with initial value i.
 Create an inner loop with a loop variable j that counts from i + 1 up to
the length of the list – 1.
 Inside the inner loop, if the elements at index j is smaller than the
element at index smallest, then set smallest equal to j.
 After the inner loop finishes, swap the elements at indexes i and
smallest.

4. Program/Source Code
Here is the source code of a Python program to implement selection sort.

def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
38
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

5. Program Explanation
 The user is prompted to enter a list of numbers.
 The list is passed to the selection_sort function.
 The sorted list is displayed.

6. Runtime Test Cases


 Case 1:
Enter the list of numbers: 3 1 4 5 2 6
Sorted list: [1, 2, 3, 4, 5, 6]

 Case 2:
Enter the list of numbers: 2 10 5 38 1 7
Sorted list: [1, 2, 5, 7, 10, 38]

 Case 3:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]

39
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

FLOW CHART

40
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

EXAMPLE

STEP 1 STEP 2

STEP 3 STEP 4

41
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

ALGORITHM

 Step 1 − Set MIN to location 0


 Step 2 − Search the minimum element in the list
 Step 3 − Swap with value at location MIN
 Step 4 − Increment MIN to point to next element
 Step 5 − Repeat until list is sorted

42
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

16) MERGE SORT

 Python Program to Implement Merge Sort


• This is a Python program to implement merge sort.

 Problem Description

• The program sorts a list by merge sort.

 Problem Solution

• 1. Create a function merge_sort that takes a list and two variables start
and end as arguments.
2. The function merge_sort will sort the list from indexes start to end – 1
inclusive.
3. If end – start is not greater than 1, then return.
4. Otherwise, set mid equal to the floor of (start + end)/2.
5. Call merge_sort with the same list and with start = start and end = mid
as arguments.
6. Call merge_sort with the same list and with start = mid and end = end
as arguments.
7. Call the function merge_list, passing the list and the variables start,
mid and end as arguments.
8. The function merge_list takes a list and three numbers, start, mid and
end as arguments and assuming the list is sorted from indexes start to
mid – 1 and from mid to end – 1, merges them to create a new sorted
list from indexes start to end – 1.

 Program/Source Code

• Here is the source code of a Python program to implement merge sort.


The program output is shown below.

• def merge_sort(alist, start, end): '''Sorts the list from indexes start to end
- 1 inclusive.''' if end - start > 1: mid = (start + end)//2 merge_sort(alist,
start, mid) merge_sort(alist, mid, end) merge_list(alist, start, mid,

43
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

end) def merge_list(alist, start, mid, end): left = alist[start:mid] right =


alist[mid:end] k = start i = 0 j = 0 while (start + i < mid and mid + j < end):
if (left[i] <= right[j]): alist[k] = left[i] i = i + 1 else: alist[k] = right[j] j = j + 1
k = k + 1 if start + i < mid: while k < end: alist[k] = left[i] i = i + 1 k = k + 1
else: while k < end: alist[k] = right[j] j = j + 1 k = k + 1 alist =
input('Enter the list of numbers: ').split() alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist)) print('Sorted list: ', end='') print(alist)

 Program Explanation

• 1. The user is prompted to enter a list of numbers.


2. The list is passed to the merge_sort function.
3. The sorted list is displayed.

 Runtime Test Cases

• Case 1: Enter the list of numbers: 3 1 5 8 2 5 1 3 Sorted list: [1, 1, 2, 3, 3, 5,


5, 8]

Case 2: Enter the list of numbers: 5 3 2 1 0 Sorted list: [0, 1, 2, 3, 5]

44
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

17) Python Program to Implement Heap sort

This is a Python program to implement heap sort.

Problem Description
The program sorts a list by heap sort.

Problem Solution
1. Create a function heap sort that takes a list as argument.
2. Call build_max_heap with the list as argument to rearrange the list into a list
representation of a heap.
3. Swap the first element with the last element in the heap.
4. Consider the new heap to have size one less than its previous size and call
max_heapify with index = 0 to make this new heap satisfy the heap property.
5. Repeat steps 3 and 4 until the size of the heap reduces to zero and the
entire list is sorted.
6. Define the function parent that takes an index as argument and returns the
index of the parent.
7. Define the function left that takes an index as argument and returns the
index of its left child.
8. Define the function right that takes an index as argument and returns the
index of its right child.
9. Define the function build_max_heap that takes a list as argument and
rearranges it to form a max heap.
10. The build_max_heap function works by calling max_heapify on each parent
node starting from the last parent node and working towards the root.
11. Define the function max_heapify that takes an index as argument and
modifies the heap structure at and below the node at this index to make it
satisfy the heap property.

Program/Source Code
Here is the source code of a Python program to implement heapsort. The
program output is shown below.

def heapsort(alist):
build_max_heap(alist)
for i in range(len(alist) - 1, 0, -1):
alist[0], alist[i] = alist[i], alist[0]

45
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

max_heapify(alist, index=0, size=i)

def parent(i):
return (i - 1)//2

def left(i):
return 2*i + 1

def right(i):
return 2*i + 2

def build_max_heap(alist):
length = len(alist)
start = parent(length - 1)
while start >= 0:
max_heapify(alist, index=start, size=length)
start = start - 1

def max_heapify(alist, index, size):


l = left(index)
r = right(index)
if (l < size and alist[l] > alist[index]):
largest = l
else:
largest = index
if (r < size and alist[r] > alist[largest]):
largest = r
if (largest != index):
alist[largest], alist[index] = alist[index], alist[largest]
max_heapify(alist, largest, size)

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
heapsort(alist)
print('Sorted list: ', end='')
print(alist)

Program Explanation
46
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

1. The user is prompted to enter a list of numbers.


2. The list is passed to the heapsort function.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 3 2 2 1 0 -2 5 7
Sorted list: [-2, 0, 1, 2, 2, 3, 5, 7]

Case 2:
Enter the list of numbers: 5 4 3 2 1
Sorted list: [1, 2, 3, 4, 5]

Case 3:
Enter the list of numbers: 1
Sorted list: [1]

Algorithm:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it
with the last item of the heap followed by reducing the size of heap by 1.
Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.

Flowchart:

47
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

18) STACK
STEP 1:
This is a Python program to implement a stack.

STEP 2: Problem Description


The program creates a stack and allows the user to perform push and pop
operations on it.

STEP 3: Problem Solution


1. Create a class Stack with instance variable items initialized to an empty list.

2. Define methods push, pop and is_empty inside the class Stack.

3. The method push appends data to items.

4. The method pop pops the first element in items.

5. The method is_empty returns True only if items is empty.

6. Create an instance of Stack and present a menu to the user to perform


operations on the stack.

STEP 4: Program/Source Code


class Stack:

def __init__(self):

self.items = []

def is_empty(self):

return self.items == []

48
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

def push(self, data):

self.items.append(data)

def pop(self):

return self.items.pop()

s = Stack()

while True:

print('push <value>')

print('pop')

print('quit')

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'push':

s.push(int(do[1]))

elif operation == 'pop':

if s.is_empty():

print('Stack is empty.')

else:

print('Popped value: ', s.pop())

49
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

elif operation == 'quit':

break

STEP 5: Flow Diagram

50
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

STEP 6: Program Explanation


1. An instance of Stack is created.

2. The user is presented with a menu to perform push and pop operations on
the stack.

3. The chosen operation is performed by calling the corresponding method of


the stack.

STEP 7: Runtime Test Cases


push <value>

pop

quit

What would you like to do? push 3

push <value>

pop

quit

What would you like to do? push 5

push <value>

pop

quit

What would you like to do? pop

Popped value: 5

push <value>

pop

quit
51
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

What would you like to do? pop

Popped value: 3

push <value>

pop

quit

What would you like to do? pop

Stack is empty.

push <value>

pop

quit

What would you like to do? quit

STEP 8: FLOWCHART

52
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

19) Python Program to Implement Queue


This is a Python program to implement a queue.
Problem Description
The program creates a queue and allows the user to perform enqueue and
dequeue operations on it.
Problem Solution
1. Create a class Queue with instance variable items initialized to an empty list.
2. Define methods enqueue, dequeue and is empty inside the class Queue.
3. The method enqueue appends data to items.
4. The method dequeue dequeues the first element in items.
5. The method is empty returns True only if items are empty.
6. Create an instance of Queue and present a menu to the user to perform
operations on the queue.
Program/Source Code
Here is the source code of a Python program to implement a queue. The
program output is shown below.
class Queue:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def enqueue(self, data):


self.items.append(data)

def dequeue(self):
return self.items.pop(0)

q = Queue()
while True:
print('enqueue <value>')
print('dequeue')

53
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

print('quit')
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'quit':
break

Program Explanation

54
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

1. An instance of Queue is created.


2. The user is presented with a menu to perform enqueue and dequeue operations on
the queue.
3. The chosen operation is performed by calling the corresponding method of the queue.

Runtime Test Cases


Case 1:
enqueue <value>
dequeue
quit
What would you like to do? enqueue 3
enqueue <value>
dequeue
quit
What would you like to do? enqueue 1
enqueue <value>
dequeue
quit
What would you like to do? enqueue 0
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 3
enqueue <value>
dequeue
quit
What would you like to do? Dequeue

55
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Dequeued value: 1
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 0
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? quit

Case 2:
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? enqueue 7
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 7
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Queue is empty.
enqueue <value>
dequeue
quit
What would you like to do? Quit

56
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

20) GRAPH

A graph is a pictorial representation of a set of objects where


some pairs of objects are connected by links. The
interconnected objects are represented by points termed as
vertices, and the links that connect the vertices are called the
edges. Following are the basic operations we perform on
graphs:
 Display graph vertices
 Display graph edges
 Add a vertex
 Add an edge
 Create a graph

Q. PYTHON PROGRAM TO FIND MINIMUM


SPANNING TREE USING KRUSAL’S
ALGORITHM
This is a python program to find a minimum spanning tree of
an undirected weighted graph using Krusal’s algorithm.

PROBLEM DESCRIPTION:
A spanning tree of a graph can be defined as a graph with
minimal set of objects that connect all vertices. A minimum
spanning tree of a graph is a graph with least weight( where
weight is computed by adding all the edges in the spanning
tree ). In general, a graph can have multiple minimum

57
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

spanning trees. The problem is to find a minimum spanning


tree of a graph.
PROBLEM SOLUTION:
1. Create classes for Graph and Vertex.
2. Create a function mst_krusal that takes a Graph object
g as argument.
3. The function will return a Graph object which is a
minimum spanning tree of the graph g.
4. An empty graph called mst is created which will hold
a MST of the graph g.
5. The algorithm works by first sorting all the edges of g
in ascending order by weight.
6. Then the smallest edge is taken from the sorted list.
7. If that edge does not form a cycle when added to mst,
it is added.
8. Then the next smallest edge is taken and step 7 is
performed again.
9. The above is performed until mst has the same number
of vertices as g.
10. To determine whether adding an edge will form a
cycle, each vertex in g is assigned a component.
11. When any vertex is added to the MST, its component
is updated.
12. If both vertices of an edge belong to the same
component, then adding the edge will form a cycle.

PROGRAM/ SOURCE CODE:


class Graph:
58
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

def __init__(self):
# dictionary containing keys that map to the corresponding
vertex object
self.vertices = {}

def add_vertex(self, key):


"""Add a vertex with the given key to the graph."""
vertex = Vertex(key)
self.vertices[key] = vertex

def get_vertex(self, key):


"""Return vertex object with the corresponding key."""
return self.vertices[key]

def __contains__(self, key):


return key in self.vertices

def add_edge(self, src_key, dest_key, weight=1):


"""Add edge from src_key to dest_key with given
weight."""

self.vertices[src_key].add_neighbour(self.vertices[dest_key],
weight)

def does_vertex_exist(self, key):


return key in self.vertices
def does_edge_exist(self, src_key, dest_key):
"""Return True if there is an edge from src_key to dest_key."""
return self.vertices[src_key].does_it_point_to(self.vertices[dest_key])

59
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

def display(self):
print('Vertices: ', end='')
for v in self:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in self:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))

def __len__(self):
return len(self.vertices)

def __iter__(self):
return iter(self.vertices.values())class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

60
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key

def add_neighbour(self, dest, weight):


"""Make this vertex point to dest with given edge weight."""
self.points_to[dest] = weight

def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()

def get_weight(self, dest):


"""Get weight of edge from this vertex to dest."""
return self.points_to[dest]

def does_it_point_to(self, dest):


"""Return True if this vertex points to dest."""
return dest in self.points_to
def mst_krusal(g):
"""Return a minimum cost spanning tree of the connected graph
g."""

61
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

mst = Graph()
if len(g) == 1:
u = next(iter(g)) # get the single vertex
mst.add_vertex(u.get_key()) # add a copy of it to mst
return mst

edges = []
for v in g:
for n in v.get_neighbours():
if v.get_key() < n.get_key():
edges.append((v, n))

edges.sort(key=lambda edge: edge[0].get_weight(edge[1]))


component = {}
for i, v in enumerate(g):
component[v] = i
edge_index = 0
while len(mst) < len(g):
u, v = edges[edge_index]
edge_index += 1

62
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

if component[u] != component[v]:

if not mst.does_vertex_exist(u.get_key()):
mst.add_vertex(u.get_key())
if not mst.does_vertex_exist(v.get_key()):
mst.add_vertex(v.get_key())
mst.add_edge(u.get_key(), v.get_key(), u.get_weight(v))
mst.add_edge(v.get_key(), u.get_key(), u.get_weight(v))

for w in g:
if component[w] == component[v]:
component[w] = component[u]

return mst
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('mst')
print('display')
print('quit')

63
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

while True:
do = input('What would you like to do? ').split()

operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:

64
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

if not g.does_edge_exist(src, dest):


g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:
print('Edge already exists.')

elif operation == 'mst':


mst = mst_krusal(g)
print('Minimum Spanning Tree:')
mst.display()
print()

elif operation == 'display':


g.display()
print()

elif operation == 'quit':


break
PROGRAM EXPLANATION:
1. An instance of Graph is created.
2. A menu is presented to the user to perform various operations on
the graph.

65
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

3. mst_krusal is called to get a minimum spanning tree of the graph.


4. This is then displayed.

RUN TIME TEST CASES:


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
mst
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add vertex 6
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 5 30
What would you like to do? add edge 1 4 40

66
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

What would you like to do? add edge 2 5 20


What would you like to do? add edge 4 5 40
What would you like to do? add edge 5 3 40
What would you like to do? add edge 5 6 70
What would you like to do? add edge 3 6 50
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3 4 5 6
Edges:
(src=1, dest=4, weight=40)
(src=1, dest=2, weight=10)
(src=2, dest=5, weight=20)
(src=2, dest=1, weight=10)
(src=3, dest=5, weight=40)
(src=3, dest=6, weight=50)
(src=4, dest=1, weight=40)
(src=5, dest=2, weight=20)
(src=5, dest=3, weight=40)
(src=6, dest=3, weight=50)

67
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

What would you like to do? quit

68
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

21) Python Program to Construct a Binary Search


Tree and perform deletion and in order traversal
Step-1. This is a Python program to construct a binary search tree and
perform deletion and inorder traversal.
Step-2. Problem Description
The program creates a binary search tree and presents a menu to the user to
perform insertion, deletion and inorder traversal operations.
Step3. Problem Solution
1. Create a class BSTNode with instance variables key, left, right and
parent.
2. Define methods insert, inorder, replace_node_of_parent, find_min,
remove and search in BSTNode.
3. The method insert takes a node as argument and inserts that node in
the BST with the BSTNode object as root.
4. The method inorder displays the inorder traversal of the BST with the
BSTNode object as root.
5. The method replace_node_of_parent takes a node as argument and
replaces the current object in the BST with the node.
6. The method find_min finds the the left-most node in the BST with the
BSTNode object as root.
7. The method remove removes the current BSTNode object from the
BST.
8. The method search takes a key as argument and returns the node
with that key in the BST with the BSTNode object as root.
9. Create a class BSTree with instance variable root.
10. Define methods inorder, add, remove and search in BSTree.
11. The method inorder calls the inorder method of the root node.
12. The method add takes a key as argument and adds a node with that
key by calling the insert method of the root node.
13. The method search takes a key as argument and returns the node
with that key by calling the search method of the root node.
14. The method remove takes a key as argument and removes the node
with that key. If the node is the root node then the instance variable
root is set to None otherwise the remove method of the node is called.

69
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step-4. Program/Source Code


Here is the source code of a Python program to implement a binary search tree
and perform deletion and inorder traversal operations. The program output is
shown below.
class BSTNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None

def insert(self, node):


if self.key > node.key:
if self.left is None:
self.left = node
node.parent = self
else:
self.left.insert(node)
elif self.key < node.key:
if self.right is None:
self.right = node
node.parent = self
else:
self.right.insert(node)

def inorder(self):
if self.left is not None:
self.left.inorder()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder()

def replace_node_of_parent(self, new_node):


if self.parent is not None:
if new_node is not None:
new_node.parent = self.parent
if self.parent.left == self:

70
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

self.parent.left = new_node
elif self.parent.right == self:
self.parent.right = new_node
else:
self.key = new_node.key
self.left = new_node.left
self.right = new_node.right
if new_node.left is not None:
new_node.left.parent = self
if new_node.right is not None:
new_node.right.parent = self

def find_min(self):
current = self
while current.left is not None:
current = current.left
return current

def remove(self):
if (self.left is not None and self.right is not None):
successor = self.right.find_min()
self.key = successor.key
successor.remove()
elif self.left is not None:
self.replace_node_of_parent(self.left)
elif self.right is not None:
self.replace_node_of_parent(self.right)
else:
self.replace_node_of_parent(None)

def search(self, key):


if self.key > key:
if self.left is not None:
return self.left.search(key)
else:
return None
elif self.key < key:
if self.right is not None:
return self.right.search(key)
else:

71
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

return None
return self

class BSTree:
def __init__(self):
self.root = None

def inorder(self):
if self.root is not None:
self.root.inorder()

def add(self, key):


new_node = BSTNode(key)
if self.root is None:
self.root = new_node
else:
self.root.insert(new_node)

def remove(self, key):


to_remove = self.search(key)
if (self.root == to_remove
and self.root.left is None and self.root.right is None):
self.root = None
else:
to_remove.remove()

def search(self, key):


if self.root is not None:
return self.root.search(key)

bstree = BSTree()

print('Menu (this assumes no duplicate keys)')


print('add <key>')
print('remove <key>')
print('inorder')
print('quit')

72
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

while True:
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'add':
key = int(do[1])
bstree.add(key)
elif operation == 'remove':
key = int(do[1])
bstree.remove(key)
elif operation == 'inorder':
print('Inorder traversal: ', end='')
bstree.inorder()
print()
elif operation == 'quit':
break
Step-5. Program Explanation
1. An instance of BSTree is created.
2. The user is presented with a menu to perform insertion, deletion and
inorder traversal on the tree.
3. The corresponding methods are called to perform each operation.
Step-6. Runtime Test Cases
Menu (this assumes no duplicate keys)
add <key>
remove <key>
inorder
quit
What would you like to do? add 5
What would you like to do? add 1
What would you like to do? add 10
What would you like to do? add 7
What would you like to do? add 3
What would you like to do? inorder
Inorder traversal: 1 3 5 7 10
What would you like to do? remove 3
What would you like to do? remove 7
What would you like to do? inorder
Inorder traversal: 1 5 10
73
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

What would you like to do? remove 5


What would you like to do? Inorder
Inorder traversal: 1 10
What would you like to do? quit
Step-7.FLOW CHART

74
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

75
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

22) Python program to implement Quick Sort

Step1=This is a python program to implement Quick Sort.

Step2=Problem description

The program sorts a list by quick sort.

Step3=Problem Solution

1. Create a function quick sort that takes a list and two variables start and end
as arguments.
2. If end – start is not greater than 1, return.
3. Find the index of the pivot, p by calling the function partition with the list
and variables start and end as arguments.
4. Call quick sort with the list and the variables start and p as arguments to sort
the list from start to p – 1.
5. Call quick sort with the list, the expression p + 1 and end as arguments to
sort the list from p + 1 to end – 1.
6. Define the function partition that takes a list and two variables start and end
as arguments.
7. The function partition uses Hoare’s partition scheme to partition the list.

Step4=Algorithm
Step 1 − Choose the highest index value has pivot

Step 2 − Take two variables to point left and right of the list excluding pivot

Step 3 − left points to the low index

Step 4 − right points to the high

Step 5 − while value at left is less than pivot move right

Step 6 − while value at right is greater than pivot move left


76
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step 7 − if both step 5 and step 6 does not match swap left and right

Step 8 − if left ≥ right, the point where they met is new pivot

STEP=5: FLOWCHART

77
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Step6=diagram

Pivot=4

Pivot=
4

Pivot=3

Pivot=
1
Pivot=
5
Pivot=
9
sorted

Step7=Program

Here is the program of a Python program to implement quick sort.

def quicksort(alist, start, end):

if end - start > 1:

p = partition(alist, start, end)

quicksort(alist, start, p)

quicksort(alist, p + 1, end)

def partition(alist, start, end):

pivot = alist[start]
78
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

i = start + 1

j = end - 1

while True:

while (i <= j and alist[i] <= pivot):

i=i+1

while (i <= j and alist[j] >= pivot):

j=j-1

if i <= j:

alist[i], alist[j] = alist[j], alist[i]

else:

alist[start], alist[j] = alist[j], alist[start]

return j

alist = input('Enter the list of numbers: ').split()

alist = [int(x) for x in alist]

quicksort(alist, 0, len(alist))

print('Sorted list: ', end='')

print(alist)

Step8=Program Explanation
79
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

1. The user is prompted to enter a list of numbers.


2. The list is passed to the quicksort function.
3. The sorted list is displayed.

Step9=Runtime Test Cases

Case1:-

Enter the list of numbers: 9 -3 5 2 6 8 -6 1 3

Sorted list: [-6,-3,1,2,3,5,6,8,9]

Case2:-

Enter the list of numbers: 2 1 9 5 3 8 4

Sorted list: [1,2,3,4,5,8,9]

80
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

23) Python program to arrange words alphabetically .


Problem description: The program takes in a string (of words, in this case
i.e. a sentence) from the user and arranges it in alphabetical order by sorting
method.
Problem solution:
1. Create a function alphabetical sort that takes a list of words/ a sentence
as an argument.
2. In this program, we store the string to be sorted in my_str.
3. Using the split() method the string is converted into a list of words.
4. The split() method splits the string at whitespaces.
5. The list of words is then sorted using the sort() method and all the words
are displayed.
6. Preference is given to the words according to the ASCII CHART.

81
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Program:
# Program to sort alphabetically the words form a string provided by the user

# take input from the user


my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

#sort the list


words.sort()

#display the sorted words


For the word in words:
82
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

print(word)

Program explanation:
1. The user is prompted to enter a list of words.
2. The list is pushed to the word sort function.
3. The sorted list id displayed.

Runtime test case:


Enter a string: my name is kookie
Sorted list: is
kookie
my
name

83
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

24) Python Program to Find the Binary Equivalent of a


Number Recursively
This is a Python Program to find the binary equivalent of a number recursively.

Problem Description
The program takes a number and finds the binary equivalent of a number
recursively.

Problem Solution
1. Define a recursive function which takes a number as the argument.

2. Take a number from the user and pass it as an argument to a recursive


function.

3. In the function, put the base condition that if the number is zero, return the
formed list.

4. Otherwise, convert each digit into binary and append it to the list.

5. Reverse the list and using a for loop print the elements of the list.

6. Exit.

Program/Source Code
Here is source code of the Python Program to find the binary equivalent of a
number recursively. The program output is also shown below.

l=[]

def convert(b):

if(b==0):
84
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

return l

dig=b%2

l.append(dig)

convert(b//2)

a=int(input("Enter a number: "))

convert(a)

l.reverse()

print("Binary equivalent:")

for i in l:

print i,

Program Explanation
1. A recursive function is defined which takes a number as the argument.

2. A number is taken from the user and passed as an argument to a recursive


function.

3. In the function, the base condition is that if the number is zero, the formed
list is returned.

4. Otherwise, each digit is converted into binary and appended to the list.

5. The list is reversed and a for loop is used to print the elements of the list.

Runtime Test Cases

Case 1:

Enter a number: 17

85
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

Binary equivalent:

10001

Algorithm

Flowchart

86
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

25) Python Program to Find the Fibonacci Series without Using


Recursion.
This is a Python Program to find the fibonacci series without using recursion.
• Problem Description
The program takes the first two numbers of the series along with the number
of terms needed and prints the fibonacci series.
• Problem Solution
1. Take the first two numbers of the series and the number of terms to
be printed from the user.
2. Print the first two numbers.
3. Use a while loop to find the sum of the first two numbers and then
proceed the fibonacci series.
4. Print the fibonacci series till n-2 is greater than 0.
5. Exit.
• Program/Source Code
Here is source code of the Python Program to find the fibonacci series without
using recursion. The program output is also shown below.
a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b,end=" ")
while(n-2):
c=a+b
a=b
b=c
print(c,end=" ")
n=n-1
• Program Explanation
1. User must enter the first two numbers of the series and the number of terms
to be printed.
2. The first two terms are printed outside the while loop.
3. A while loop is used to find the sum of the first two terms and proceed the
series by interchanging the variables.

87
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

4. The value of n is decremented.


5. The fibonacci series is printed till n-2 is greater than 0.
• Runtime Test Cases

Case 1:
Enter the first number of the series 0
Enter the second number of the series 1
Enter the number of terms needed 4
0112
Case 2:
Enter the first number of the series 2
Enter the second number of the series 4
Enter the number of terms needed 5
2 4 6 10 16

88
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

26) LCM OF TWO NUMBERS

Step1) Python Program to Find the LCM of Two Numbers


This is a Python Program to find the LCM of two numbers.
Step2) Problem Description
The program takes two numbers and prints the LCM of two numbers.
Step3) Problem Solution
1.Take in both the integers and store it in separate variables.
2.Find which of the integer among the two is smaller and store it in a
separate variable.
3.Use a while loop whose condition is always True until break is used.
4.Use an if statement to check if both the numbers are divisible by the
minimum number and increment otherwise.
5.Print the final LCM.
6. Exit.

Step 4) flow of solution


A common multiple is a number that is a multiple of two or more
numbers. The common multiples of 3 and 4 are 0, 12, 24, ….

The least common multiple (LCM) of two numbers is the smallest number (not
zero) that is a multiple of both.

89
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

The least common multiple (L.C.M.) of two numbers is the smallest positive
integer that is perfectly divisible by the two given numbers.

Step 5) Program/Source Code


Here is source code of the Python Program to find the LCM of two
numbers. The program output is also shown below.
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
if(a>b):
min1=a
else:
min1=b
while(1):
if(min1%a==0 and min1%b==0):
print("LCM is:",min1)
break
min1=min1+1

Step6) Program Explanation


1.User must enter both the numbers and store it in separate variables.
2. An if statement is used to find out which of the numbers is smaller
and store in minimum variable.
3.Then a while loop is used whose condition is always true (or 1)
unless break is used.
4.Then an if statement within the loop is used to check whether the
value in the minimum variable is divisible by both the numbers.
5.If it is divisible, break statement breaks out of the loop.
6.If it is not divisible, the value in the minimum variable is
incremented.
7. The final LCM is printed.
Step7) Runtime Test Cases
Case 1:
Enter the first number:5
Enter the second number:3

90
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019

LCM is: 15

Case 2:
Enter the first number:15
Enter the second number:20
LCM is: 60

91

Você também pode gostar