Académique Documents
Professionnel Documents
Culture Documents
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.
1
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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
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.
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.
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.
5
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
b)index() Returns the index of the first element with the specified value.
Algorithm
step 1 :make a list using variable or constants only.
step 3 :prints the list after applying the function. ie the new list.
Program
1. sort ()
>>> v.sort()
2. index ()
6
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
3.reverse ()
>>> l = [ 1 , 2 , 3 , 4 ]
>>> l.reverse()
reverse list : [ 4 , 3 , 2 , 1 ]
4.append ()
>>> n = [ 1 , 2 , 3 , 4 ]
adding number : [ 1 , 2 , 3 , 4 , 5 ]
Flowchart
START
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
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.
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
Here is the complete list of methods in text mode with a brief description.
Method Description
9
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Algorithm
Assume we have the following file, located in the same folder as Python:
demofile.txt
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
Change directory to
test
Print(line[0])
Stop
11
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
5) DICTIONARY IN PYTHON
Dictionaries are enclosed by curly braces ({}) and values can be assigned and
accessed using square braces ([]).
ALGORITHM:
STEP 1: Input words in the strings.
PROGRAMMING:
>>> dict [‘2’] = “This is two.”
This is two
12
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
This is six.
This is an animal.
Ananya
FLOWCHART: START
Print (dict)
X = dict [“Name”]
STOP
13
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
6) STEP 1:
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
STOP
16
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Step 5. Algorithm:
(a) Start
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
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
Start
Input
number (a)
Yes If a % No
2 == 0
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
24
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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.
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
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
27
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
28
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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
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.
a[mid] is a[4] which is compared with 57. As 11 is less than 57, lower bound min is
pointed to a[5].
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
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
33
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
34
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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
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.
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
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
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.
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
42
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Problem Description
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
• 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
Program Explanation
44
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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
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
Program Explanation
46
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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.
2. Define methods push, pop and is_empty inside the class Stack.
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
48
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
self.items.append(data)
def pop(self):
return self.items.pop()
s = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
if s.is_empty():
print('Stack is empty.')
else:
49
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
break
50
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
2. The user is presented with a menu to perform push and pop operations on
the stack.
pop
quit
push <value>
pop
quit
push <value>
pop
quit
Popped value: 5
push <value>
pop
quit
51
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Popped value: 3
push <value>
pop
quit
Stack is empty.
push <value>
pop
quit
STEP 8: FLOWCHART
52
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
def is_empty(self):
return self.items == []
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
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
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
def __init__(self):
# dictionary containing keys that map to the corresponding
vertex object
self.vertices = {}
self.vertices[src_key].add_neighbour(self.vertices[dest_key],
weight)
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 get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
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))
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
65
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
66
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
67
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
68
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
69
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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()
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)
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()
bstree = BSTree()
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
74
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
75
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Step2=Problem description
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 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
quicksort(alist, start, p)
quicksort(alist, p + 1, end)
pivot = alist[start]
78
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
i = start + 1
j = end - 1
while True:
i=i+1
j=j-1
if i <= j:
else:
return j
quicksort(alist, 0, len(alist))
print(alist)
Step8=Program Explanation
79
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Case1:-
Case2:-
80
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
81
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
Program:
# Program to sort alphabetically the words form a string provided by the user
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.
83
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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.
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)
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.
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.
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
87
ALGORITHM DESIGN AND DATA STRUCTURE- DOCUMENT 2019
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
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.
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