Python Programs

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 537

Python Program to Calculate the Average of Numbers in a

Given List
This is a Python Program to Calculate the Average of Numbers in a Given List.

Problem Description
The program takes the elements of the list one by one and displays the average of the
elements of the list.

Problem Solution
1. Take the number of elements to be stored in the list as input.
2. Use a for loop to input elements into the list.
3. Calculate the total sum of elements in the list.
4. Divide the sum by total number of elements in the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to Calculate the Average of Numbers in a Given
List. The program output is also shown below.

n=int(input("Enter the number of elements to be inserted: "))


a=[]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2))
Program Explanation
1. User must first enter the number of elements which is stored in the variable n.
2. The value of I ranges from 0 to the number of elements and is incremented each time
after the body of the loop is executed.
3. Then, the element that the user enters is stored in the variable elem.
4. a.append(elem) appends the element to the list.
5. Now the value of i is incremented to 2.
6. The new value entered by the user for the next loop iteration is now stored in elem which
is appended to the list.
7. The loop runs till the value of i reaches n.
8. sum(a) gives the total sum of all the elements in the list and dividing it by the total number
of elements gives the average of elements in the list.
9. round(avg,2) rounds the average upto 2 decimal places.
10. Then the average is printed after rounding.

Runtime Test Cases


Case 1:
Enter the number of elements to be inserted: 3
Enter element: 23
Enter element: 45
Enter element: 56
Average of elements in the list 41.33

Case 2:
Enter the number of elements to be inserted: 5
Enter element: 12
Enter element: 24
Enter element: 33
Enter element: 25
Enter element: 18
Average of elements in the list 22.4

Python Program to Exchange the Values of Two Numbers


Without Using a Temporary Variable
This is a Python Program to exchange the values of two numbers without using a temporary
variable.

Problem Description
The program takes both the values from the user and swaps them without using temporary
variable.

Problem Solution
1. Take the values of both the elements from the user.
2. Store the values in separate variables.
3. Add both the variables and store it in the first variable.
4. Subtract the second variable from the first and store it in the second variable.
5. Then, subtract the first variable from the second variable and store it in the first variable.
6. Print the swapped values.
7. Exit.

Program/Source Code
Here is source code of the Python Program to exchange the values of two numbers without
using a temporary variable. The program output is also shown below.
a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
a=a+b
b=a-b
a=a-b
print("a is:",a," b is:",b)
Program Explanation
1. User must first enter the values for both the elements.
2. The first element is assigned the sum of the first two elements.
3. Second element is assigned the difference between the sum in the first variable and the
second variable, which is basically the first element.
4. Later the first element is assigned the difference between the sum in the variable and the
second variable, which is the second element.
5. Then the swapped values are printed.

Runtime Test Cases


Case 1
Enter value of first variable: 3
Enter value of second variable: 5
a is: 5 b is: 3

Case 2
Enter value of first variable: 56
Enter value of second variable: 25
a is: 25 b is: 56

Python Program to Read a Mumber n and Compute n+nn+nnn


This is a Python Program to read a number n and compute n+nn+nnn.

Problem Description
The program takes a number n and computes n+nn+nnn.

Problem Solution
1. Take the value of a element and store in a variable n.
2. Convert the integer into string and store it in another variable.
3. Add the string twice so the string gets concatenated and store it in another variable.
4. Then add the string thrice and assign the value to the third variable.
5. Convert the strings in the second and third variables into integers.
6. Add the values in all the integers.
7. Print the total value of the expression.
8. Exit.

Program/Source Code
Here is the source code of the Python Program to read a number n and compute n+nn+nnn.
The program output is also shown below.

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


temp=str(n)
t1=temp+temp
t2=temp+temp+temp
comp=n+int(t1)+int(t2)
print("The value is:",comp)
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The integer is converted to string for concatenation of the value of n.
3. The string is then concatenated once and twice and stored in separate variables.
4. Later to find the total sum, the string is converted back to integer.
5. The total value of the expression is then printed.

Runtime Test Cases


Case 1:
Enter a number n: 5
The value is: 615

Case 2:
Enter a number n: 20
The value is: 204060

Python Program to Reverse a Given Number


This is a Python Program to reverse a given number.

Problem Description
The program takes a number and reverses it.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Using a while loop, get each digit of the number and store the reversed number in
another variable.
3. Print the reverse of the number.
4. Exit.

Program/Source Code
Here is the source code of the Python Program to reverse a given number.

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


rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The while loop is used and the last digit of the number is obtained by using the modulus
operator.
3. The last digit is then stored at the one’s place, second last at the ten’s place and so on.
4. The last digit is then removed by truly dividing the number with 10.
5. This loop terminates when the value of the number is 0.
6. The reverse of the number is then printed.

Runtime Test Cases


Case 1:
Enter number: 124
Reverse of the number: 421

Case 2:
Enter number: 4538
Reverse of the number: 8354

Python Program to Check Whether a Number is Positive or


Negative
This is a Python Program to check whether a number is positive or negative.

Problem Description
The program takes a number and checks whether it is positive or negative.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Use an if statement to determine whether the number is positive or negative.
3. Exit.

Program/Source Code
Here is the source code of the Python Program to check whether a number is positive or
negative. The program output is also shown below.

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


if(n>0):
print("Number is positive")
else:
print("Number is negative")
Program Explanation
1. User must first enter the value and store it in a variable.
2. Use an if statement to make a decision.
3. If the value of the number is greater than 0, “Number is positive” is printed.
4. If the value of the number if lesser than 0, ”Number is negative” is negative.

Runtime Test Cases


Case 1:
Enter number: 45
Number is positive

Case 2:
Enter number: -30
Number is negative

Python Program to Take in the Marks of 5 Subjects and Display


the Grade
This is a Python Program to take in the marks of 5 subjects and display the grade.

Problem Description
The program takes in the marks of 5 subjects and displays the grade.

Problem Solution
1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.
Program/Source Code
Here is source code of the Python Program to take in the marks of 5 subjects and display
the grade. The program output is also shown below.

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Program Explanation
1. User must enter 5 different values and store it in separate variables.
2. Then sum up all the five marks and divide by 5 to find the average of the marks.
3. If the average is greater than 90, “Grade: A” is printed.
4. If the average is in between 80 and 90, “Grade: B” is printed.
5. If the average is in between 70 and 80, “Grade: C” is printed.
6. If the average is in between 60 and 70, “Grade: D” is printed.
7. If the average is anything below 60, “Grade: F” is printed.

Runtime Test Cases


Case 1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100
Grade: A

Case 2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80
Grade: B
Python Program to Print all Numbers in a Range Divisible by a
Given Number
This is a Python Program to print all numbers in a range divisible by a given number.

Problem Description
The program prints all numbers in a range divisible by a given number.

Problem Solution
1. Take in the upper range and lower range limit from the user.
2. Take in the number to be divided by from the user.
3. Using a for loop, print all the factors which is divisible by the number.
4. Exit.

Program/Source Code
Here is the source code of the Python Program to print all numbers in a range divisible by a
given number. The program output is also shown below.

lower=int(input("Enter lower range limit:"))


upper=int(input("Enter upper range limit:"))
n=int(input("Enter the number to be divided by:"))
for i in range(lower,upper+1):
if(i%n==0):
print(i)
Program Explanation
1. User must enter the upper range limit and the lower range limit.
2. Then the user must enter the number to be divided from the user.
3. The value of i ranges from the lower limit to the upper limit.
4. Whenever the remainder of the number divided by i is equal to 0, i is printed.

Runtime Test Cases


Case 1:
Enter lower range limit:1
Enter upper range limit:50
Enter the number to be divided by:5
5
10
15
20
25
30
35
40
45
50

Case 2:
Enter lower range limit:50
Enter upper range limit:100
Enter the number to be divided by:7
56
63
70
77
84
91
98

Python Program to Read Two Numbers and Print Their


Quotient and Remainder
This is a Python Program to read two numbers and print their quotient and remainder.

Problem Description
The program takes two numbers and prints the quotient and remainder.

Problem Solution
1. Take in the first and second number and store it in separate variables.
2. Then obtain the quotient using division and the remainder using modulus operator.
3. Exit.

Program/Source Code
Here is the source code of the Python Program to read two numbers and print their quotient
and remainder. The program output is also shown below.

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


b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Program Explanation
1. User must enter the first and second number .
2. The quotient is obtained using true division (// operator).
3. The modulus operator gives the remainder when a is divided by b.

Runtime Test Cases


Case 1:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1

Case 2:
Enter the first number: 125
Enter the second number: 7
Quotient is: 17
Remainder is: 6

Python Program to Read Two Numbers and Print Their


Quotient and Remainder
This is a Python Program to read two numbers and print their quotient and remainder.

Problem Description
The program takes two numbers and prints the quotient and remainder.

Problem Solution
1. Take in the first and second number and store it in separate variables.
2. Then obtain the quotient using division and the remainder using modulus operator.
3. Exit.

Program/Source Code
Here is the source code of the Python Program to read two numbers and print their quotient
and remainder. The program output is also shown below.

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


b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Program Explanation
1. User must enter the first and second number .
2. The quotient is obtained using true division (// operator).
3. The modulus operator gives the remainder when a is divided by b.

Runtime Test Cases


Case 1:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1

Case 2:
Enter the first number: 125
Enter the second number: 7
Quotient is: 17
Remainder is: 6

Python Program to Read Two Numbers and Print Their


Quotient and Remainder
This is a Python Program to read two numbers and print their quotient and remainder.

Problem Description
The program takes two numbers and prints the quotient and remainder.

Problem Solution
1. Take in the first and second number and store it in separate variables.
2. Then obtain the quotient using division and the remainder using modulus operator.
3. Exit.

Program/Source Code
Here is the source code of the Python Program to read two numbers and print their quotient
and remainder. The program output is also shown below.

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


b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
Program Explanation
1. User must enter the first and second number .
2. The quotient is obtained using true division (// operator).
3. The modulus operator gives the remainder when a is divided by b.

Runtime Test Cases


Case 1:
Enter the first number: 15
Enter the second number: 7
Quotient is: 2
Remainder is: 1

Case 2:
Enter the first number: 125
Enter the second number: 7
Quotient is: 17
Remainder is: 6

Python Program to Find the Sum of Digits in a Number


This is a Python Program to find the sum of digits in a number.

Problem Description
The program takes in a number and finds the sum of digits in a number.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Using a while loop, get each digit of the number and add the digits to a variable.
3. Print the sum of the digits of the number.
4. Exit.

Program/Source Code
Here is the source code of the Python Program to find the sum of digits in a number. The
program output is also shown below.

n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)
Program Explanation
1. User must first enter the value and store it in a variable.
2. The while loop is used and the last digit of the number is obtained by using the modulus
operator.
3. The digit is added to another variable each time the loop is executed.
4. This loop terminates when the value of the number is 0.
5. The total sum of the number is then printed.

Runtime Test Cases


Case 1:
Enter a number:1892
The total sum of digits is: 20
Case 2:
Enter a number:157
The total sum of digits is: 13

Python Program to Find the Smallest Divisor of an Integer


This is a Python Program to find the smallest divisor of an integer.

Problem Description
The program takes in an integer and prints the smallest divisor of the integer.

Problem Solution
1. Take in an integer from the user.
2. Use a for loop where the value of i ranges from 2 to the integer.
3. If the number is divisible by i, the value of i is appended to the list.
4. The list is then sorted and the smallest element is printed.
5. Exit.

Program/Source Code
Here is the source code of the Python Program to find the smallest divisor of an integer.
The program output is also shown below.

n=int(input("Enter an integer:"))
a=[]
for i in range(2,n+1):
if(n%i==0):
a.append(i)
a.sort()
print("Smallest divisor is:",a[0])
Program Explanation
1. User must enter an integer
2. The for loop ranges from 2 to the number
3. If the remainder of the number divided by the value of i is 0 that means that the element
is a divisor of the number
4. The divisor of the number is then appended to the list
5. The list is then sorted and the smallest element which is the element with index 0 is
printed

Runtime Test Cases


Case 1:
Enter an integer:75
Smallest divisor is: 3

Case 2:
Enter an integer:64
Smallest divisor is: 2

Python Program to Count the Number of Digits in a Number


This is a Python Program to count the number of digits in a number.

Problem Description
The program takes the number and prints the number of digits in the number.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Using a while loop, get each digit of the number and increment the count each time a
digit is obtained.
3. Print the number of digits in the given integer.
4. Exit.

Program/Source Code
Here is source code of the Python Program to count the number of digits in a number. The
program output is also shown below.
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
Program Explanation
1. User must first enter the value of the integer and store it in a variable.
2. The while loop is used and the last digit of the number is obtained by using the modulus
operator.
3. Each time a digit is obtained, the count value is incremented.
4. This loop terminates when the value of the number is 0.
5. The total count of the number of digits is printed.

Runtime Test Cases


Case 1:
Enter number:123
The number of digits in the number are: 3
Case 2:
Enter number:1892
The number of digits in the number are: 4

Python Program to Check if a Number is a Palindrome


This is a Python Program to check whether a given number is a palindrome.

Problem Description
The program takes a number and checks whether it is a palindrome or not.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Transfer the value of the integer into another temporary variable.
3. Using a while loop, get each digit of the number and store the reversed number in
another variable.
4. Check if the reverse of the number is equal to the one in the temporary variable.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check whether a given number is a
palindrome. The program output is also shown below.

n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
Program Explanation
1. User must first enter the value of the integer and store it in a variable.
2. The value of the integer is then stored in another temporary variable.
3. The while loop is used and the last digit of the number is obtained by using the modulus
operator.
4. The last digit is then stored at the one’s place, second last at the ten’s place and so on.
5. The last digit is then removed by truly dividing the number with 10.
6. This loop terminates when the value of the number is 0.
7. The reverse of the number is then compared with the integer value stored in the
temporary variable.
8. If both are equal, the number is a palindrome.
9. If both aren’t equal, the number isn’t a palindrome.
10. The final result is then printed.

Runtime Test Cases


Case 1
Enter number:121
The number is a palindrome!

Case 2
Enter number:567
The number isn't a palindrome!

Python Program to Print all Integers that Aren’t Divisible by


Either 2 or 3 and Lie between 1 and 50.
This is a Python Program to print all integers that aren’t divisible by either 2 or 3 and lies
between 1 and 50.

Problem Description
The program prints all integers that aren’t divisible by either 2 or 3 and lies between 1 and
50.

Problem Solution
1. Use a for-loop ranging from 0 to 51.
2. Then use an if statement to check if the number isn’t divisible by both 2 and 3.
3. Print the numbers satisfying the condition.
4. Exit.

Program/Source Code
Here is source code of the Python Program to print all integers that aren’t divisible by either
2 or 3 and lies between 1 and 50. The program output is also shown below.

for i in range(0,51):
if(i%2!=0&i%3!=0):
print(i)
Program Explanation
1. The for loop ranges from 0 to 50 (as 51 isn’t exclusive).
2. The expression within the if-statement checks if the remainder obtained when the number
divided by 2 and 3 is one or not.
3. If the remainder isn’t equal to 0, the number isn’t divisible by either 2 and 3.
4. The number satisfying the condition is printed.

Runtime Test Cases


Case 1:
1
5
7
11
13
17
19
23
25
29
31
35
37
41
43
47
49

Python Program to Read a Number n And Print the Series


“1+2+…..+n= “
This is a Python Program to read a number n and print and compute the series
“1+2+…+n=”.

Problem Description
The program takes a number n and prints and computes the series “1+2+…+n=”.

Problem Solution
1. Take a value from the user and store it in a variable n.
2. Use a for loop where the value of i ranges between the values of 1 and n.
3. Print the value of i and ‘+’ operator while appending the value of i to a list.
4. Then find the sum of elements in the list.
5. Print ‘=’ followed by the total sum.
6. Exit.
Program/Source Code
Here is the source code of the Python Program to read a number n and print and compute
the series “1+2+…+n=”. The program output is also shown below.
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))

print()
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The for loop enables i to range between 1 and n (as n+1 is not included).
3. For each iteration, the value of i is printed.
4. ‘+’ operator is printed only if i<="" div="">

Runtime Test Cases


Case 1:
Enter a number: 4
1 + 2 + 3 + 4 = 10

Case 2:
Enter a number: 5
1 + 2 + 3 + 4 + 5 = 15

Python Program to Read a Number n and Print the Natural


Numbers Summation Pattern
This is a Python Program to read a number n and print the natural numbers summation
pattern.

Problem Description
The program takes a number n and prints the natural numbers summation pattern.

Problem Solution
1. Take a value from the user and store it in a variable n.
2. Use two for loop where the value of j ranges between the values of 1 and n and value of i
ranges between 1 and j.
3. Print the value of i and ‘+’ operator while appending the value of i to a list.
4. Then find the sum of elements in the list.
5. Print ‘=’ followed by the total sum.
6. Exit.

Program/Source Code
Here is the source code of the Python Program to read a number n and print the natural
numbers summation pattern. The program output is also shown below.
n=int(input("Enter a number: "))
for j in range(1,n+1):
a=[]
for i in range(1,j+1):
print(i,sep=" ",end=" ")
if(i<j):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))

print()
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The outer for loop enables j to range between 1 and n (as n+1 is not included) while the
inner for loop enables i to range between 1 and i.
3. For each iteration, the value of i is printed.
4. ‘+’ operator is printed only if i<="" div="">

Runtime Test Cases


Case 1:
Enter a number: 4
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10

Case 2:
Enter a number: 5
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15

Python Program to Print an Identity Matrix


This is a Python Program to read a number n and print an identity matrix of the desired size.
Problem Description
The program takes a number n and prints an identity matrix of the desired size.

Problem Solution
1. Take a value from the user and store it in a variable n.
2. Use two for loop where the value of j ranges between the values of 0 and n-1 and value
of i also ranges between 0 and n-1.
3. Print the value of 1 when i is equal to j and 0 otherwise.
4. Exit.

Program/Source Code
Here is the source code of the Python Program to read a number n and print an identity
matrix of the desired size. The program output is also shown below.
n=int(input("Enter a number: "))
for i in range(0,n):
for j in range(0,n):
if(i==j):
print("1",sep=" ",end=" ")
else:
print("0",sep=" ",end=" ")
print()
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The outer for loop enables j to range between 1 and n-1 (as n is not included) while the
inner for loop also enables i to range between 1 and n-1.
3. For each iteration, the value of 1 is printed if i is equal to j and value of 0 is printed
otherwise.
4. The sep and end parameters of the print function help in formatting and print() allows
values to printed in a new line for each iteration of the outer for loop.

Runtime Test Cases


Case 1:
Enter a number: 4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

Case 2:
Enter a number: 5
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

Python Program to Print an Inverted Star Pattern


This is a Python Program to read a number n and print an inverted star pattern of the
desired size.

Problem Description
The program takes a number n and prints an inverted star pattern of the desired size.

Problem Solution
1. Take a value from the user and store it in a variable n.
2. Use a for loop where the value of i ranges between the values of n-1 and 0 with a
decrement of 1 with each iteration.
3. Multiply empty spaces with n-i and ‘*’ with i and print both of them.
4. Exit.

Program/Source Code
Here is the source code of the Python Program to read a number n and print an inverted
star pattern of the desired size. The program output is also shown below.
n=int(input("Enter number of rows: "))
for i in range (n,0,-1):
print((n-i) * ' ' + i * '*')
Program Explanation
1. User must first enter the value and store it in a variable n.
2. The for loop enables i to range between n-1 and 0 with a decrement of 1 with each
iteration.
3. For each iteration, ” ” is multiplied with n-i and ‘*’ is multiplied with i to ensure correct
spacing of the stars.
4. The required pattern is printed.

Runtime Test Cases


Case 1:
Enter number of rows: 5
*****
****
***
**
*

Case 2:
Enter number of rows: 10
**********
*********
********
*******
******
*****
****
***
**
*

Python Program to Read Print Prime Numbers in a Range using


Sieve of Eratosthenes
This is a Python Program to print prime numbers in a range using Sieve of Eratosthenes.

Problem Description
The program takes a range and prints prime numbers in that range using Sieve of
Eratosthenes.

Problem Solution
1. Take the value of n from the user.
2. Initialise the sieve with numbers from 2 to n.
3. Use a while loop with the condition that the sieve is not empty
4. Get the smallest number that is prime
5. Remove that number and it’s multiples
6. Continue till the sieve is empty
7. Exit

Program/Source Code
Here is the source code of the Python Program to takes a range and print prime numbers in
that range using Sieve of Eratosthenes. The program output is also shown below.
n=int(input("Enter upper limit of range: "))
sieve=set(range(2,n+1))
while sieve:
prime=min(sieve)
print(prime,end="\t")
sieve-=set(range(prime,n+1,prime))

print()
Program Explanation
1. User must first enter the value for upper limit of range and store it in a variable n.
2. The sieve is initialised to a set which ranges from 2 to n( as n+1 is not included).
3. The while loop is used to ensure that the sieve isn’t empty.
4. The variable prime is initialised with the least number in the sieve and the prime number
is printed.
5. The sieve is then removed with all multiples of the prime number.
6. Steps 4 and 5 continue till value of sieve becomes empty.

Runtime Test Cases


Case 1:
Enter upper limit of range: 10
2 3 5 7

Case 2:
Enter upper limit of range: 15
2 3 5 7 11 13

2. Python Programming Examples on Mathematical Functions

Python Program to Check if a Date is Valid and Print the


Incremented Date if it is
This is a Python Program to check if a date is valid and print the incremented date if it is.

Problem Description
The program takes in a date and checks if it a valid date and prints the incremented date if it
is.

Problem Solution
1. Take in the date of the form: dd/mm/yyyy.
2. Split the date and store the day, month and year in separate variables.
3. Use various if-statements to check if the day, month and year are valid.
4. Increment the date if the date is valid and print it
5. Exit.

Program/Source Code
Here is source code of the Python Program to check if a date is valid and print the
incremented date if it is. The program output is also shown below.

date=input("Enter the date: ")


dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
max1=29
else:
max1=28
if(mm<1 or mm>12):
print("Date is invalid.")
elif(dd<1 or dd>max1):
print("Date is invalid.")
elif(dd==max1 and mm!=12):
dd=1
mm=mm+1
print("The incremented date is: ",dd,mm,yy)
elif(dd==31 and mm==12):
dd=1
mm=1
yy=yy+1
print("The incremented date is: ",dd,mm,yy)
else:
dd=dd+1
print("The incremented date is: ",dd,mm,yy)
Program Explanation
1. User must enter the date of the form dd/mm/yy.
2. The date is then split and the day, month and year is stored in separate variables.
3. If the day isn’t between 1 and 30 for the months of April, June, September and
November, the date is invalid.
4. If the day isn’t between 1 and 31 for the months January, March, April, May, July, August,
October and December, the date is invalid.
5. If the month is February, the day should be between 1 and 28 for years other than the
leap year and between 1 and 29 for leap years.
6. If the date is valid, the date should be incremented.
7. The final result is printed.

Runtime Test Cases


Case 1
Enter the date: 5/7/2016
The incremented date is: 6 7 2016

Case 2
Enter the date: 30/2/1997
Date is invalid.

Case 3
Enter the date: 31/12/2016
The incremented date is: 1 1 2017

Python Program to Compute Simple Interest Given all the


Required Values
This is a Python Program to compute simple interest given all the required values.

Problem Description
The program computes simple interest given the principle amount, rate and time.

Problem Solution
1. Take in the values for principle amount, rate and time.
2. Using the formula, compute the simple interest.
3. Print the value for the computed interest.
4. Exit.

Program/Source Code
Here is source code of the Python Program to compute simple interest given all the required
values. The program output is also shown below.

principle=float(input("Enter the principle amount:"))


time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is:",simple_interest)
Program Explanation
1. User must enter the values for the principle amount, rate and time.
2. The formula: (amount*time*rate)/100 is used to compute simple interest.
3. The simple interest is later printed.

Runtime Test Cases


Case 1:
Enter the principle amount:200
Enter the time(years):5
Enter the rate:5.0
The simple interest is: 50.0

Case 2:
Enter the principle amount:70000
Enter the time(years):1
Enter the rate:4.0
The simple interest is: 2800.0

Python Program to Check Whether a Given Year is a Leap Year


This is a Python Program to check whether a given year is a leap year or not.

Problem Description
The program takes in a year and checks whether it is a leap year or not.

Problem Solution
1. Take the value of the year as input
2. Using an if-statement, check whether the year is a leap year or not
3. Print the final result
4. Exit

Program/Source Code
Here is source code of the Python Program to Calculate the Average of Numbers in a Given
List. The program output is also shown below.

year=int(input("Enter year to be checked:"))


if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!)
else:
print("The year isn't a leap year!)
Program Explanation
1. User must first enter the year to be checked.
2. The if statement checks if the year is a multiple of 4 but isn’t a multiple of 100 or if it is a
multiple of 400 (not every year that is a multiple of 4 is a leap year).
3. Then the result is printed.

Runtime Test Cases


Case 1:
Enter year to be checked:2016
The year is a leap year!
Case 2:
Enter year to be checked:2005
The year isn't a leap year!

Python Program to Read Height in Centimeters and then


Convert the Height to Feet and Inches
This is a Python Program to read height in centimeters and then convert the height to feet
and inches

Problem Description
The program reads the height in centimeters and then converts the height to feet and
inches.

Problem Solution
1. Take the height in centimeters and store it in a variable.
2. Convert the height in centimeters into inches and feet.
3. Print the length in inches and feet.
4. Exit.

Program/Source Code
Here is source code of the Python Program to Calculate the Average of Numbers in a Given
List. The program output is also shown below.

cm=int(input("Enter the height in centimeters:"))


inches=0.394*cm
feet=0.0328*cm
print("The length in inches",round(inches,2))
print("The length in feet",round(feet,2))
Program Explanation
1. User must enter the height in centimeters.
2. The height in centimeters is multiplied by 0.394 and stored in another variable which now
contains the height in inches.
3. The height in centimeters is multiplied by 0.0328 and stored in another variable which
now contains the height in feet.
4. The converted height in inches and feet is printed.

Runtime Test Cases


Case 1:
Enter the height in centimeters:50
The length in inches 19.7
The length in feet 1.64

Case 2:
Enter the height in centimeters:153
The length in inches 60.28
The length in feet 5.02

Python Program to Take the Temperature in Celcius and Covert


it to Farenheit
This is a Python Program to take the temperature in Celsius and convert it to Fahrenheit.

Problem Description
The program takes the temperature in Celsius and converts it to Fahrenheit.

Problem Solution
1. Take the value of temperature in Celsius and store it in a variable.
2. Convert it to Fahrenheit.
3. Print the final result.
4. Exit.

Program/Source Code
Here is source code of the Python Program to take the temperature in Celsius and convert it
to Fahrenheit. The program output is also shown below.

celsius=int(input("Enter the temperature in celcius:"))


f=(celsius*1.8)+32
print("Temperature in farenheit is:",f)
Program Explanation
1. User must first enter the value of temperature in Celsius.
2. Using the formula of: f=(c*1.8)+32, convert Celsius to Fahrenheit.
3. Print the temperature in Fahrenheit.

Runtime Test Cases


Case 1:
Enter the temperature in celcius:32
Temperature in Fahrenheit is: 89.6

Case 2:
Enter the temperature in celcius:48
Temperature in Fahrenheit is: 118.4
Python Program to Compute Prime Factors of an Integer
This is a Python Program to compute prime factors of an integer.

Problem Description
The program takes a number and computes the prime factors of the integer.

Problem Solution
1. Take the value of the integer and store in a variable.
2. Using a while loop, first obtain the factors of the number.
3. Using another while loop within the previous one, compute if the factors are prime or not.
4. Exit.

Program/Source Code
Here is source code of the Python Program to compute prime factors of an integer. The
program output is also shown below.

n=int(input("Enter an integer:"))
print("Factors are:")
i=1
while(i<=n):
k=0
if(n%i==0):
j=1
while(j<=i):
if(i%j==0):
k=k+1
j=j+1
if(k==2):
print(i)
i=i+1
Program Explanation
1. User must first enter the value and store it in a variable.
2. The while loop is used and the factors of the integer are computed by using the modulus
operator and checking if the remainder of the number divided by i is 0.
3. Then the factors of the integer are then again checked if the factor is prime or not.
4. If the factor of the integer has two factors, the factor is prime.
5. The prime factor of the integer is printed.

Runtime Test Cases


Case 1:
Enter an integer:25
Factors are:
5
Case 2:
Enter an integer:200
Factors are:
2
5

Python Program to Generate all the Divisors of an Integer


This is a Python Program to generate all the divisors of an integer.

Problem Description
The program takes a number and generates all the divisors of the number.

Problem Solution
1. Take the value of the integer and store it in a variable.
2. Use a for loop and if statement to generate the divisors of the integer.
3. Print the divisors of the number.
4. Exit.

Program/Source Code
Here is source code of the Python Program to generate all the divisors of an integer. The
program output is also shown below.

n=int(input("Enter an integer:"))
print("The divisors of the number are:")
for i in range(1,n+1):
if(n%i==0):
print(i)
Program Explanation
1. User must first enter the value and store it in a variable.
2. Use a for loop to generate numbers from 1 to n.
3. Using an if statement check if the number divided by i gives the remainder as 0 which is
basically the divisor of the integer.
4. Print the divisors of the number.

Runtime Test Cases


Case 1:
Enter an integer:25
The divisors of the number are:
1
5
25
Case 2:
Enter an integer:20
The divisors of the number are:
1
2
4
5
10
20

Python Program to Print Table of a Given Number


This is a Python Program to print the table of a given number.

Problem Description
The program takes in a number and prints the table of a given number.

Problem Solution
1. Take in a number and store it in a variable.
2. Print the multiplication tables of a given number.
3. Exit.

Program/Source Code
Here is source code of the Python Program to print the table of a given number. The
program output is also shown below.

n=int(input("Enter the number to print the tables for:"))


for i in range(1,11):
print(n,"x",i,"=",n*i)
Program Explanation
1. User must enter a number.
2. Using a print statement, print the multiplication tables of the given number.

Runtime Test Cases


Case 1:
Enter the number to print the tables for:7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Case 2:
Enter the number to print the tables for:17
17 x 1 = 17
17 x 2 = 34
17 x 3 = 51
17 x 4 = 68
17 x 5 = 85
17 x 6 = 102
17 x 7 = 119
17 x 8 = 136
17 x 9 = 153
17 x 10 = 170

Python Program to Print Sum of Negative Numbers, Positive


Even Numbers and Positive Odd numbers in a List
This is a Python Program to print the sum of negative numbers, positive even numbers and
positive odd numbers in a given list.

Problem Description
The program prints the sum of negative numbers, positive even numbers and positive odd
numbers in a given list..

Problem Solution
1. Take in the number of elements to be in the list from the user.
2. Take in the elements from the user using a for loop and append to a list.
3. Using a for loop, get the elements one by one from the list and check if it is positive or
negative.
4. If it is positive, check if it is odd or even and find the individual sum.
5. Find the individual sum of negative numbers.
6. Print all the sums.
7. Exit.

Program/Source Code
Here is source code of the Python Program to print the sum of negative numbers, positive
even numbers and positive odd numbers in a given list. The program output is also shown
below.

n=int(input("Enter the number of elements to be in the list:"))


b=[]
for i in range(0,n):
a=int(input("Element: "))
b.append(a)
sum1=0
sum2=0
sum3=0
for j in b:
if(j>0):
if(j%2==0):
sum1=sum1+j
else:
sum2=sum2+j
else:
sum3=sum3+j
print("Sum of all positive even numbers:",sum1)
print("Sum of all positive odd numbers:",sum2)
print("Sum of all negative numbers:",sum3)
Program Explanation
1. User must enter the number of elements to be in the list.
2. User must then enter the elements of the list one by one which is appended to the list.
3. The for loop is used to traverse through the list and obtain the elements one by one.
4. The if statement checks whether the element is positive or negative.
5. If it is positive, another if statement checks if it is odd or even.
6. The sum of even elements is stored in sum1 and the sum of odd elements is stored in
sum2.
7. The sum of negative numbers is stored in sum3.
8. All the sums are respectively printed.

Runtime Test Cases


Case 1:
Enter the number of elements to be in the list:4
Element: -12
Element: 34
Element: 35
Element: 89
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12

Case 2:
Enter the number of elements to be in the list:5
Element: -45
Element: -23
Element: 56
Element: 23
Element: 7
Sum of all positive even numbers: 56
Sum of all positive odd numbers: 30
Sum of all negative numbers: -68

Python Program to Print Largest Even and Largest Odd


Number in a List
This is a Python Program to print the largest even and largest odd number in a list.

Problem Description
The program takes in a list and prints the largest even and largest off number in it.

Problem Solution
1. Take in the number of elements to be in the list from the user.
2. Take in the elements from the user using a for loop and append to a list.
3. Using a for loop, get the elements one by one from the list and check if it odd or even and
append them to different lists.
4. Sort both the lists individually and get the length of each list.
5. Print the last elements of the sorted lists.
6. Exit.

Program/Source Code
Here is source code of the Python Program to print the largest even and largest odd
number in a list. The program output is also shown below.

n=int(input("Enter the number of elements to be in the list:"))


b=[]
for i in range(0,n):
a=int(input("Element: "))
b.append(a)
c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1+1
for j in d:
count2=count2+1
print("Largest even number:",c[count1-1])
print("Largest odd number",d[count2-1])
Program Explanation
1. User must enter the number of elements to be in the list.
2. User must then enter the elements of the list one by one which is appended to the list.
3. The for loop is used to traverse through the list and obtain the elements one by one.
4. The if statement checks whether the element is odd or even.
5. The odd elements are appended to another list and the even elements are appending to
another list.
6. Both the lists are then sorted.
7. The individual lengths of both the lists is obtained using for loops.
8. The last element of the sorted lists which is the largest odd and largest even number is
printed.

Runtime Test Cases


Case 1:
Enter the number of elements to be in the list:5
Element: 45
Element: 20
Element: 80
Element: 93
Element: 3
Largest even number: 80
Largest odd number 93

Case 2:
Enter the number of elements to be in the list:4
Element: 23
Element: 10
Element: 34
Element: 89
Largest even number: 34
Largest odd number 89

Python Program to Form an Integer that has the Number of


Digits at Ten’s Place and the Least Significant Digit of the
Entered Integer at One’s Place
This is a Python Program to form an integer that has the number of digits at the ten’s place
and the least significant digit in the one’s place.

Problem Description
The program takes an integer and forms a new integer which has the number of digits at the
ten’s place and the least significant digit in the one’s place.
Problem Solution
1. Take in an integer and store it in a variable.
2. Make a separate copy of the integer.
3. Using a while loop, calculate the number of digits in the integer.
4. Convert the copy of the integer and the count of the number of digits to string.
5. Concatenate the last digit of the integer to the count and convert the new integer back to
int.
6. Print the newly formed integer.
7. Exit.

Program/Source Code
Here is source code of the Python Program tto form an integer that has the number of digits
at the ten’s place and the most significant digit in the one’s place. The program output is
also shown below.

n=int(input("Enter the number:"))


tmp=n
k=0
while(n>0):
k=k+1
n=n//10
b=str(tmp)
c=str(k)
d=c+b[k-1]
print("The new number formed:",int(d))
Program Explanation
1. User must enter the number and store it in a variable.
2. A copy of the variable is made because the original value of the variable would be
changed for counting the number of digits.
3. The while loop is used and the last digit of the number is obtained by using the modulus
operator.
4. Each time a digit is obtained, the count value is incremented.
5. The number of digits of the variable and the number is converted to string for ease of
concatenation.
6. Then the last digit of the string is obtained and concatenated to the count variable.
7. The new number formed is then printed.

Runtime Test Cases


Case 1:
Enter the number:129
The new number formed: 39
Case 2:
Enter the number:24678
The new number formed: 58

Python Program to Find Those Numbers which are Divisible by


7 and Multiple of 5 in a Given Range of Numbers
This is a Python Program to find those numbers which are divisible by 7 and multiple of 5 in
a given range of numbers.

Problem Description
The program takes an upper range and lower range and finds those numbers within the
range which are divisible by 7 and multiple of 5.

Problem Solution
1. Take in the upper and lower range and store it in separate variables.
2. Use a for loop which ranges from the lower range to the upper range.
3. Then find the numbers which are divisible by both 5 and 7.
4. Print those numbers
5. Exit.

Program/Source Code
Here is source code of the Python Program to find those numbers which are divisible by 7
and multiple of 5 in a given range of numbers. The program output is also shown below.

lower=int(input("Enter the lower range:"))


upper=int(input("Enter the upper range:"))
for i in range (lower,upper+1):
if(i%7==0 and i%5==0):
print(i)
Program Explanation
1. User must enter the upper range limit and the lower range limit.
2. Then the for loop ranges from the lower limit to the upper limit.
3. The value of i ranges from the lower limit to the upper limit.
4. Whenever the remainder of i divided by 5 and 7 is equal to 0, i is printed.

Runtime Test Cases


Case 1:
Enter the lower range:1
Enter the upper range:100
35
70

Case 2:
Enter the lower range:400
Enter the upper range:700
420
455
490
525
560
595
630
665
700

Python Program to Check if a Number is an Armstrong Number


This is a Python Program to check if a number is an Armstrong number.

Problem Description
The program takes a number and checks if it is an Armstrong number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Convert each digit of the number to a string variable and store it in a list.
3. Then cube each of the digits and store it in another list.
4. Find the sum of the cube of digits in the list and check if it is equal to the original number.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is an Armstrong number.
The program output is also shown below.

n=int(input("Enter any number: "))


a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
print("The number is an armstrong number. ")
else:
print("The number isn't an arsmtrong number. ")
Program Explanation
1. User must enter the number and store it in a variable.
2. The map function obtains each digit from the number and converts it to a string and
stores it in a list.
3. The second map function cubes each digit and stores it in another list.
4. Then the sum of the cubes of the digits is found and is checked if it is equal to the original
number.
5. If the sum of the cube of digits is equal to the original number, the number is an
Armstrong number.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter any number: 13
The number isn't an arsmtrong number.

Case 2:
Enter any number: 371
The number is an armstrong number.

Python Program to Print the Pascal’s triangle for n number of


rows given by the user
This is a Python Program to print the pascal’s triangle for n number of rows given by the
user.

Problem Description
The program takes a number n and prints the pascal’s triangle having n number of rows.

Problem Solution
1. Take in the number of rows the triangle should have and store it in a separate variable.
2. Using a for loop which ranges from 0 to n-1, append the sub-lists into the list.
3. Then append 1 into the sub-lists.
4. Then use a for loop to determine the value of the number inside the triangle.
5. Print the Pascal’s triangle according to the format.
6. Exit.

Program/Source Code
Here is source code of the Python Program to print the pascal’s triangle for n number of
rows given by the user. The program output is also shown below.
n=int(input("Enter number of rows: "))
a=[]
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1,i):
a[i].append(a[i-1][j-1]+a[i-1][j])
if(n!=0):
a[i].append(1)
for i in range(n):
print(" "*(n-i),end=" ",sep=" ")
for j in range(0,i+1):
print('{0:6}'.format(a[i][j]),end=" ",sep=" ")
print()
Program Explanation
1. User must enter the number of rows that the Pascal’s triangle should have.
2. The for loop is used to append sub-lists into an empty list defined earlier.
3. Then 1 is appended into all the sub-lists.
4. The for loop is used to determine the value of the number inside the triangle which is the
sum of the two numbers above it.
5. The other for loop is used to print the Pascal’s triangle according to the format.

Runtime Test Cases


Case 1:
Enter number of rows: 3
1
1 1
1 2 1

Case 2:
Enter number of rows: 4
1
1 1
1 2 1
1 3 3 1

Python Program to Check if a Number is a Perfect Number


This is a Python Program to check if a number is a Perfect number.

Problem Description
The program takes a number and checks if it is a Perfect number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Initialize a variable to count the sum of the proper divisors to 0.
3. Use a for loop and an if statement to add the proper divisors of the integer to the sum
variable.
4. Check if the sum of the proper divisors of the number is equal to the variable.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is a Perfect number. The
program output is also shown below.

n = int(input("Enter any number: "))


sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
Program Explanation
1. User must enter the number and store it in a variable.
2. Use a for loop to generate numbers from 1 to n (where n is not included as we need the
sum of the proper divisors of the number).
3. Using an if statement check if the number divided by i gives the remainder as 0 which is
basically the proper divisor of the integer.
4. Then the proper divisors of the number are added to the sum variable.
5. If the sum of the proper divisors of the number is equal to the original number, tje number
is a Perfect number.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter any number: 6
The number is a Perfect number!

Case 2:
Enter any number: 25
The number is not a Perfect number!

Python Program to Check if a Number is a Strong Number


This is a Python Program to check if a number is a strong number.

Problem Description
The program takes a number and checks if it is a strong number.

Problem Solution
1. Take in an integer and store it in a variable.
2. Using two while loops, find the factorial of each of the digits in the number.
3. Then sum up all the factorials of the digits.
4. Check if the sum of the factorials of the digits is equal to the number.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is a strong number. The
program output is also shown below.

sum1=0
num=int(input("Enter a number:"))
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print("The number is a strong number")
else:
print("The number is not a strong number")
Program Explanation
1. User must enter the number and store it in a variable.
2. A copy of the original number is made as the original value will get altered in the later
course of the program.
3. Using a while loop, each of the digits of the numbers is obtained.
4. Then the other while loop is used to find the factorial of the individual digits and store it in
a sum variable.
5. If the sum of the factorial of the digits in a number is equal to the original number, the
number is a strong number.
6. The final result is printed.
Runtime Test Cases
Case 1:
Enter a number:145
The number is a strong number.

Case 2:
Enter a number:234
The number is not a strong number.

Python Program to Find the LCM of Two Numbers


This is a Python Program to find the LCM of two numbers.

Problem Description
The program takes two numbers and prints the LCM of two numbers.

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.

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
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 a
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.

Runtime Test Cases


Case 1:
Enter the first number:5
Enter the second number:3
LCM is: 15

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

Python Program to Find the GCD of Two Numbers


This is a Python Program to find the GCD of two numbers.

Problem Description
The program takes two numbers and prints the GCD of two numbers.

Problem Solution
1. Import the fractions module.
2. Take in both the integers and store it in separate variables.
3. Use the in-built function to find the GCD of both the numbers.
4. Print the GCD.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the GCD of two numbers. The program
output is also shown below.
import fractions
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
print("The GCD of the two numbers is",fractions.gcd(a,b))
Program Explanation
1. Import the fractions module.
2. User must enter both the numbers and store it in separate variables.
3. The in-built function of fractions.gcd(a,b) is used where a and b are the variables
containing the integer values.
4. The final GCD is printed.

Runtime Test Cases


Case 1:
Enter the first number:15
Enter the second number:5
The GCD of the two numbers is 5

Case 2:
Enter the first number:105
Enter the second number:222
The GCD of the two numbers is 3

Python Program to Compute a Polynomial Equation given that


the Coefficients of the Polynomial are stored in a List
This is a Python Program to compute a polynomial equation given that the coefficients of
the polynomial are stored in the list.

Problem Description
The program takes the coefficients of the polynomial equation and the value of x and gives
the value of the polynomial.

Problem Solution
1. Import the math module.
2. Take in the coefficients of the polynomial equation and store it in a list.
3. Take in the value of x.
4. Use a for loop and while loop to compute the value of the polynomial expression for the
first three terms and store it in a sum variable.
5. Add the fourth term to the sum variable.
6. Print the computed value.
7. Exit.

Program/Source Code
Here is source code of the Python Program to compute a polynomial equation given that the
coefficients of the polynomial are stored in a list. The program output is also shown below.
import math
print("Enter the coefficients of the form ax^3 + bx^2 + cx + d")
lst=[]
for i in range(0,4):
a=int(input("Enter coefficient:"))
lst.append(a)
x=int(input("Enter the value of x:"))
sum1=0
j=3
for i in range(0,3):
while(j>0):
sum1=sum1+(lst[i]*math.pow(x,j))
break
j=j-1
sum1=sum1+lst[3]
print("The value of the polynomial is:",sum1)
Program Explanation
1. The math module is imported.
2. User must enter the coefficients of the polynomial which is stored in a list.
3. User must also enter the value of x.
4. The value of i ranges from 0 to 2 using the for loop which is used to access the
coefficients in the list.
5. The value of j ranges from 3 to 1, which is used to determine the power for the value of x.
6. The value of the first three terms is computed this way.
7. The last term is added to the final sum.
8. The final computed value is printed.

Runtime Test Cases


Case 1:
Enter the coefficients of the form ax^3 + bx^2 + cx + d
Enter coefficient:3
Enter coefficient:4
Enter coefficient:5
Enter coefficient:6
Enter the value of x:2
The value of the polynomial is: 56.0

Case 2:
Enter the coefficients of the form ax^3 + bx^2 + cx + d
Enter coefficient:2
Enter coefficient:5
Enter coefficient:6
Enter coefficient:3
Enter the value of x:1
The value of the polynomial is: 16.0
Python Program to Check If Two Numbers are Amicable
Numbers
This is a Python Program to check if two numbers are amicable numbers.

Problem Description
The program takes two numbers and checks if they are amicable numbers.

Problem Solution
1. Take in both the integers and store it in separate variables.
2. Find the sum of the proper divisors of both the numbers.
3. Check if the sum of the proper divisors is equal to the opposite numbers.
4. If they are equal, they are amicable numbers.
5. Print the final result.
6. Exit.

Program/Source Code
Here is the source code of the Python Program to check if two numbers are amicable
numbers. The program output is also shown below.
x=int(input('Enter number 1: '))
y=int(input('Enter number 2: '))
sum1=0
sum2=0
for i in range(1,x):
if x%i==0:
sum1+=i
for j in range(1,y):
if y%j==0:
sum2+=j
if(sum1==y and sum2==x):
print('Amicable!')
else:
print('Not Amicable!')
Program Explanation
1. User must enter both the numbers and store it in separate variables.
2. Using a for loop and an if statement, find the proper divisors of both the numbers.
3. Find the sum of the proper divisors of both the numbers.
4. The if statement is used to check if the sum of proper divisors of the number is equal to
the other number and vice-versa.
5. If it is equal, both the numbers are amicable numbers.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter number 1: 220
Enter number 2: 284
Amicable!

Case 2:
Enter number 1: 349
Enter number 2: 234
Not Amicable!

Python Program to Find the Area of a Triangle Given All Three


Sides
This is a Python Program to find the area of a triangle given all three sides.

Problem Description
The program takes three sides of a triangle and prints the area formed by all three sides.

Problem Solution
1. Take in all the three sides of the triangle and store it in three separate variables.
2. Then using the Heron’s formula, compute the area of the triangle.
3. Print the area of the triangle.
4. Exit.

Program/Source Code
Here is source code of the Python Program to find the area of a triangle given all three
sides. The program output is also shown below.
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
Program Explanation
1. User must enter all three numbers and store it in separate variables.
2. First the value of s is found out which is equal to (a+b+c)/2
3. Then the Heron’s formula is applied to determine the area of the triangle formed by all
three sides.
4. Then the area of the triangle is printed.

Runtime Test Cases


Case 1:
Enter first side: 15
Enter second side: 9
Enter third side: 7
Area of the triangle is: 20.69

Case 2:
Enter first side: 5
Enter second side: 6
Enter third side: 7
Area of the triangle is: 14.7

Python Program to Find the Gravitational Force Acting Between


Two Objects
This is a Python Program to find the gravitational force acting between two objects.

Problem Description
The program takes the masses of two objects and the distance between them to determine
the gravitational force acting between the objects.

Problem Solution
1. Take in both the masses and the distance between the masses and store it in separate
variables.
2. Initialize one of the variables to the value of gravitational constant, G.
3. The the formula is used to determine the force acting between the masses.
4. Rounding off up-to two decimal places, print the value of the force.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the gravitational force acting between
two objects. The program output is also shown below.
m1=float(input("Enter the first mass: "))
m2=float(input("Enter the second mass: "))
r=float(input("Enter the distance between the centres of the masses: "))
G=6.673*(10**-11)
f=(G*m1*m2)/(r**2)
print("Hence, the gravitational force is: ",round(f,2),"N")
Program Explanation
1. User must enter the values for both the masses and the distance between the masses
and store it in separate variables.
2. One of the variables is initialised to the value of gravitational constant (G) which is equal
to 6.673*(10**-11).
3. Then the formula: f=(G*m1*m2)/(r**2), where m1 and m2 are the masses and r is the
distance between them, is used to determine the magnitude of force acting between the
masses.
4. The force calculated is rounded up-to 2 decimal places and printed.

Runtime Test Cases


Case 1:
Enter the first mass: 1000000
Enter the second mass: 500000
Enter the distance between the centres of the masses: 20
Hence, the gravitational force is: 0.08 N

Case 2:
Enter the first mass: 90000000
Enter the second mass: 7000000
Enter the distance between the centres of the masses: 20
Hence, the gravitational force is: 105.1 N

Python Program to Check if a Number is a Prime Number


This is a Python Program to check if a number is a prime number.

Problem Description
The program takes in a number and checks if it is a prime number.

Problem Solution
1. Take in the number to be checked and store it in a variable.
2. Initialize the count variable to 0.
3. Let the for loop range from 2 to half of the number (excluding 1 and the number itself).
4. Then find the number of divisors using the if statement and increment the count variable
each time.
5. If the number of divisors is lesser than or equal to 0, the number is prime.
6. Print the final result.
5. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is a prime number. The
program output is also shown below.
a=int(input("Enter number: "))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print("Number is prime")
else:
print("Number isn't prime")
Program Explanation
1. User must enter the number to be checked and store it in a different variable.
2. The count variable is first initialized to 0.
3. The for loop ranges from 2 to the half of the number so 1 and the number itself aren’t
counted as divisors.
4. The if statement then checks for the divisors of the number if the remainder is equal to 0.
5. The count variable counts the number of divisors and if the count is lesser or equal to 0,
the number is a prime number.
6. If the count is greater than 0, the number isn’t prime.
7. The final result is printed.

Runtime Test Cases


Case 1:
Enter number: 7
Number is prime

Case 2:
Enter number: 35
Number isn't prime

Python Program to Print all the Prime Numbers within a Given


Range
This is a Python Program to print all prime numbers within a given range.

Problem Description
The program takes in the upper limit and prints all prime numbers within the given range.

Problem Solution
1. Take in the upper limit for the range and store it in a variable.
2. Let the first for loop range from 2 to the upper limit.
3. Initialize the count variable to 0.
4. Let the second for loop range from 2 to half of the number (excluding 1 and the number
itself).
5. Then find the number of divisors using the if statement and increment the count variable
each time.
6. If the number of divisors is lesser than or equal to 0, the number is prime.
7. Print the final result.
8. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is a prime number. The
program output is also shown below.
r=int(input("Enter upper limit: "))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
Program Explanation
1. User must enter the upper limit of the range and store it in a different variable.
2. The first for loop ranges till the upper limit entered by the user.
3. The count variable is first initialized to 0.
4. The for loop ranges from 2 to the half of the number so 1 and the number itself aren’t
counted as divisors.
5. The if statement then checks for the divisors of the number if the remainder is equal to 0.
6. The count variable counts the number of divisors and if the count is lesser or equal to 0,
the number is a prime number.
7. If the count is greater than 0, the number isn’t prime.
8. The final result is printed.

Runtime Test Cases


Case 1:
Enter upper limit: 15
2
3
5
7
11
13

Case 2:
Enter upper limit: 40
2
3
5
7
11
13
17
19
23
29
31
37

Python Program to Print Numbers in a Range (1,upper) Without


Using any Loops
This is a Python Program to print all numbers in a range without using loops.

Problem Description
The program takes in the upper limit and prints all numbers within the given range.

Problem Solution
1. Define a recursive function.
2. Define a base case for that function that the number should be greater than zero.
3. If number is greater than 0, call the function again with the argument as the number
minus 1.
4. Print the number.
5. Exit.

Program/Source Code
Here is source code of the Python Program to check if a number is a prime number. The
program output is also shown below.
def printno(upper):
if(upper>0):
printno(upper-1)
print(upper)
upper=int(input("Enter upper limit: "))
printno(upper)
Program Explanation
1. User must enter the upper limit of the range.
2. This value is passed as an argument for the recursive function.
3. The base case for the recursive function is that number should always be greater than 0.
4. If number is greater than 0, function is called again with the argument as the number
minus 1.
5. The number is printed.
6. The recursion continues until the number becomes lesser than 0.

Runtime Test Cases


Case 1:
Enter upper limit: 5
1
2
3
4
5

Case 2:
Enter upper limit: 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Python Program to Find the Sum of Sine Series


This is a Python Program to find the sum of sine series.

Problem Description
The program takes in the the number of terms and finds the sum of sine series.

Problem Solution
1. Take in the value of x in degrees and the number of terms and store it in separate
variables.
2. Pass these values to the sine function as arguments.
3. Define a sine function and using a for loop, first convert degrees to radians.
4. Then use the sine formula expansion and add each term to the sum variable.
5. Then print the final sum of the expansion.
6. Exit.
Program/Source Code
Here is source code of the Python Program to find the sum of sine series. The program
output is also shown below.
import math
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
pi=22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(sin(x,n),2))
Program Explanation
1. User must enter the value of x in degrees and the number of terms and store it in
separate variables.
2. These values are passed to the sine functions as arguments.
3. A sine function is defined and a for loop is used convert degrees to radians and find the
value of each term using the sine expansion formula.
4. Each term is added the sum variable.
5. This continues till the number of terms is equal to the number given by the user.
6. The total sum is printed.

Runtime Test Cases


Case 1:
Enter the value of x in degrees:30
Enter the number of terms:10
0.5

Case 2:
Enter the value of x in degrees:45
Enter the number of terms:15
0.71

Python Program to Find the Sum of Cosine Series


This is a Python Program to find the sum of cosine series.

Problem Description
The program takes in the the number of terms and finds the sum of cosine series.
Problem Solution
1. Take in the value of x in degrees and the number of terms and store it in separate
variables.
2. Pass these values to the cosine function as arguments.
3. Define a cosine function and using a for loop which iterates by 2 steps, first convert
degrees to radians.
4. Then use the cosine formula expansion and add each term to the sum variable.
5. Then print the final sum of the cosine expansion.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of cosine series. The program
output is also shown below.
import math
def cosine(x,n):
cosx = 1
sign = -1
for i in range(2, n, 2):
pi=22/7
y=x*(pi/180)
cosx = cosx + (sign*(y**i))/math.factorial(i)
sign = -sign
return cosx
x=int(input("Enter the value of x in degrees:"))
n=int(input("Enter the number of terms:"))
print(round(cosine(x,n),2))
Program Explanation
1. User must enter the value of x in degrees and the number of terms and store it in
separate variables.
2. These values are passed to the cosine functions as arguments.
3. A cosine function is defined and a for loop is used convert degrees to radians and find
the value of each term using the sine expansion formula.
4. Each term is added the sum variable.
5. This continues till the number of terms is equal to the number given by the user.
6. The total sum is printed.

Runtime Test Cases


Case 1:
Enter the value of x in degrees:0
Enter the number of terms:10
1.0
Case 2:
Enter the value of x in degrees:75
Enter the number of terms:15
0.26

Python Program to Find the Sum of First N Natural Numbers


This is a Python Program to find the sum of first N Natural Numbers.

Problem Description
The program takes in the the number of terms and finds the sum of first N Natural Numbers.

Problem Solution
1. Take in the number of natural numbers to find the sum of and store it in a separate
variable.
2. Initialize the sum variable to 0.
3. Use a while loop to find the sum of natural numbers and decrement the number for each
iteration.
4. The numbers are added to the sum variable and this continues until the the value of the
number is greater than 0.
5. Then the sum of first N natural numbers is printed.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of first N Natural Numbers. The
program output is also shown below.
n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
sum1=sum1+n
n=n-1
print("The sum of first n natural numbers is",sum1)
Program Explanation
1. User must enter the number of natural numbers to find the sum of.
2. The sum variable is initialized to 0.
3. The while loop is used to find the sum of natural numbers and the number is
decremented for each iteration.
4. The numbers are added to the sum variable and this continues till the value of the
variable is greater than 0.
5. When the value of the variable becomes lesser than 0, the total sum of N natural
numbers is printed.

Runtime Test Cases


Case 1:
Enter a number: 18
The sum of first n natural numbers is 171

Case 2:
Enter a number: 167
The sum of first n natural numbers is 14028

Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 +


….. + 1/N
This is a Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.

Problem Description
The program takes in the the number of terms and finds the sum of series: 1 + 1/2 + 1/3 +
….. + 1/N.

Problem Solution
1. Take in the number of terms to find the sum of the series for.
2. Initialize the sum variable to 0.
3. Use a for loop ranging from 1 to the number and find the sum of the series.
4. Print the sum of the series after rounding it off to two decimal places.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. +
1/N. The program output is also shown below.
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
Program Explanation
1. User must enter the number of terms to find the sum of.
2. The sum variable is initialized to 0.
3. The for loop is used to find the sum of the series and the number is incremented for each
iteration.
4. The numbers are added to the sum variable and this continues till the value of i reaches
the number of terms.
5. Then the sum of the series is printed.

Runtime Test Cases


Case 1:
Enter the number of terms: 7
The sum of series is 2.59

Case 2:
Enter the number of terms: 15
The sum of series is 3.32

Python Program to Find the Sum of the Series: 1 + x^2/2 +


x^3/3 + … x^n/n
This is a Python Program to find the sum of series: 1 + x^2/2 + x^3/3 + … x^n/n.

Problem Description
The program takes in the the number of terms and finds the sum of series: 1 + x^2/2 + x^3/3
+ … x^n/n.

Problem Solution
1. Take in the number of terms to find the sum of the series for.
2. Initialize the sum variable to 0.
3. Use a for loop ranging from 1 to the number and find the sum of the series.
4. Print the sum of the series after rounding it off to two decimal places.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. +
1/N. The program output is also shown below.
n=int(input("Enter the number of terms:"))
x=int(input("Enter the value of x:"))
sum1=1
for i in range(2,n+1):
sum1=sum1+((x**i)/i)
print("The sum of series is",round(sum1,2))
Program Explanation
1. User must enter the number of terms to find the sum of.
2. The sum variable is initialized to 0.
3. The for loop is used to find the sum of the series and the number is incremented for each
iteration.
4. The numbers are added to the sum variable and this continues till the value of i reaches
the number of terms.
5. Then the sum of the series is printed.

Runtime Test Cases


Case 1:
Enter the number of terms:3
Enter the value of x:1
The sum of series is 1.83

Case 2:
Enter the number of terms:5
Enter the value of x:2
The sum of series is 16.07

Python Program to Compute the Value of Euler’s Number e.


Use the Formula: e = 1 + 1/1! + 1/2! + …… 1/n!
This is a Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.

Problem Description
The program takes in the the number of terms and finds the sum of series: 1 + 1/2 + 1/3 +
….. + 1/N.

Problem Solution
1. Take in the number of terms to find the sum of the series for.
2. Initialize the sum variable to 1.
3. Use a for loop ranging from 1 to the number and find the sum of the series.
4. Print the sum of the series after rounding it off to two decimal places.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. +
1/N. The program output is also shown below.
import math
n=int(input("Enter the number of terms: "))
sum1=1
for i in range(1,n+1):
sum1=sum1+(1/math.factorial(i))
print("The sum of series is",round(sum1,2))
Program Explanation
1. User must enter the number of terms to find the sum of.
2. The sum variable is initialized to 1.
3. The for loop is used to find the sum of the series and the number is incremented for each
iteration.
4. The numbers are added to the sum variable and this continues till the value of i reaches
the number of terms.
5. Then the sum of the series is printed.

Runtime Test Cases


Case 1:
Enter the number of terms: 5
The sum of series is 2.72

Case 2:
Enter the number of terms: 20
The sum of series is 2.72

Python Program to Determine all Pythagorean Triplets in the


Range
This is a Python Program to determine all Pythagorean triplets till the upper limit.

Problem Description
The program takes a upper limit and determines all Pythagorean triplets till the upper limit.

Problem Solution
1. Take in the upper limit and store it in a variable.
2. Using a while loop and for loop, compute the Pythagorean triplets using the formula.
3. If the value of the c is greater than the upper limit or if any of the numbers is equal to 0,
break from the loop.
4. Print all the three numbers of the Pythagorean triplets.
5. Exit.

Program/Source Code
Here is source code of the Python Program to determine all Pythagorean triplets till the
upper limit. The program output is also shown below.
limit=int(input("Enter upper limit:"))
c=0
m=2
while(c<limit):
for n in range(1,m+1):
a=m*m-n*n
b=2*m*n
c=m*m+n*n
if(c>limit):
break
if(a==0 or b==0 or c==0):
break
print(a,b,c)
m=m+1
Program Explanation
1. User must enter the upper limit and store it in a variable.
2. The while and for loop is used to find the value of the Pythagorean triplets using the
formula.
3. If the value of a side is greater than the upper limit or if any of the side is 0, the loop is
broken out of.
4. Then the triplets are printed.

Runtime Test Cases


Case 1:
Enter upper limit:20
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20

Case 2:
Enter upper limit:35
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34

Python Program to Search the Number of Times a Particular


Number Occurs in a List
This is a Python Program to search the number of times a particular number occurs in a list.

Problem Description
The program takes a number and searches the number of times the particular number
occurs in a list.

Problem Solution
1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then take in the number to be searched in the list.
4. Use a for loop to traverse through the elements in the list and increment the count
variable.
5. Display the value of the count variable which contains the number of times a particular
number occurs in a list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to search the number of times a particular
number occurs in a list. The program output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
k=0
num=int(input("Enter the number to be counted:"))
for j in a:
if(j==num):
k=k+1
print("Number of times",num,"appears is",k)
Program Explanation
1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. User must also enter the number to be search the list for.
4. A for loop is used to traverse through the elements in the list and an if statement is used
to count a particular number.
5. The total count of a particular number in the list is printed.

Runtime Test Cases


Case 1:
Enter number of elements:4
Enter element:23
Enter element:45
Enter element:23
Enter element:67
Enter the number to be counted:23
Number of times 23 appears is 2

Case 2:
Enter number of elements:7
Enter element:12
Enter element:45
Enter element:67
Enter element:45
Enter element:67
Enter element:67
Enter element:67
Enter the number to be counted:67
Number of times 67 appears is 4

Python Program to test Collatz Conjecture for a Given Number


This is a Python program to test Collatz conjecture for a given number.

Problem Description
The Collatz conjecture is a conjecture that a particular sequence always reaches 1. The
sequence is defined as: start with a number n. The next number in the sequence is n/2 if n
is even and 3n + 1 if n is odd.

Problem Solution
1. Create a function collatz that takes an integer n as argument.
2. Create a loop that runs as long as n is greater than 1.
3. In each iteration of the loop, update the value of n.
4. If n is even, set n to n/2 and if n is odd, set it to 3n + 1.
5. Print the value of n in each iteration.

Program/Source Code
Here is the source code of a Python program to test Collatz conjecture for a given number.
The program output is shown below.
def collatz(n):
while n > 1:
print(n, end=' ')
if (n % 2):
# n is odd
n = 3*n + 1
else:
# n is even
n = n//2
print(1, end='')
n = int(input('Enter n: '))
print('Sequence: ', end='')
collatz(n)
Program Explanation
1. The user is asked to input n.
2. The sequence is printed by calling collatz on n.

Runtime Test Cases


Case 1:
Enter n: 11
Sequence: 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

Case 2:
Enter n: 5
Sequence: 5 16 8 4 2 1

Case 3:
Enter n: 1
Sequence: 1

Python Program to Count Set Bits in a Number


This is a Python program to count set bits in a number.

Problem Description
The program finds the number of ones in the binary representation of a number.

Problem Solution
1. Create a function count_set_bits that takes a number n as argument.
2. The function works by performing bitwise AND of n with n – 1 and storing the result in n
until n becomes 0.
3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n.
4. Thus the number of operations required to make n zero is the number of set bits in n.

Program/Source Code
Here is the source code of a Python program count set bits in a number. The program
output is shown below.
def count_set_bits(n):
count = 0
while n:
n &= n - 1
count += 1
return count
n = int(input('Enter n: '))
print('Number of set bits:', count_set_bits(n))
Program Explanation
1. The user is asked to input n.
2. The number of set bits is found by calling count_set_bits on n.

Runtime Test Cases


Case 1:
Enter n: 9
Number of set bits: 2

Case 2:
Enter n: 31
Number of set bits: 5

Case 3:
Enter n: 1
Number of set bits: 1

Python Program to Find Whether a Number is a Power of Two


This is a Python program to find whether a number is a power of two.

Problem Description
A number is given. The problem is to determine whether the number is a power of two.

Problem Solution
1. The function is_power_of_two is defined.
2. It takes a number n as argument and returns True if the number is a power of two.
3. If n is not positive, False is returned.
4. If n is positive, then n & (n – 1) is calculated.
5. The above expression equals n with its rightmost set bit cleared. That is, the rightmost 1
in the binary representation of n is made 0.
6. All powers of two have only one set bit in their binary representation and all numbers with
only one set bit is a power of two.
7. Thus n & (n – 1) will equal zero iff n is a power of two.
8. This is used to determine if n is a power of two if n is positive.

Program/Source Code
Here is the source code of a Python program to find whether a number is a power of two.
The program output is shown below.
def is_power_of_two(n):
"""Return True if n is a power of two."""
if n <= 0:
return False
else:
return n & (n - 1) == 0

n = int(input('Enter a number: '))

if is_power_of_two(n):
print('{} is a power of two.'.format(n))
else:
print('{} is not a power of two.'.format(n))
Program Explanation
1. The user is prompted to enter a number.
2. is_power_of_two is called on the number.
3. If the return value is True, the number is a power of two.

Runtime Test Cases


Case 1:
Enter a number: 5
5 is not a power of two.

Case 2:
Enter a number: 0
0 is not a power of two.

Case 3:
Enter a number: 8
8 is a power of two.

Python Program to Clear the Rightmost Set Bit of a Number


This is a Python program to clear the rightmost set bit of a number.

Problem Description
A number is given. We have to clear the rightmost set bit of the number. That is, we have to
flip the rightmost 1 in the binary representation of n.

Problem Solution
1. The function clear_rightmost_set_bit is defined.
2. It takes a number n as argument and returns n with its rightmost set bit cleared.
3. This is done by computing n & (n – 1) and returning it.
4. (n – 1) equals n with all the rightmost consecutive 0s and the first rightmost 1 flipped.
5. Thus n & (n – 1) equals n with its rightmost 1 cleared.
Program/Source Code
Here is the source code of a Python program to clear the rightmost set bit of a number. The
program output is shown below.
def clear_rightmost_set_bit(n):
"""Clear rightmost set bit of n and return it."""
return n & (n - 1)

n = int(input('Enter a number: '))


ans = clear_rightmost_set_bit(n)
print('n with its rightmost set bit cleared equals:', ans)
Program Explanation
1. The user is prompted to enter a number.
2. clear_rightmost_set_bit is called on the number.
3. The return value is displayed.

Runtime Test Cases


Case 1:
Enter a number: 5
n with its rightmost set bit cleared equals: 4

Case 2:
Enter a number: 0
n with its rightmost set bit cleared equals: 0

Case 3:
Enter a number: 1
n with its rightmost set bit cleared equals: 0

Python Program to Generate Gray Codes using Recursion


This is a Python program to generate all gray codes using recursion

Problem Description
The number of bits n is given. The problem is to generate the n-bit Gray code. The Gray code is an
ordering of the binary numbers such that two successive codewords differ in only one bit.

Problem Solution
1. The function get_gray_codes is defined.
2. It takes the number of bits n as argument.
3. It returns n-bit Gray code in a list.
4. The function works by first obtaining the (n – 1)-bit Gray code.
5. The first half of the n-bit Gray codewords are simply the (n – 1)-bit Gray codewords prepended by
a 0.
6. The second half of the n-bit Gray codewords are (n – 1)-bit Gray codewords listed in reverse and
prepended with a 1.
7. The 0-bit Gray code simply consists of the empty string.

Program/Source Code
Here is the source code of a Python program to generate all gray codes using recursion. The
program output is shown below.
def get_gray_codes(n):
"""Return n-bit Gray code in a list."""
if n == 0:
return ['']
first_half = get_gray_codes(n - 1)
second_half = first_half.copy()

first_half = ['0' + code for code in first_half]


second_half = ['1' + code for code in reversed(second_half)]

return first_half + second_half

n = int(input('Enter the number of bits: '))


codes = get_gray_codes(n)
print('All {}-bit Gray Codes:'.format(n))
print(codes)
Program Explanation
1. The user is prompted to enter the number of bits.
2. get_gray_codes is called on the number of bits.
3. The returned list is displayed.

Runtime Test Cases


Case 1:
Enter the number of bits: 3
All 3-bit Gray Codes:
['000', '001', '011', '010', '110', '111', '101', '100']

Case 2:
Enter the number of bits: 1
All 1-bit Gray Codes:
['0', '1']

Case 3:
Enter the number of bits: 4
All 4-bit Gray Codes:
['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', '1100', '1101',
'1111', '1110', '1010', '1011', '1001', '1000']
Python Program to Convert Gray Code to Binary
This is a Python program to convert Gray code to binary.

Problem Description
We are given a Gray codeword. We have to find the associated binary number.

Problem Solution
1. The function gray_to_binary is defined.
2. It takes the Gray codeword string as argument.
3. It returns its associated binary number as a string.
4. If g(i) is the ith bit in the Gray codeword and b(i) is the ith bit in its associated binary
number where the 0th bit is the MSB, it can be shown g(0) = b(0) and b(i) = g(i) XOR b(i –
1) for i > 0.
5. From the above, it follows that b(i) = g(i) XOR g(i – 1) XOR … XOR g(0).
6. Thus a Gray codeword g can be converted to its associated binary number by performing
(g XOR (g >> 1) XOR (g >> 2) XOR … XOR (g >> m)) where m is such that g >> (m + 1)
equals 0.

Program/Source Code
Here is the source code of a Python program to convert Gray code to binary. The program
output is shown below.
def gray_to_binary(n):
"""Convert Gray codeword to binary and return it."""
n = int(n, 2) # convert to int

mask = n
while mask != 0:
mask >>= 1
n ^= mask

# bin(n) returns n's binary representation with a '0b' prefixed


# the slice operation is to remove the prefix
return bin(n)[2:]

g = input('Enter Gray codeword: ')


b = gray_to_binary(g)
print('In binary:', b)
Program Explanation
1. The user is prompted to enter the Gray codeword.
2. gray_to_binary is called on the Gray codeword.
3. The returned string which is its associated binary number is displayed.
Runtime Test Cases
Case 1:
Enter Gray codeword: 111
In binary: 101

Case 2:
Enter Gray codeword: 1101
In binary: 1001

Case 3:
Enter Gray codeword: 10
In binary: 11

Python Program to Convert Binary to Gray Code


This is a Python program to convert binary to Gray code.

Problem Description
We are given a binary number. We have to find the associated Gray codeword.

Problem Solution
1. The function binary_to_gray is defined.
2. It takes the binary number as a string as argument.
3. It returns its associated Gray codeword as a string.
4. If b(i) is the ith bit in the binary number and g(i) is the ith bit in its associated Gray
codeword where the 0th bit is the MSB, it can be shown g(0) = b(0) and g(i) = b(i) XOR b(i –
1) for i > 0.
5. Thus a binary number b can be converted to its associated Gray codeword by performing
b XOR (b >> 1).

Program/Source Code
Here is the source code of a Python program to convert binary to Gray codeword. The
program output is shown below.
def binary_to_gray(n):
"""Convert Binary to Gray codeword and return it."""
n = int(n, 2) # convert to int
n ^= (n >> 1)

# bin(n) returns n's binary representation with a '0b' prefixed


# the slice operation is to remove the prefix
return bin(n)[2:]

g = input('Enter binary number: ')


b = binary_to_gray(g)
print('Gray codeword:', b)
Program Explanation
1. The user is prompted to enter the binary number.
2. binary_to_gray is called on the binary number.
3. The returned string which is its associated Gray codeword is displayed.

Runtime Test Cases


Case 1:
Enter binary number: 110
Gray codeword: 101

Case 2:
Enter binary number: 1001
Gray codeword: 1101

Case 3:
Enter binary number: 11
Gray codeword: 10

3. Python Programming Examples on Lists

Python Program to Read a List of Words and Return the Length


of the Longest One
This is a Python Program to read a list of words and return the length of the longest one.

Problem Description
The program takes a list of words and returns the word with the longest length.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. First assume that the first element is the word with the longest length.
4. Then using a for loop and if statement, compare the lengths of the words in the list with
the first element.
5. Store the name of the word with the longest length in a temporary variable.
6. Display the word with the longest length
7. Exit.

Program/Source Code
Here is source code of the Python Program to read a list of words and return the length of
the longest one. The program output is also shown below.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
max1=len(a[0])
temp=a[0]
for i in a:
if(len(i)>max1):
max1=len(i)
temp=i
print("The word with the longest length is:")
print(temp)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. Assuming that the first element in the list has the longest length, its length is stored in a
variable to be compared with other lengths later in the program.
5. Based on the above assumption, the first element is also copied to a temporary variable.
6. The for loop is used to traverse through the elements in the list.
7. The if statement then compares the lengths of other elements with the length of the first
element in the list.
8. If the length of a particular word is the largest, that word is copied to the temporary
variable.
9. The word with the longest length is printed.

Runtime Test Cases


Case 1:
Enter the number of elements in list:4
Enter element1:"Apple"
Enter element2:"Ball"
Enter element3:"Cat"
Enter element4:"Dinosaur"
The word with the longest length is:
Dinosaur

Case 2:
Enter the number of elements in list:3
Enter element1:"Bangalore"
Enter element2:"Mumbai"
Enter element3:"Delhi"
The word with the longest length is:
Bangalore

Python Program to Remove the ith Occurrence of the Given


Word in a List where Words can Repeat
This is a Python Program to remove the ith occurrence of the given word in list where words
can repeat.

Problem Description
The program takes a list and removes the ith occurrence of the given word in the list where
words can repeat.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements in the list.
4. Then use an if statement to check if the word to be removed matches the element and
the occurrence number and otherwise it appends the element to another list.
5. The number of repetitions along with the updated list and distinct elements is printed.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the ith occurrence of the given word
in list where words can repeat. The program output is also shown below.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
print(a)
c=[]
count=0
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
if(i==b):
count=count+1
if(count!=n):
c.append(i)
else:
c.append(i)
if(count==0):
print("Item not found ")
else:
print("The number of repetitions is: ",count)
print("Updated list is: ",c)
print("The distinct elements are: ",set(a))
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. User must enter the word and the occurrence of the word to remove.
5. A for loop is used to traverse across the elements in the list.
6. An if statement then checks whether the element matches equal to the word that must be
removed and whether the occurrence of the element matches the occurrence to be
removed.
7. If both aren’t true, the element is appended to another list.
8. If only the word matches, the count value is incremented.
9. Finally the number of repetitions along with the updated list and the distinct elements is
printed.

Runtime Test Cases


Case 1:
Enter the number of elements in list:5
Enter element1:"apple"
Enter element2:"apple"
Enter element3:"ball"
Enter element4:"ball"
Enter element5:"cat"
['apple', 'apple', 'ball', 'ball', 'cat']
Enter word to remove: "ball"
Enter the occurence to remove: 2
('The number of repitions is: ', 2)
('Updated list is: ', ['apple', 'apple', 'ball', 'cat'])
('The distinct elements are: ', set(['ball', 'apple', 'cat']))

Case 2:
Enter the number of elements in list:6
Enter element1:"A"
Enter element2:"B"
Enter element3:"A"
Enter element4:"A"
Enter element5:"C"
Enter element6:"A"
['A', 'B', 'A', 'A', 'C', 'A']
Enter word to remove: "A"
Enter the occurence to remove: 3
('The number of repitions is: ', 4)
('Updated list is: ', ['A', 'B', 'A', 'C', 'A'])
('The distinct elements are: ', set(['A', 'C', 'B']))

Python Program to Remove All Tuples in a List of Tuples with


the USN Outside the Given Range
This is a Python Program to remove all tuples in a list of tuples with the USN outside the
given range.

Problem Description
The program removes all tuples in a list of tuples with the USN outside the given range.

Problem Solution
1. Take in the lower and upper roll number from the user.
2. Then append the prefixes of the USN’s to the roll numbers.
3. Using list comprehension, find out which USN’s lie in the given range.
4. Print the list containing the tuples.
5. Exit.

Program/Source Code
Here is source code of the Python Program to remove all tuples in a list of tuples with the
USN outside the given range. The program output is also shown below.
y=[('a','12CS039'),('b','12CS320'),('c','12CS055'),('d','12CS100')]
low=int(input("Enter lower roll number (starting with 12CS):"))
up=int(input("Enter upper roll number (starting with 12CS):"))
l='12CS0'+str(low)
u='12CS'+str(up)
p=[x for x in y if x[1]>l and x[1]<u]
print(p)
Program Explanation
1. User must enter the upper and lower roll number.
2. The prefixes are then appended to the roll numbers using the ‘+’ operator to form the
USN.
3. List comprehension is then used to find the USN’s within the upper and lower range.
4. The list containing USN’s in the given range is then printed.

Runtime Test Cases


Case 1:
Enter lower roll number (starting with 12CS):50
Enter upper roll number (starting with 12CS):150
[('c', '12CS055'), ('d', '12CS100')]

Python Program to solve Maximum Subarray Problem using


Divide and Conquer
This is a Python program to solve the maximum subarray problem using divide and conquer
technique.

Problem Description
The program finds a subarray that has the maximum sum within the given array.

Problem Solution
1. Define the function find_max_subarray that takes a list as argument and two indexes,
start and end. It finds the maximum subarray in the range [start, end – 1].
2. The function find_max_subarray returns the tuple (l, r, m) where l, r are the left and right
indexes of the maximum subarray and m is its sum.
3. The base case is when the input list is just one element (i.e. start == end – 1).
4. Otherwise, the list is divided into two and find_max_subarray is called on both the halves.
5. The maximum subarray is either the maximum subarray of one of the halves or the
maximum subarray crossing the midpoint of the two halves.
6. The function find_max_crossing_subarray takes a list as argument and three indexes,
start, mid and end and finds the maximum subarray containing mid.

Program/Source Code
Here is the source code of a Python program to find the subarray with maximum sum. The
program output is shown below.
def find_max_subarray(alist, start, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end."""
# base case
if start == end - 1:
return start, end, alist[start]
else:
mid = (start + end)//2
left_start, left_end, left_max = find_max_subarray(alist, start, mid)
right_start, right_end, right_max = find_max_subarray(alist, mid, end)
cross_start, cross_end, cross_max = find_max_crossing_subarray(alist, start,
mid, end)
if (left_max > right_max and left_max > cross_max):
return left_start, left_end, left_max
elif (right_max > left_max and right_max > cross_max):
return right_start, right_end, right_max
else:
return cross_start, cross_end, cross_max

def find_max_crossing_subarray(alist, start, mid, end):


"""Returns (l, r, m) such that alist[l:r] is the maximum subarray within
alist with start <= l < mid <= r < end with sum m. The arguments start, mid,
end must satisfy start <= mid <= end."""
sum_left = float('-inf')
sum_temp = 0
cross_start = mid
for i in range(mid - 1, start - 1, -1):
sum_temp = sum_temp + alist[i]
if sum_temp > sum_left:
sum_left = sum_temp
cross_start = i

sum_right = float('-inf')
sum_temp = 0
cross_end = mid + 1
for i in range(mid, end):
sum_temp = sum_temp + alist[i]
if sum_temp > sum_right:
sum_right = sum_temp
cross_end = i + 1
return cross_start, cross_end, sum_left + sum_right

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


alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to find_max_subarray and the returned tuple is stored.
3. The start and end indexes and the sum of the maximum subarray is printed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 3 4 -2 3 -10 32 4 -11 7 -3 2
The maximum subarray starts at index 5, ends at index 6 and has sum 36.

Case 2:
Enter the list of numbers: 4 -2 3 4 1 4 -5
The maximum subarray starts at index 0, ends at index 5 and has sum 14.

Case 3:
Enter the list of numbers: 2
The maximum subarray starts at index 0, ends at index 0 and has sum 2.
Python Program to solve Maximum Subarray Problem using
Kadane’s Algorithm
This is a Python program to solve the maximum subarray problem using Kadane’s
algorithm.

Problem Description
The program finds a subarray that has the maximum sum within the given array.

Problem Solution
1. Define the function find_max_subarray that takes a list as argument and two indexes,
start and end. It finds the maximum subarray in the range [start, end – 1].
2. The function find_max_subarray returns the tuple (l, r, m) where l, r are the left and right
indexes of the maximum subarray and m is its sum.
3. The function uses a loop to keep track of the maximum subarray ending at index i. That
is, the maximum subarray that has the element at index i as its last element.
4. Then the maximum subarray will simply be the maximum of all these subarrays.
5. The maximum subarray ending at index i + 1 is given by max(list[i] + maximum sum of
subarray ending at i, list[i]).
6. The function keeps track of the maximum sum of the subarray seen so far and its left,
right indexes as the loop iterates.

Program/Source Code
Here is the source code of a Python program to find the subarray with maximum sum. The
program output is shown below.
def find_max_subarray(alist, start, end):
"""Returns (l, r, m) such that alist[l:r] is the maximum subarray in
A[start:end] with sum m. Here A[start:end] means all A[x] for start <= x <
end."""
max_ending_at_i = max_seen_so_far = alist[start]
max_left_at_i = max_left_so_far = start
# max_right_at_i is always i + 1
max_right_so_far = start + 1
for i in range(start + 1, end):
if max_ending_at_i > 0:
max_ending_at_i += alist[i]
else:
max_ending_at_i = alist[i]
max_left_at_i = i
if max_ending_at_i > max_seen_so_far:
max_seen_so_far = max_ending_at_i
max_left_so_far = max_left_at_i
max_right_so_far = i + 1
return max_left_so_far, max_right_so_far, max_seen_so_far
alist = input('Enter the list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
start, end, maximum = find_max_subarray(alist, 0, len(alist))
print('The maximum subarray starts at index {}, ends at index {}'
' and has sum {}.'.format(start, end - 1, maximum))
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to find_max_subarray and the returned tuple is stored.
3. The start and end indexes and the sum of the maximum subarray is printed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 3 -2 4 -6 7 8 -10 4
The maximum subarray starts at index 4, ends at index 5 and has sum 15.

Case 2:
Enter the list of numbers: 4 5 -2 0 -5 15
The maximum subarray starts at index 0, ends at index 5 and has sum 17.

Case 3:
Enter the list of numbers: 3
The maximum subarray starts at index 0, ends at index 0 and has sum 3.

Python Program to Find Element Occurring Odd Number of


Times in a List
This is a Python program to find the element that occurs odd number of times in a list.

Problem Description
A list is given in which all elements except one element occurs an even number of times.
The problem is to find the element that occurs an odd number of times.

Problem Solution
1. The function find_odd_occurring is defined.
2. It takes a list as argument which has only one element that occurs an odd number of
times.
3. The function returns that element.
4. It finds the element by XORing all elements in the list.
5. Since the XOR operation is commutative and associative and it satisfies p XOR p = 0 and
p XOR 0 = p, the element that occurs an odd number of times is the result.
Program/Source Code
Here is the source code of a Python program to find element that occurs odd number of
times in a list. The program output is shown below.
def find_odd_occurring(alist):
"""Return the element that occurs odd number of times in alist.

alist is a list in which all elements except one element occurs an even
number of times.
"""
ans = 0

for element in alist:


ans ^= element

return ans

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


alist = [int(i) for i in alist]
ans = find_odd_occurring(alist)
print('The element that occurs odd number of times:', ans)
Program Explanation
1. The user is prompted to enter the list.
2. find_odd_occurring is called on the list.
3. The result is then displayed.

Runtime Test Cases


Case 1:
Enter the list: 15 22 10 33 22 33 15 1 1 15 15
The element that occurs odd number of times: 10

Case 2:
Enter the list: 3
The element that occurs odd number of times: 3

Case 3:
Enter the list: 1 2 3 1 2 3 4 1 2 3 1 2 4 3 4
The element that occurs odd number of times: 4

Python Program to Find the Largest Number in a List


This is a Python Program to find the largest number in a list.

Problem Description
The program takes a list and prints the largest number in the list.

Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the largest number in a list. The program
output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Program Explanation
1. User must enter the number of elements and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. The list should then be sorted.
4. Then the last element of the list is printed which is also the largest element of the list.

Runtime Test Cases


Case 1:
Enter number of elements:3
Enter element:23
Enter element:567
Enter element:3
Largest element is: 567

Case 2:
Enter number of elements:4
Enter element:34
Enter element:56
Enter element:24
Enter element:54
Largest element is: 56

Python Program to Find the Second Largest Number in a List


This is a Python Program to find the second largest number in a list.
Problem Description
The program takes a list and prints the second largest number in the list.

Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the second last element of the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the second largest number in a list. The
program output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Second largest element is:",a[n-2])
Program Explanation
1. User must enter the number of elements and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. The list should then be sorted.
4. Then the last element of the list is printed which is also the largest element of the list.

Runtime Test Cases


Case 1:
Enter number of elements:4
Enter element:23
Enter element:56
Enter element:39
Enter element:11
Second largest element is: 39

Case 2:
Enter number of elements:3
Enter element:23
Enter element:4
Enter element:67
Second largest element is: 23
Python Program to Put Even and Odd elements in a List into
Two Different Lists
This is a Python Program to put the even and odd elements in a list into two different lists.

Problem Description
The program takes a list and puts the even and odd elements in it into two separate lists.

Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to check if
the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a different
one.
5. Display the elements in both the lists.
6. Exit.

Program/Source Code
Here is source code of the Python Program to put the even and odd elements in a list into
two different lists. The program output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)
Program Explanation
1. User must enter the number of elements and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. Another for loop is used to traverse through the elements of the list.
4. The if statement checks if the element is even or odd and appends them to separate lists.
5. Both the lists are printed.
Runtime Test Cases
Case 1:
Enter number of elements:5
Enter element:67
Enter element:43
Enter element:44
Enter element:22
Enter element:455
The even list [44, 22]
The odd list [67, 43, 455]

Case 2:
Enter number of elements:3
Enter element:23
Enter element:44
Enter element:99
The even list [44]
The odd list [23, 99]

Python Program to Merge Two Lists and Sort it


This is a Python Program to merge two lists and sort it.

Problem Description
The program takes two lists, merges them and sorts the merged list.

Problem Solution
1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for the second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to merge two lists and sort it. The program
output is also shown below.
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
Program Explanation
1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.

Runtime Test Cases


Case 1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)

Case 2:
Enter the number of elements in list 1 : 0

Enter the number of elements in list 2 : 3

Enter element 1 : 12

Enter element 2 : 12

Enter element 3 : 12

The union is :

[12]

Python Program to Sort the List According to the Second


Element in Sublist
This is a Python Program to sort the list according to the second element in the sublist.

Problem Description
The program takes a list of lists and sorts the list according to the second element in the
sublist.

Problem Solution
1. Take in a list containing sublists.
2. Using two for loops, use bubble sort to sort the sublists based on the second value of the
sublist.
3. If the second element of the first sublist is greater than the second element of the second
sublist, exchange the entire sublist.
4. Print the sorted list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to sort the list according to the second element
in the sublist. The program output is also shown below.
a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j][1]>a[j+1][1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp

print(a)
Program Explanation
1. User must enter a list containing several sublists.
2. Then bubble sort is implemented to sort the list according to the second element in the
sublist.
3. If the second element of the first sublist is greater than the second element of the second
sublist, then the entire sublist is switched.
4. This process continues till the entire list has been sorted.
5. The sorted list is then printed.

Runtime Test Cases


Case 1:
[['B', 21], ['C', 26], ['A', 34]]

Python Program to Find the Second Largest Number in a List


Using Bubble Sort
This is a Python Program to find the second largest number in a list using bubble sort.

Problem Description
The program takes a list and finds the second largest number in the list using bubble sort.

Problem Solution
1. Take in the number of elements for the list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list using bubble sort.
4. Print the second last element of the sorted list which is the second largest number.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find the second largest number in a list using
bubble sort. The program output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print('Second largest number is:',a[n-2])
Program Explanation
1. User must enter the number of elements for the list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. Then bubble sort algorithm may be used to sort the elements of the list.
4. The second last element of the sorted list is then printed which is basically the second
largest element in the list.

Runtime Test Cases


Case 1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)
Case 2:
Enter number of elements:6
Enter element:23
Enter element:45
Enter element:94
Enter element:10
Enter element:34
Enter element:95
('Second largest number is:', 94)

Python Program to Sort a List According to the Length of the


Elements
This is a Python Program to sort a list according to the length of the elements.

Problem Description
The program takes a list and sorts the list according to the length of the elements.

Problem Solution
1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list giving the length of the elements as the key.
4. Display the sorted list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to sort a list according to the length of the
elements. The program output is also shown below.
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=input("Enter element:")
a.append(b)
a.sort(key=len)
print(a)
Program Explanation
1. User must enter the number of elements for the first list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. Then the list is sorted using the length of the elements as the key.
4. The sorted list is then printed.

Runtime Test Cases


Case 1:
Enter number of elements:4
Enter element:"Apple"
Enter element:"Ball"
Enter element:"Cat"
Enter element:"Dog"
['Cat', 'Dog', 'Ball', 'Apple']

Case 2:
Enter number of elements:4
Enter element:"White"
Enter element:"Red"
Enter element:"Purple"
Enter element:"Orange"
['Red', 'White', 'Purple', 'Orange']

Python Program to Find the Union of two Lists


This is a Python Program to find the union of two lists.

Problem Description
The program takes two lists and finds the unions of the two lists.

Problem Solution
1. Define a function which accepts two lists and returns the union of them.
2. Declare two empty lists and initialise to an empty list.
3. Consider a for loop to accept values for two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the second list also.
7. Find the union of the two lists.
8. Print the union.
9. Exit.

Program/Source Code
Here is source code of the Python Program to find the union of two lists. The program
output is also shown below.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The same of 2 and 3 is done for the second list also.
5. The union function accepts two lists and returns the list which is the union of the two lists,
i.e, all the values from list 1 and 2 without redundancy.
6. The set function in the union function accepts a list and returns the list after elimination of
redundant values.
7. The lists are passed to the union function and the returned list is printed.

Runtime Test Cases


Case 1:
Enter the number of elements in list:5
Enter element1:10
Enter element2:10
Enter element3:20
Enter element4:20
Enter element5:20
Non-duplicate items:
[10, 20]

Case 2:
Enter the number of elements in list:4
Enter element1:23
Enter element2:56
Enter element3:67
Enter element4:10
('The original list is: ', [23, 56, 67, 10])
('The new list is: ', [23, 79, 146, 156])

Python Program to Find the Intersection of Two Lists


This is a Python Program to find the intersection of two lists.

Problem Description
The program takes two lists and finds the intersection of the two lists.

Problem Solution
1. Define a function which accepts two lists and returns the intersection of them.
2. Declare two empty lists and initialize them to an empty list.
3. Consider a for loop to accept values for the two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the second list also.
7. Find the intersection of the two lists.
8. Print the intersection.
9. Exit.

Program/Source Code
Here is source code of the Python Program to find the intersection of two lists. The program
output is also shown below.
def intersection(a, b):
return list(set(a) & set(b))

def main():
alist=[]
blist=[]
n1=int(input("Enter number of elements for list1:"))
n2=int(input("Enter number of elements for list2:"))
print("For list1:")
for x in range(0,n1):
element=int(input("Enter element" + str(x+1) + ":"))
alist.append(element)
print("For list2:")
for x in range(0,n2):
element=int(input("Enter element" + str(x+1) + ":"))
blist.append(element)
print("The intersection is :")
print(intersection(alist, blist))
main()
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The same of 2 and 3 is done for the second list also.
5. The intersection function accepts two lists and returns the list which is the intersection of
the two lists, i.e, all the common values from list 1 and 2.
6. The set function in the intersection function accepts a list and returns the list which
contains the common elements in both the lists.
7. The lists are passed to the intersection function and the returned list is printed.

Runtime Test Cases


Case 1:
Enter number of elements for list1:3
Enter number of elements for list2:4
For list1:
Enter element1:34
Enter element2:23
Enter element3:65
For list2:
Enter element1:33
Enter element2:65
Enter element3:23
Enter element4:86
The intersection is :
[65, 23]

Case 2:
Enter number of elements for list1:2
Enter number of elements for list2:4
For list1:
Enter element1:3
Enter element2:4
For list2:
Enter element1:12
Enter element2:34
Enter element3:4
Enter element4:6
The intersection is :
[4]

Python Program to Create a List of Tuples with the First


Element as the Number and Second Element as the Square of
the Number
This is a Python Program to create a list of tuples with the first element as the number and
the second element as the square of the number.

Problem Description
The program takes a range and creates a list of tuples within that range with the first
element as the number and the second element as the square of the number.

Problem Solution
1. Take the upper and lower range for the numbers from the user.
2. A list of tuples must be created using list comprehension where the first element is the
number within the range and the second element is the square of the number.
3. This list of tuples is then printed.
4. Exit.

Program/Source Code
Here is source code of the Python Program to create a list of tuples with the first element as
the number and the second element as the square of the number. The program output is
also shown below.
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)
Program Explanation
1. User must enter the upper and lower range for the numbers.
2. List comprehension must be used to create a list of tuples where the first number is the
number itself from the given range and the second element is a square of the first number.
3. The list of tuples which is created is printed.

Runtime Test Cases


Case 1:
Enter the lower range:1
Enter the upper range:4
[(1, 1), (2, 4), (3, 9), (4, 16)]

Case 2:
Enter the lower range:45
Enter the upper range:49
[(45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401)]

Python Program to Find all Numbers in a Range which are


Perfect Squares and Sum of all Digits in the Number is Less
than 10
This is a Python Program to create a list of of all numbers in a range which are perfect
squares and the sum of the digits of the number is less than 10.

Problem Description
The program takes a range and creates a list of all numbers in the range which are perfect
squares and the sum of the digits is less than 10.

Problem Solution
1. User must enter the upper and lower range for the numbers.
2. A list must be created using list comprehension where the element is a perfect square
within the range and the sum of the digits of the number is less than 10.
3. This list must then be printed.
4. Exit.

Program/Source Code
Here is source code of the Python Program to create a list of of all numbers in a range
which are perfect squares and the sum of the digits of the number is less than 10. The
program output is also shown below.
l=int(input("Enter lower range: "))
u=int(input("Enter upper range: "))
a=[]
a=[x for x in range(l,u+1) if (int(x**0.5))**2==x and sum(list(map(int,str(x))))<10]
print(a)
Program Explanation
1. User must enter the upper and lower range for the numbers.
2. List comprehension must be used to create a list of numbers which are perfect squares
and sum of the digits is less than 10.
3. The second part of the list comprehension first maps separate digits of the number into a
list and finds the sum of the elements in the list.
3. The list which is created is printed.

Runtime Test Cases


Case 1:
Enter lower range: 1
Enter upper range: 40
[1, 4, 9, 16, 25, 36]

Case 2:
Enter lower range: 50
Enter upper range: 100
[81, 100]
Python Program to Find the Cumulative Sum of a List where the
ith Element is the Sum of the First i+1 Elements From The
Original List
This is a Python Program to find the cumulative sum of a list where the ith element is the
sum of the first i+1 elements from the original list.

Problem Description
The program takes a list from the user and finds the cumulative sum of a list where the ith
element is the sum of the first i+1 elements from the original list.

Problem Solution
1. Declare an empty list and initialise to an empty list.
2. Consider a for loop to accept values for the list.
3. Take the number of elements in the list and store it in a variable.
4. Accept the values into the list using another for loop and insert into the list.
5. Using list comprehension and list slicing, find the cumulative sum of elements in the list.
6. Print the original list and the new list.
7. Exit.

Program/Source Code
Here is source code of the Python Program to find the cumulative sum of a list where the ith
element is the sum of the first i+1 elements from the original list. The program output is also
shown below.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b=[sum(a[0:x+1]) for x in range(0,len(a))]
print("The original list is: ",a)
print("The new list is: ",b)
Program Explanation
1. Use must declare a list and initialize it to an empty list.
2. Then a for loop is used to accept values for the list.
3. User must enter the number of elements in the list and store it in a variable.
4. Then the user must enter the values into the list using another for loop and insert into the
list.
5. List comprehension along with list slicing is used to find cumulative sum of elements in
the list
6. Then the original list and the new list is printed.

Runtime Test Cases


Case 1:
Enter the number of elements in list:5
Enter element1:1
Enter element2:2
Enter element3:3
Enter element4:4
Enter element5:5
('The original list is: ', [1, 2, 3, 4, 5])
('The new list is: ', [1, 3, 6, 10, 15])

Case 2:
Enter the number of elements in list:4
Enter element1:23
Enter element2:56
Enter element3:67
Enter element4:10
('The original list is: ', [23, 56, 67, 10])
('The new list is: ', [23, 79, 146, 156])

Python Program to Generate Random Numbers from 1 to 20


and Append Them to the List
This is a Python Program to generate random numbers from 1 to 20 and append them to
the list.

Problem Description
The program takes in the number of elements and generates random numbers from 1 to 20
and appends them to the list.

Problem Solution
1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them
appending to a list.
4. Then print the randomised list.
4. Exit.

Program/Source Code
Here is source code of the Python Program to generate random numbers from 1 to 20 and
append them to the list. The program output is also shown below.
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
Program Explanation
1. The random module is imported into the program.
2. User must enter the number of elements from the user.
3. Using a for loop, random.randint() is used to generate random numbers which are then
appended to a list.
4. The arguments given inside the random.randint() function are used to specify the range
to print the randomized numbers within.
5. Then the randomized list is printed.

Runtime Test Cases


Case 1:
Enter number of elements:3
('Randomised list is: ', [17, 4, 9])

Case 2:
Enter number of elements:7
('Randomised list is: ', [16, 5, 18, 19, 6, 7, 20])

Python program to Sort a List of Tuples in Increasing Order by


the Last Element in Each Tuple
This is a Python Program to sort a list of tuples in increasing order by the last element in
each tuple.

Problem Description
The program takes a list of tuples and sorts the list of tuples in increasing order by the last
element in each tuple.

Problem Solution
1. Take a list of tuples from the user.
2. Define a function which returns the last element of each tuple in the list of tuples.
3. Define another function with the previous function as the key and sort the list.
4. Print the sorted list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to sort a list of tuples in increasing order by the
last element in each tuple. The program output is also shown below.
def last(n):
return n[-1]

def sort(tuples):
return sorted(tuples, key=last)

a=input("Enter a list of tuples:")


print("Sorted:")
print(sort(a))
Program Explanation
1. User must enter a list of tuples.
2. The function last returns the last element of each tuple in the list of tuples.
3. The function sort returns the sorted list with the last function as its key.
4. The sorted list is then printed.

Runtime Test Cases


Case 1:
Enter a list of tuples:[(2,5),(1,2),(4,4),(2,3)]
Sorted:
[(1, 2), (2, 3), (4, 4), (2, 5)]

Case 2:
Enter a list of tuples:[(23,45),(25,44),(89,40)]
Sorted:
[(89, 40), (25, 44), (23, 45)]

Python Program to Remove the Duplicate Items from a List


This is a Python Program to remove the duplicate items from a list.

Problem Description
The program takes a lists and removes the duplicate items from the list.

Problem Solution
1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements of the list.
4. Use an if statement to check if the element is already there in the list and if it is not there,
append it to another list.
5. Print the non-duplicate items of the list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the duplicate items from a list. The
program output is also shown below.
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The for loop basically traverses through the elements of the list and the if statement
checks if the element is a duplicate or not.
5. If the element isn’t a duplicate, it is added into another list.
6. The list containing non-duplicate items is then displayed.

Runtime Test Cases


Case 1:
Enter the number of elements in list:5
Enter element1:10
Enter element2:10
Enter element3:20
Enter element4:20
Enter element5:20
Non-duplicate items:
[10, 20]

Case 2:
Enter the number of elements in list:7
Enter element1:10
Enter element2:20
Enter element3:20
Enter element4:30
Enter element5:40
Enter element6:40
Enter element7:50
Non-duplicate items:
[10, 20, 30, 40, 50]

4. Python Programming Examples on Strings

Python Program to Replace all Occurrences of ‘a’ with $ in a


String
This is a Python Program to replace all occurrences of ‘a’ with ‘$’ in a string.

Problem Description
The program takes a string and replaces all occurrences of ‘a’ with ‘$’.

Problem Solution
1. Take a string and store it in a variable.
2. Using the replace function, replace all occurrences of ‘a’ and ‘A’ with ‘$’ and store it back
in the variable.
3. Print the modified string.
4. Exit.

Program/Source Code
Here is source code of the Python Program to replace all occurrences of ‘a’ with ‘$’ in a
string. The program output is also shown below.
string=raw_input("Enter string:")
string=string.replace('a','$')
string=string.replace('A','$')
print("Modified string:")
print(string)
Program Explanation
1. User must enter the string and store it in a variable.
2. The replace function replaces all occurrences of ‘a’ and ‘A’ with ‘$’ and store it back in the
variable.
3. The modified string is printed
Runtime Test Cases
Case 1:
Enter string:Apple
Modified string:
$pple

Case 2:
Enter string:Asia
Modified string:
$si$

Python Program to Remove the nth Index Character from a


Non-Empty String
This is a Python Program to remove the nth index character from a non-empty string.

Problem Description
The program takes a string and removes the nth index character from the non-empty string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Take the index of the character to remove.
3. Pass the string and the index as arguments to a function named remove.
4. In the function, the string should then be split into two halves before the index character
and after the index character.
5. These two halves should then be merged together.
6. Print the modified string.
7. Exit.

Program/Source Code
Here is source code of the Python Program to remove the nth index character from a non-
empty string. The program output is also shown below.
def remove(string, n):
first = string[:n]
last = string[n+1:]
return first + last
string=raw_input("Enter the sring:")
n=int(input("Enter the index of the character to remove:"))
print("Modified string:")
print(remove(string, n))
Program Explanation
1. User must enter a string and store it in a variable.
2. User must also enter the index of the character to remove.
3. The string and the index of the character to remove are passed as arguments to the
remove function.
4. In the function, the string is split into two halves before the index character and after the
index character.
5. The first half and the last half is then merged together using the ‘+’ operator.
6. The modified string is printed.

Runtime Test Cases


Case 1:
Enter the sring:Hello
Enter the index of the character to remove:3
Modified string:
Helo

Case 2:
Enter the sring:Checking
Enter the index of the character to remove:4
Modified string:
Checing

Python Program to Detect if Two Strings are Anagrams


This is a Python Program to detect if two strings are anagrams.

Problem Description
The program takes two strings and checks if the two strings are anagrams.

Problem Solution
1. Take two strings from the user and store them in separate variables.
2. Then use sorted() to sort both the strings into lists.
3. Compare the sorted lists and check if they are equal.
4. Print the final result.
5. Exit.

Program/Source Code
Here is source code of the Python Program to detect if two strings are anagrams. The
program output is also shown below.
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
Program Explanation
1. User must enter both the strings and store them in separate variables.
2. The characters of both the strings are sorted into separate lists.
3. They are then checked whether they are equal or not using an if statement.
4. If they are equal, they are anagrams as the characters are simply jumbled in anagrams.
5. If they aren’t equal, the strings aren’t anagrams.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter first string:anagram
Enter second string:nagaram
The strings are anagrams.

Case 2:
Enter first string:hello
Enter second string:world
The strings aren't anagrams.

Python Program to Form a New String where the First


Character and the Last Character have been Exchanged
This is a Python Program to form a string where the first character and the last character
have been exchanged.

Problem Description
The program takes a string and swaps the first character and the last character of the string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, split the string.
4. Then add the last character to the middle part of the string which is in turn added to the
first character.
5. Print the modified string.
6. Exit.
Program/Source Code
Here is source code of the Python Program to form a string where the first character and
the last character have been exchanged. The program output is also shown below.
def change(string):
return string[-1:] + string[1:-1] + string[:1]
string=raw_input("Enter string:")
print("Modified string:")
print(change(string))
Program Explanation
1. User must enter a string and store it in a variable.
2. This string is passed as an argument to a function.
3. In the function, using string slicing, the string is first split into three parts which is the last
character, middle part and the first character of the string.
4. These three parts are then concatenated using the ‘+’ operator.
5. The modified string is then printed.

Runtime Test Cases


Case 1:
Enter string:abcd
Modified string:
dbca

Case 2:
Enter string:hello world
Modified string:
dello worlh

Python Program to Count the Number of Vowels in a String


This is a Python Program to count the number of vowels in a string.

Problem Description
The program takes a string and counts the number of vowels in a string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string.
4. Use an if statement to check if the character is a vowel or not and increment the count
variable if it is a vowel.
5. Print the total number of vowels in the string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the nth index character from a non-
empty string. The program output is also shown below.
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I'
or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. An if statement checks if the character is a vowel or not.
5. The count is incremented each time a vowel is encountered.
6. The total count of vowels in the string is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world
Number of vowels are:
3

Case 2:
Enter string:WELCOME
Number of vowels are:
3

Python Program to Take in a String and Replace Every Blank


Space with Hyphen
This is a Python Program to take a string and replace every blank space with a hyphen.

Problem Description
The program takes a string and replaces every blank space with a hyphen.

Problem Solution
1. Take a string and store it in a variable.
2. Using the replace function, replace all occurrences of ‘ ‘ with ‘-‘ and store it back in the
variable.
3. Print the modified string.
4. Exit.

Program/Source Code
Here is source code of the Python Program to take a string and replace every blank space
with a hyphen. The program output is also shown below.
string=raw_input("Enter string:")
string=string.replace(' ','-')
print("Modified string:")
print(string)
Program Explanation
1. User must enter the string and store it in a variable.
2. The replace function replaces all occurrences of ‘ ‘ with ‘-‘ and store it back in the same
variable.
3. The modified string is printed.

Runtime Test Cases


Case 1:
Enter string:hello world
Modified string:
hello-world

Case 2:
Enter string:apple orange banana
Modified string:
apple-orange-banana

Python Program to Calculate the Length of a String Without


Using a Library Function
This is a Python Program to calculate the length of a string without using library functions.

Problem Description
The program takes a string and calculates the length of the string without using library
functions.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the count
variable each time.
4. Print the total count of the variable.
5. Exit.

Program/Source Code
Here is source code of the Python Program to calculate the length of a string without using
library functions. The program output is also shown below.
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a character is encountered.
5. The total count of characters in the string which is the length of the string is printed.

Runtime Test Cases


Case 1:
Enter string:Hello
Length of the string is:
5

Case 2:
Enter string:Bangalore
Length of the string is:
9

Python Program to Remove the Characters of Odd Index


Values in a String
This is a Python Program to remove the characters of odd index values in a string.

Problem Description
The program takes a string and removes the characters of odd index values in the string.
Problem Solution
1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, initialize a variable to an empty character.
4. Use a for loop to traverse through the string.
5. Use an if statement to check if the index of the string is odd or even.
6. If the index is odd, append the no character to the string.
7. Then print the modified string.
8. Exit.

Program/Source Code
Here is source code of the Python Program to remove the characters of odd index values in
a string. The program output is also shown below.
def modify(string):
final = ""
for i in range(len(string)):
if i % 2 == 0:
final = final + string[i]
return final
string=raw_input("Enter string:")
print("Modified string is:")
print(modify(string))
Program Explanation
1. User must enter a string and store it in a variable.
2. This string is passed as an argument to a function.
3. In the function, a variable is initialized with an empty character.
4. A for loop is used to traverse through the string.
5. An if statement checks if the index of the string is odd or even.
6. If the index is odd, the empty character variable is appended to the string thus indirectly
removing the character.
7. Finally the modified string is printed.

Runtime Test Cases


Case 1:
Enter string:hello
Modified string is:
hlo

Case 2:
Enter string:checking
Modified string is:
cekn
Python Program to Calculate the Number of Words and the
Number of Characters Present in a String
This is a Python Program to calculate the number of words and characters present in a
string.

Problem Description
The program takes a string and calculates the number of words and characters present in
the string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize the character count variable to 0 and the word count variable to 1.
3. Use a for loop to traverse through the characters in the string and increment the
character count variable each time.
4. Increment the word count variable only if a space is encountered.
5. Print the total count of the characters and words in the string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to calculate the number of words and
characters present in a string. The program output is also shown below.
string=raw_input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)
Program Explanation
1. User must enter a string and store it in a variable.
2. The character count variable is initialized to zero and the word count variable is initialized
to 1 (to account for the first word).
3. The for loop is used to traverse through the characters in the string.
4. The character count is incremented each time a character is encountered and the word
count is incremented only when a space is encountered.
6. The total count of characters and the words in the string is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world
Number of words in the string:
2
Number of characters in the string:
11

Case 2:
Enter string:I love python
Number of words in the string:
3
Number of characters in the string:
13

Python Program to Take in Two Strings and Display the Larger


String without Using Built-in Functions
This is a Python Program to take in two strings and display the larger string without using
built-in functions.

Problem Description
The program takes in two strings and display the larger string without using built-in function.

Problem Solution
1. Take in two strings from the user and store it in separate variables.
2. Initialize the two count variables to zero.
3. Use a for loop to traverse through the characters in the string and increment the count
variables each time a character is encountered.
4. Compare the count variables of both the strings.
5. Print the larger string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to take in two strings and display the larger
string without using built-in functions. The program output is also shown below.
string1=raw_input("Enter first string:")
string2=raw_input("Enter second string:")
count1=0
count2=0
for i in string1:
count1=count1+1
for j in string2:
count2=count2+1
if(count1<count2):
print("Larger string is:")
print(string2)
elif(count1==count2):
print("Both strings are equal.")
else:
print("Larger string is:")
print(string1)
Program Explanation
1. User must enter two strings and store it in separate variables.
2. The count variables are initialized to zero.
3. The for loop is used to traverse through the characters in the strings.
4. The count variables are incremented each time a character is encountered.
6. The count variables are then compared and the larger string is printed.

Runtime Test Cases


Case 1:
Enter first string:Bangalore
Enter second string:Delhi
Larger string is:
Bangalore

Case 2:
Enter first string:Ball
Enter second string:Apple
Larger string is:
Apple

Python Program to Count Number of Lowercase Characters in


a String
This is a Python Program to count number of lowercase characters in a string.

Problem Description
The program takes a string and counts number of lowercase characters in a string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the count
variable each time a lowercase character is encountered.
4. Print the total count of the variable.
5. Exit.

Program/Source Code
Here is source code of the Python Program to count number of lowercase characters in a
string. The program output is also shown below.
string=raw_input("Enter string:")
count=0
for i in string:
if(i.islower()):
count=count+1
print("The number of lowercase characters is:")
print(count)
Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a lowercase character is encountered.
5. The total count of lowercase characters in the string is printed.

Runtime Test Cases


Case 1:
Enter string:Hello
The number of lowercase characters is:
4

Case 2:
Enter string:AbCd
The number of lowercase characters is:
2

Python Program to Check if a String is a Palindrome or Not


This is a Python Program to check if a string is a palindrome or not.

Problem Description
The program takes a string and checks if a string is a palindrome or not.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Reverse the string using string slicing and compare it back to the original string.
3. Print the final result
4. Exit.

Program/Source Code
Here is source code of the Python Program to check if a string is a palindrome or not. The
program output is also shown below.
string=raw_input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")
Program Explanation
1. User must enter a string and store it in a variable.
2. The string is reversed using string slicing and it is compared back to the non-reversed
string.
3. If they both are equal, the strings are palindromes.
4. If they aren’t equal, the strings aren’t palindromes.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter string:malayalam
The string is a palindrome

Case 2:
Enter string:hello
The string isn't a palindrome

Python Program to Calculate the Number of Upper Case Letters


and Lower Case Letters in a String
This is a Python Program to count the number of lowercase letters and uppercase letters in
a string.

Problem Description
The program takes a string and counts the number of lowercase letters and uppercase
letters in the string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize the two count variables to 0.
3. Use a for loop to traverse through the characters in the string and increment the first
count variable each time a lowercase character is encountered and increment the second
count variable each time a uppercase character is encountered.
4. Print the total count of both the variables.
5. Exit.

Program/Source Code
Here is source code of the Python Program to count the number of lowercase characters
and uppercase characters in a string. The program output is also shown below.
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.islower()):
count1=count1+1
elif(i.isupper()):
count2=count2+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)

Python Program to Check if a String is a Pangram or Not


This is a Python Program to check if a string is a pangram or not.

Problem Description
The program takes a string and checks if it is a pangram or not.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Pass the string as an argument to a function.
3. In the function, form two sets- one of all lower case letters and one of the letters in the
string.
4. Subtract these both sets and check if it is equal to an empty set.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check if a string is a pangram or not. The
program output is also shown below.
from string import ascii_lowercase as asc_lower
def check(s):
return set(asc_lower) - set(s.lower()) == set([])
strng=raw_input("Enter string:")
if(check(strng)==True):
print("The string is a pangram")
else:
print("The string isn't a pangram")
Program Explanation
1. User must enter a string and store it in a variable.
2. The string is passed as an argument to a function.
3. In the function, two sets are formed- one for all lower case letters and one for the letters
in the string.
4. The two sets are subtracted and if it is an empty set, the string is a pangram.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter string:The quick brown fox jumps over the lazy dog
The string is a pangram

Case 2:
Enter string:Hello world
The string isn't a pangram

Python Program to Accept a Hyphen Separated Sequence of


Words as Input and Print the Words in a Hyphen-Separated
Sequence after Sorting them Alphabetically
This is a Python Program to accept a hyphen separated sequence of words as input and
print the words in a hyphen-separated sequence after sorting them alphabetically.

Problem Description
The program accepts a hyphen separated sequence of words as input and print the words
in a hyphen-separated sequence after sorting them alphabetically.

Problem Solution
1. Take a hyphen separated sequence of words from the user.
2. Split the words in the input with hyphen as reference and store the words in a list.
3. Sort the words in the list.
4. Join the words in the list with hyphen between them and print the sorted sequence.
5. Exit.

Program/Source Code
Here is source code of the Python Program to accept a hyphen separated sequence of
words as input and print the words in a hyphen-separated sequence after sorting them
alphabetically. The program output is also shown below.
print("Enter a hyphen separated sequence of words:")
lst=[n for n in raw_input().split('-')]
lst.sort()
print("Sorted:")
print('-'.join(lst))
Program Explanation
1. User must enter a hyphen separated sequence of words as the input.
2. The sequence is split with the hyphen as the key and the words are stored in a list.
3. The words in the list are sorted alphabetically using the sort() function.
4. The words in the list are then joined using hyphen as the reference.
6. The sorted sequence of words is then printed.

Runtime Test Cases


Case 1:
red-green-blue-yellow
Sorted:
blue-green-red-yellow

Case 2:
Enter a hyphen separated sequence of words:
Bangalore-hyderabad-delhi
Sorted:
Bangalore-delhi-hyderabad

Python Program to Calculate the Number of Digits and Letters


in a String
This is a Python Program to calculate the number of digits and letters in a string.

Problem Description
The program takes a string and calculates the number of digits and letters in a string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize the two count variables to 0.
3. Use a for loop to traverse through the characters in the string and increment the first
count variable each time a digit is encountered and increment the second count variable
each time a character is encountered.
4. Print the total count of both the variables.
5. Exit.

Program/Source Code
Here is source code of the Python Program to calculate the number of digits and letters in a
string. The program output is also shown below.
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
Program Explanation
1. User must enter a string and store it in a variable.
2. Both the count variables are initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The first count variable is incremented each time a digit is encountered and the second
count variable is incremented each time a character is encountered.
5. The total count of digits and characters in the string are printed.

Runtime Test Cases


Case 1:
Enter string:Hello123
The number of digits is:
3
The number of characters is:
8

Case 2:
Enter string:Abc12
The number of digits is:
2
The number of characters is:
5
Python Program to Form a New String Made of the First 2 and
Last 2 characters From a Given String
This is a Python Program to form a new string made of the first 2 characters and last 2
characters from a given string.

Problem Description
The program takes a string and forms a new string made of the first 2 characters and last 2
characters from a given string.

Problem Solution
1. Take a string from the user and store it in a variable.
2. Initialize a count variable to 0.
3. Use a for loop to traverse through the characters in the string and increment the count
variable each time.
4. Form the new string using string slicing.
5. Print the newly formed string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to form a new string made of the first 2
characters and last 2 characters from a given string. The program output is also shown
below.
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
new=string[0:2]+string[count-2:count]
print("Newly formed string is:")
print(new)
Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to zero.
3. The for loop is used to traverse through the characters in the string.
4. The count is incremented each time a character is encountered.
5. The new string is formed by using string slicing and the first two letters and the last two
letters of the string are concatenated using the ‘+’ operator.
6. The newly formed string is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world
Newly formed string is:
Held

Case 2:
Enter string:Checking
Newly formed string is:
Chng

Python Program to Count the Occurrences of Each Word in a


Given String Sentence
This is a Python Program to count the occurrences of each word in a given string sentence.

Problem Description
The program takes a string and counts the occurrence of each word in the given sentence.

Problem Solution
1. Take a string and a word from the user and store it in separate variables.
2. Initialize a count variable to 0.
3. Split the string using space as the reference and store the words in a list.
4. Use a for loop to traverse through the words in the list and use an if statement to check if
the word in the list matches the word given by the user and increment the count.
5. Print the total count of the variable.
6. Exit.

Program/Source Code
Here is source code of the Python Program to calculate the length of a string without using
library functions. The program output is also shown below.
string=raw_input("Enter string:")
word=raw_input("Enter word:")
a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print("Count of the word is:")
print(count)
Program Explanation
1. User must enter a string and a word and store it in separate variables.
2. The count variable is initialized to zero.
3. The string is split into words using space as the reference and stored in a list.
4. The for loop is used to traverse through the words in the list.
5. The count is incremented each time the word in the list is equal to the word given by the
user.
6. The total count of the word is printed.

Runtime Test Cases


Case 1:
Enter string:hello world
Enter word:hello
Count of the word is:
1

Case 2:
Enter string:orange blue red orange
Enter word:orange
Count of the word is:
2

Python Program to Check if a Substring is Present in a Given


String
This is a Python Program to check if a substring is present in a given string.

Problem Description
The program takes a string and checks if a substring is present in the given string.

Problem Solution
1. Take a string and a substring from the user and store it in separate variables.
2. Check if the substring is present in the string using find() in-built function.
3. Print the final result.
4. Exit.

Program/Source Code
Here is source code of the Python Program to calculate the length of a string without using
library functions. The program output is also shown below.
string=raw_input("Enter string:")
sub_str=raw_input("Enter word:")
if(string.find(sub_str)==-1):
print("Substring not found in string!")
else:
print("Substring in string!")
Program Explanation
1. User must enter a string and a substring from the user and store it in separate variables.
2. It is then checked if the substring is present in the string using find() in-built function.
3. An if statement is used to make the decision and the final result is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world
Enter word:world
Substring in string!

Case 2:
Enter string:Hello world
Enter word:apple
Substring not found in string!

Python Program to Print All Permutations of a String in


Lexicographic Order without Recursion
This is a Python program to print all permutations of a string in lexicographic order without
using recursion.

Problem Description
The problem is the display all permutations of a string in lexicographic or dictionary order.

Problem Solution
1. The algorithm work by first creating a loop that will run n! times where n is the length of
the string.
2. Each iteration of the loop prints the string and finds its next permutation to be printed in
the next iteration.
3. The next higher permutation is found as follows.
4. If our sequence is called seq, then we find the smallest index p such that all elements in
seq[p…end] are in descending order.
5. If seq[p…end] is the entire sequence, i.e. p == 0, then seq is the highest permutation. So
we simply reverse the entire string to get the smallest permutation which we consider as the
next permutation.
6. If p > 0, then we reverse seq[p…end].
7. Then we look for the smallest element in seq[p…end] that is greater than seq[p – 1] and
swap its position with seq[p – 1].
8. This is then the next permutation.

Program/Source Code
Here is the source code of a Python program to print all permutations of a string in
lexicographic order without recursion. The program output is shown below.
from math import factorial

def print_permutations_lexicographic_order(s):
"""Print all permutations of string s in lexicographic order."""
seq = list(s)

# there are going to be n! permutations where n = len(seq)


for _ in range(factorial(len(seq))):
# print permutation
print(''.join(seq))

# find p such that seq[p:] is the largest sequence with elements in


# descending lexicographic order
p = len(seq) - 1
while p > 0 and seq[p - 1] > seq[p]:
p -= 1

# reverse seq[p:]
seq[p:] = reversed(seq[p:])

if p > 0:
# find q such that seq[q] is the smallest element in seq[p:] such that
# seq[q] > seq[p - 1]
q = p
while seq[p - 1] > seq[q]:
q += 1

# swap seq[p - 1] and seq[q]


seq[p - 1], seq[q] = seq[q], seq[p - 1]

s = input('Enter the string: ')


print_permutations_lexicographic_order(s)
Program Explanation
1. The user is asked to enter a string.
2. The function print_permutations_lexicographic_order is called on the string.
3. The function then prints all permutations of the string in lexicographic order.

Runtime Test Cases


Case 1:
Enter the string: pig
pig
gip
gpi
igp
ipg
pgi

Case 2:
Enter the string: abcd
abcd
abdc
acbd
acdb
adbc
adcb
bacd
badc
bcad
bcda
bdac
bdca
cabd
cadb
cbad
cbda
cdab
cdba
dabc
dacb
dbac
dbca
dcab
dcba

Case 3:
Enter the string: a
a

Python Program to Print All Permutations of a String in


Lexicographic Order using Recursion
This is a Python program to print all permutations of a string in lexicographic order using
recursion.

Problem Description
The problem is the display all permutations of a string in lexicographic or dictionary order.

Problem Solution
1. The algorithm work by creating a recursive function get_next_permutation that returns the
next higher permutation of a sequence seq. If seq is the highest permutation then it returns
None.
2. The function get_next_permutation first tests the case where seq is the empty list. If it is,
it returns None.
3. Then it calls get_next_permutation on seq[1:]. Let the return value be nxt.
4. If nxt is not None, then the next higher permutation of seq is simply the concatenation of
[seq[0]] and nxt.
5. If nxt is None, then seq[1:] is in descending order and is the highest permutation.
6. To find the next higher permutation, we first reverse seq[1:].
7. Then we look for the smallest element in seq[1…end] that is greater than seq[0] and
swap its position with seq[0].
8. This is the next higher permutation which is then returned.
9. If we cannot find an element greater than seq[0] then the entire sequence is in
descending order and so seq is the highest permutation. In this case, None is returned.

Program/Source Code
Here is the source code of a Python program to print all permutations of a string in
lexicographic order using recursion. The program output is shown below.
from math import factorial

def print_permutations_lexicographic_order(s):
"""Print all permutations of string s in lexicographic order."""
seq = list(s)
for _ in range(factorial(len(seq))):
print(''.join(seq))
nxt = get_next_permutation(seq)
# if seq is the highest permutation
if nxt is None:
# then reverse it
seq.reverse()
else:
seq = nxt

def get_next_permutation(seq):
"""Return next greater lexicographic permutation. Return None if cannot.

This will return the next greater permutation of seq in lexicographic


order. If seq is the highest permutation then this will return None.

seq is a list.
"""
if len(seq) == 0:
return None

nxt = get_next_permutation(seq[1:])

# if seq[1:] is the highest permutation


if nxt is None:
# reverse seq[1:], so that seq[1:] now is in ascending order
seq[1:] = reversed(seq[1:])

# find q such that seq[q] is the smallest element in seq[1:] such that
# seq[q] > seq[0]
q = 1
while q < len(seq) and seq[0] > seq[q]:
q += 1

# if cannot find q, then seq is the highest permutation


if q == len(seq):
return None

# swap seq[0] and seq[q]


seq[0], seq[q] = seq[q], seq[0]

return seq
else:
return [seq[0]] + nxt

s = input('Enter the string: ')


print_permutations_lexicographic_order(s)
Program Explanation
1. The user is asked to enter a string.
2. The function print_permutations_lexicographic_order is called on the string.
3. The function then prints all permutations of the string in order.

Runtime Test Cases


Case 1:
cow
cwo
ocw
owc
wco
woc

Case 2:
Enter the string: dogs
dogs
dosg
dsgo
dsog
gdos
gdso
gods
gosd
gsdo
gsod
odgs
odsg
ogds
ogsd
osdg
osgd
sdgo
sdog
sgdo
sgod
sodg
sogd
ogds
ogsd

Case 3:
Enter the string: a
a

5. Python Programming Examples on Dictionary

Python Program to Add a Key-Value Pair to the Dictionary


This is a Python Program to add a key-value pair to a dictionary.

Problem Description
The program takes a key-value pair and adds it to the dictionary.

Problem Solution
1. Take a key-value pair from the user and store it in separate variables.
2. Declare a dictionary and initialize it to an empty dictionary.
3. Use the update() function to add the key-value pair to the dictionary.
4. Print the final dictionary.
5. Exit.

Program/Source Code
Here is source code of the Python Program to add a key-value pair to a dictionary. The
program output is also shown below.
key=int(input("Enter the key (int) to be added:"))
value=int(input("Enter the value for the key to be added:"))
d={}
d.update({key:value})
print("Updated dictionary is:")
print(d)
Program Explanation
1. User must enter a key-value pair and store it in separate variables.
2. A dictionary is declared and initialized to an empty dictionary.
3. The update() function is used to add the key-value pair to the dictionary.
4. The final dictionary is printed.

Runtime Test Cases


Case 1:
Enter the key (int) to be added:12
Enter the value for the key to be added:34
Updated dictionary is:
{12: 34}

Case 2:
Enter the key (int) to be added:34
Enter the value for the key to be added:29
Updated dictionary is:
{34: 29}

Python Program to Concatenate Two Dictionaries Into One


This is a Python Program to concatenate two dictionaries into one dictionary.

Problem Description
The program takes two dictionaries and concatenates them into one dictionary.

Problem Solution
1. Declare and initialize two dictionaries with some key-value pairs
2. Use the update() function to add the key-value pair from the second dictionary to the first
dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code
Here is source code of the Python Program to add a key-value pair to a dictionary. The
program output is also shown below.
d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)
Program Explanation
1. User must enter declare and initialize two dictionaries with a few key-value pairs and
store it in separate variables.
2. The update() function is used to add the key-value pair from the second to the first
dictionary.
3. The final updated dictionary is printed.

Runtime Test Cases


Case 1:
Concatenated dictionary is:
{'A': 1, 'C': 3, 'B': 2}

Python Program to Check if a Given Key Exists in a Dictionary


or Not
This is a Python Program to check if a given key exists in a dictionary or not.

Problem Description
The program takes a dictionary and checks if a given key exists in a dictionary or not.

Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the dictionary
using the dictionary.keys() method.
4. If it is present, print the value of the key.
5. If it isn’t present, display that the key isn’t present in the dictionary.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check if a given key exists in a dictionary or
not. The program output is also shown below.
d={'A':1,'B':2,'C':3}
key=raw_input("Enter key to check:")
if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else:
print("Key isn't present!")
Program Explanation
1. User must enter the key to be checked and store it in a variable.
2. An if statement and the in operator is used check if the key is present in the list
containing the keys of the dictionary.
3. If it is present, the value of the key is printed.
4. If it isn’t present, “Key isn’t present!” is printed.
5. Exit.

Runtime Test Cases


Case 1:
Enter key to check:A
Key is present and value of the key is:
1

Case 2:
Enter key to check:F
Key isn't present!

Python Program to Generate a Dictionary that Contains


Numbers (between 1 and n) in the Form (x,x*x).
This is a Python Program to generate a dictionary that contains numbers (between 1 and n) in the
form (x,x*x).

Problem Description
The program takes a number from the user and generates a dictionary that contains numbers
(between 1 and n) in the form (x,x*x).

Problem Solution
1. Take a number from the user and store it in a separate variable.
2. Declare a dictionary and using dictionary comprehension initialize it to values keeping the number
between 1 to n as the key and the square of the number as their values.
3. Print the final dictionary.
4. Exit.

Program/Source Code
Here is source code of the Python Program to generate a dictionary that contains numbers (between
1 and n) in the form (x,x*x). The program output is also shown below.
n=int(input("Enter a number:"))
d={x:x*x for x in range(1,n+1)}
print(d)
Program Explanation
1. User must enter a number and store it in a variable.
2. A dictionary is declared and initialized to values using dictionary comprehension.
3. The numbers between 1 to n are kept as keys while the squares of the numbers are made their
values.
4. The final dictionary is printed.

Runtime Test Cases


Case 1:
Enter a number:5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Case 2:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12:
144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361}

Python Program to Sum All the Items in a Dictionary


This is a Python Program to find the sum all the items in a dictionary.

Problem Description
The program takes a dictionary and prints the sum of all the items in the dictionary.

Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Find the sum of all the values in the dictionary.
3. Print the total sum.
4. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum all the items in a dictionary. The
program output is also shown below.
d={'A':100,'B':540,'C':239}
print("Total sum of values in the dictionary:")
print(sum(d.values()))
Program Explanation
1. The sum() function is used to find the sum of all the values in the dictionary.
2. The total sum of all the values in the dictionary is printed.
3. Exit.

Runtime Test Cases


Case 1:
Total sum of values in the dictionary:
879
Python Program to Multiply All the Items in a Dictionary
This is a Python Program to multiply all the items in a dictionary.

Problem Description
The program takes a dictionary and multiplies all the items in the dictionary.

Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Initialize a variable that should contain the total multiplied value to 1.
3. Use the for loop to traverse through the values of the dictionary.
4. Then multiply all the values in the dictionary against each other.
5. Print the total multiplied value.
6. Exit.

Program/Source Code
Here is source code of the Python Program to multiply all the items in a dictionary. The
program output is also shown below.
d={'A':10,'B':10,'C':239}
tot=1
for i in d:
tot=tot*d[i]
print(tot)
Program Explanation
1. A dictionary is declared and initialized to have some key-value pairs.
2. The total variable is initialized to 1.
3. The for loop is used to traverse through the values of the dictionary.
4. Then all the values in the dictionary are multiplied against each other.
5. The total multiplied value is printed.

Runtime Test Cases


Case 1:
23900

Python Program to Remove the Given Key from a Dictionary


This is a Python Program to remove the given key from a dictionary.

Problem Description
The program takes a dictionary and removes a given key from the dictionary.
Problem Solution
1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the dictionary.
4. If it is present, delete the key-value pair.
5. If it isn’t present, print that the key isn’t found and exit the program.
6. Exit.

Program/Source Code
Here is source code of the Python Program to remove the given key from a dictionary. The
program output is also shown below.
d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
Program Explanation
1. User must enter the key to be checked and store it in a variable.
2. An if statement and the in operator is used check if the key is present in the dictionary.
3. If it is present, the key-value pair is deleted.
4. If it isn’t present, “Key not found!” is printed and the program is exited.

Runtime Test Cases


Case 1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}

Case 2:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!

Python Program to Form a Dictionary from an Object of a Class


This is a Python Program to form a dictionary from an object of a class.

Problem Description
The program forms a dictionary from an object of a class.

Problem Solution
1. Declare a class named A.
2. Initialize the keys with their values in the __init__ method of the class and form a
dictionary using the __dict__ method.
3. Print the dictionary formed from the object of the class.
4. Exit.

Program/Source Code
Here is source code of the Python Program to form a dictionary from an object of a class.
The program output is also shown below.
class A(object):
def __init__(self):
self.A=1
self.B=2
obj=A()
print(obj.__dict__)
Program Explanation
1. A class named A is declared.
2. The keys are initialized with their values in the __init__ method of the class.
3. The dictionary is formed using the object of the class and by using the __dict__ method.
4. The dictionary formed from the object of the class is printed.

Runtime Test Cases


Case 1:
{'A': 1, 'B': 2}

Python Program to Map Two Lists into a Dictionary


This is a Python Program to map two lists into a dictionary.

Problem Description
The program takes two lists and maps two lists into a dictionary.

Problem Solution
1. Declare two empty lists and initialize them to an empty list.
3. Consider a for loop to accept values for the two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the values list also.
7. Zip the two lists and use dict() to convert it into a dictionary.
8. Print the dictionary.
9. Exit.

Program/Source Code
Here is source code of the Python Program to map two lists into a dictionary. The program
output is also shown below.
keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The same of 2 and 3 is done for the second values list also.
5. The two lists are merged together using the zip() function.
6. The zipped lists are then merged to form a dictionary using dict().
7. The dictionary formed from the two lists is then printed.

Runtime Test Cases


Case 1:
Enter number of elements for dictionary:3
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
For values:
Enter element1:1
Enter element2:4
Enter element3:9
The dictionary is:
{1: 1, 2: 4, 3: 9}

Case 2:
Enter number of elements for dictionary:2
For keys:
Enter element1:23
Enter element2:46
For values:
Enter element1:69
Enter element2:138
The dictionary is:
{46: 138, 23: 69}

Python Program to Count the Frequency of Words Appearing in


a String Using a Dictionary
This is a Python Program to count the frequency of words appearing in a string using a
dictionary.

Problem Description
The program takes a string and counts the frequency of words appearing in that string using
a dictionary.

Problem Solution
1. Enter a string and store it in a variable.
2. Declare a list variable and initialize it to an empty list.
3. Split the string into words and store it in the list.
4. Count the frequency of each word and store it in another list.
5. Using the zip() function, merge the lists containing the words and the word counts into a
dictionary.
3. Print the final dictionary.
4. Exit.

Program/Source Code
Here is source code of the Python Program to count the frequency of words appearing in a
string using a dictionary. The program output is also shown below.
test_string=raw_input("Enter string:")
l=[]
l=test_string.split()
wordfreq=[l.count(p) for p in l]
print(dict(zip(l,wordfreq)))
Program Explanation
1. User must enter a string and store it in a variable.
2. A list variable is declared and initialized to an empty list.
3. The string is split into words using a space as the reference and stored in the list.
4. The frequency of each word in the list is counted using list comprehension and the
count() function.
5. The final dictionary is created using the zip() function and is printed.

Runtime Test Cases


Case 1:
Enter string:hello world program world test
{'test': 1, 'world': 2, 'program': 1, 'hello': 1}

Case 2:
Enter string:orange banana apple apple orange pineapple
{'orange': 2, 'pineapple': 1, 'banana': 1, 'apple': 2}

Python Program to Create a Dictionary with Key as First


Character and Value as Words Starting with that Character
This is a Python Program to create a dictionary with key as first character and value as
words starting with that character.

Problem Description
The program takes a string and creates a dictionary with key as first character and value as
words starting with that character.

Problem Solution
1. Enter a string and store it in a variable.
2. Declare an empty dictionary.
3. Split the string into words and store it in a list.
4. Using a for loop and if statement check if the word already present as a key in the
dictionary.
5. If it is not present, initialize the letter of the word as the key and the word as the value
and append it to a sublist created in the list.
6. If it is present, add the word as the value to the corresponding sublist.
7. Print the final dictionary.
8. Exit.

Program/Source Code
Here is source code of the Python Program to create a dictionary with key as first character
and value as words starting with that character. The program output is also shown below.
test_string=raw_input("Enter string:")
l=test_string.split()
d={}
for word in l:
if(word[0] not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,":",v)
Program Explanation
1. User must enter a string and store it in a variable.
2. An empty dictionary is declared.
3. The string is split into words and is stored in a list.
4. A for loop is used to traverse through the words in the list.
5. An if statement is used to check if the word already present as a key in the dictionary.
6. If it is not present, the letter of the word is initialized as the key and the word as the value
and they are append to a sublist created in the list.
7. If it is present, the word is added as the value to the corresponding sublist.
8. The final dictionary is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world this is a test string sanfoundry
('a', ':', ['a'])
('i', ':', ['is'])
('H', ':', ['Hello'])
('s', ':', ['sanfoundry', 'string'])
('t', ':', ['test', 'this'])
('w', ':', ['world'])

Case 2:
Enter string:python is my most favourite programming language in the entire world
('e', ':', ['entire'])
('f', ':', ['favourite'])
('i', ':', ['in', 'is'])
('m', ':', ['most', 'my'])
('l', ':', ['language'])
('p', ':', ['programming', 'python'])
('t', ':', ['the'])
('w', ':', ['world'])

6. Python Programming Examples on Sets

Python Program to Count the Number of Vowels Present in a


String using Sets
This is a Python Program to count the number of vowels present in a string using sets

Problem Description
The program takes a string and creates a dictionary with key as first character and value as
words starting with that character.

Problem Solution
1. Enter a string and store it in a variable.
2. Initialize a count variable to 0.
3. Create a set containing vowels.
4. Use a for loop to traverse through the letters in the string.
5. Using an if statement, check if the letter in the string is equal to a vowel.
6. If it is equal, increment the vowel count.
7. Print the final count of the vowels.
8. Exit.

Program/Source Code
Here is source code of the Python Program to create a dictionary with key as first character
and value as words starting with that character. The program output is also shown below.
s=raw_input("Enter string:")
count = 0
vowels = set("aeiou")
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Program Explanation
1. User must enter a string and store it in a variable.
2. The count variable is initialized to 0.
3. A set containing vowels is created using set().
4. A for loop is used to traverse through the letters in the string.
5. An if statement checks if the letter in the string is equal to a vowel.
6. If it is equal, the vowel count is incremented.
7. The final count of the vowels is printed.

Runtime Test Cases


Case 1:
Enter string:Hello world
Count of the vowels is:
3

Case 2:
Enter string:Python Program
Count of the vowels is:
3

Python Program to Check Common Letters in Two Input Strings


This is a Python Program to check common letters in the two input strings.

Problem Description
The program takes two strings and checks common letters in both the strings.

Problem Solution
1. Enter two input strings and store it in separate variables.
2. Convert both of the strings into sets and find the common letters between both the sets.
3. Store the common letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to check common letters in the two input
strings. The program output is also shown below.
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
a=list(set(s1)&set(s2))
print("The common letters are:")
for i in a:
print(i)
Program Explanation
1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the common letters between both the sets
are found using the ‘&’ operator.
3. These common letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases


Case 1:
Enter first string:Hello
Enter second string:How are you
The common letters are:
H
e
o

Case 2:
Enter first string:Test string
Enter second string:checking
The common letters are:
i
e
g
n

Python Program that Displays which Letters are in the First


String but not in the Second
This is a Python Program to display which letters are in the first string but not in the second
string.

Problem Description
The program takes two strings and displays which letters are in the first string but not in the
second string.

Problem Solution
1. Enter two input strings and store it in separate variables.
2. Convert both of the strings into sets and find which letters are present in the first string
but not in the second string.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.
Program/Source Code
Here is source code of the Python Program to display which letters are in the first string but
not in the second string. The program output is also shown below.
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
a=list(set(s1)-set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation
1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are in the first string but
not in the second string are found using the ‘-‘ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases


Case 1:
Enter first string:Hello
Enter second string:world
The letters are:
H
e

Case 2:
Enter first string:Python
Enter second string:Programming language
The letters are:
y
h
t

Python Program that Displays which Letters are Present in Both


the Strings
This is a Python Program to display which letters are present in both the strings.

Problem Description
The program takes two strings and displays which letters are present in both the strings.

Problem Solution
1. Enter two input strings and store it in separate variables.
2. Convert both of the strings into sets and find the union between both the sets.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to display which letters are present in both the
strings. The program output is also shown below.
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
a=list(set(s1)|set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation
1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the union of both the sets are found using
the ‘|’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases


Case 1:
Enter first string:hello
Enter second string:world
The letters are:
e
d
h
l
o
r
w

Case 2:
Enter first string:test
Enter second string:string
The letters are:
e
g
i
n
s
r
t
Python Program that Displays which Letters are in the Two
Strings but not in Both
This is a Python Program to display which letters are in the two strings but not in both.

Problem Description
The program takes two strings and displays which letters are in the two strings but not in
both.

Problem Solution
1. Enter two input strings and store it in separate variables.
2. Convert both of the strings into sets and find which of the letters are in the two strings but
not in both.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code
Here is source code of the Python Program to display which letters are in the two strings but
not in both. The program output is also shown below.
s1=raw_input("Enter first string:")
s2=raw_input("Enter second string:")
a=list(set(s1)^set(s2))
print("The letters are:")
for i in a:
print(i)
Program Explanation
1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are present in the two
strings but not in both are found using the ‘^’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases


Case 1:
Enter first string:hello
Enter second string:world
The letters are:
e
d
h
r
w

Case 2:
Enter first string:Test
Enter second string:string
The letters are:
r
e
g
i
T
n

7. Python Programs with Recursions

Python Program to Determine Whether a Given Number is


Even or Odd Recursively
This is a Python Program to determine whether a given number is even or odd recursively.

Problem Description
The program takes a number and determines whether a given number is even or odd
recursively.

Problem Solution
1. Take a number from the user and store it in a variable.
2. Pass the number as an argument to a recursive function.
3. Define the base condition as the number to be lesser than 2.
4. Otherwise call the function recursively with the number minus 2.
5. Then return the result and check if the number is even or odd.
6. Print the final result.
7. Exit.

Program/Source Code
Here is source code of the Python Program to determine whether a given number is even or
odd recursively. The program output is also shown below.
def check(n):
if (n < 2):
return (n % 2 == 0)
return (check(n - 2))
n=int(input("Enter number:"))
if(check(n)==True):
print("Number is even!")
else:
print("Number is odd!")
Program Explanation
1. User must enter a number and store it in a variable.
2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than 2.
4. Otherwise the function is called recursively with the number minus 2.
5. The result is returned and an if statement is used to check if the number is odd or even.
6. The final result is printed.

Runtime Test Cases


Case 1:
Enter number:124
Number is even!

Case 2:
Enter number:567
Number is odd!

Python Program to Determine How Many Times a Given Letter


Occurs in a String Recursively
This is a Python Program to determine how many times a given letter occurs in a string
recursively.

Problem Description
The program takes a string and determines how many times a given letter occurs in a string
recursively.

Problem Solution
1. Take a string and a character from the user and store it in different variables.
2. Pass the string and the characters as arguments to a recursive function.
3. Pass the base condition that the string isn’t empty.
4. Check if the first character of the string is equal to the character taken from the user and
if it is equal, increment the count.
5. Progress the string either wise and print the number of times the letter occurs in the
string.
6. Exit.
Program/Source Code
Here is source code of the Python Program to determine how many times a given letter
occurs in a string recursively. The program output is also shown below.
def check(string,ch):
if not string:
return 0
elif string[0]==ch:
return 1+check(string[1:],ch)
else:
return check(string[1:],ch)
string=raw_input("Enter string:")
ch=raw_input("Enter character to check:")
print("Count is:")
print(check(string,ch))
Program Explanation
1. User must enter a string and a character and store it in separate variables.
2. The string and the character is passed as arguments to the recursive function.
3. The base condition defined is that the string isn’t empty.
4. If the first character of the string is equal to the character taken from the user, the count is
incremented.
5. The string is progressed by passing it recursively back to the function.
6. The number of times the letter is encountered in the string is printed.

Runtime Test Cases


Case 1:
Enter string:abcdab
Enter character to check:b
Count is:
2

Case 2:
Enter string:hello world
Enter character to check:l
Count is:
3

Python Program to Find the Fibonacci Series Using Recursion


This is a Python Program to find the fibonacci series using recursion.

Problem Description
The program takes the number of terms and determines the fibonacci series using recursion
upto that term.
Problem Solution
1. Take the number of terms from the user and store it in a variable.
2. Pass the number as an argument to a recursive function named fibonacci.
3. Define the base condition as the number to be lesser than or equal to 1.
4. Otherwise call the function recursively with the argument as the number minus 1 added
to the function called recursively with the argument as the number minus 2.
5. Use a for loop and print the returned value which is the fibonacci series.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the fibonacci series using recursion. The
program output is also shown below.
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print fibonacci(i),
Program Explanation
1. User must enter the number of terms and store it in a variable.
2. The number is passed as an argument to a recursive function.
3. The base condition is that the number has to be lesser than or equal to 1.
4. Otherwise the function is called recursively with the argument as the number minus 1
added to the function called recursively with the argument as the number minus 2.
5. The result is returned and a for statement is used to print the fibonacci series.

Runtime Test Cases


Case 1:
Enter number of terms:5
Fibonacci sequence:
0 1 1 2 3

Case 2:
Enter number of terms:7
Fibonacci sequence:
0 1 1 2 3 5 8
Python Program to Find the Factorial of a Number Using
Recursion
This is a Python Program to find the factorial of a number using recursion.

Problem Description
The program takes a number and determines the factorial of the number using recursion.

Problem Solution
1. Take a number from the user and store it in a variable.
2. Pass the number as an argument to a recursive factorial function.
3. Define the base condition as the number to be lesser than or equal to 1 and return 1 if it
is.
4. Otherwise call the function recursively with the number minus 1 multiplied by the number
itself.
5. Then return the result and print the factorial of the number.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the factorial of a number using recursion.
The program output is also shown below.
def factorial(n):
if(n <= 1):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter number:"))
print("Factorial:")
print(factorial(n))
Program Explanation
1. User must enter a number and store it in a variable.
2. The number is passed as an argument to a recursive factorial function.
3. The base condition is that the number has to be lesser than or equal to 1 and return 1 if it
is.
4. Otherwise the function is called recursively with the number minus 1 multiplied by the
number itself.
5. The result is returned and the factorial of the number is printed.

Runtime Test Cases


Case 1:
Enter number:5
Factorial:
120

Case 2:
Enter number:9
Factorial:
362880

Python Program to Find the Sum of Elements in a List


Recursively
This is a Python Program to find the sum of elements in a list recursively.

Problem Description
The program takes a list and finds the sum of elements in a list recursively.

Problem Solution
1. Define a recursive function which takes an array and the size of the array as arguments.
2. Declare an empty list and initialize it to an empty list.
3. Consider a for loop to accept values for the list.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Pass the list and the size of the list as arguments to the recursive function.
7. If the size of the list is zero, return 0.
8. Otherwise return the sum of the last element of the list along with the recursive function
call (with the size reduced by 1).
9. The returned value is stored in a variable and the final sum is printed.
9. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of elements in a list recursively.
The program output is also shown below.
def sum_arr(arr,size):
if (size == 0):
return 0
else:
return arr[size-1] + sum_arr(arr,size-1)
n=int(input("Enter the number of elements for list:"))
a=[]
for i in range(0,n):
element=int(input("Enter element:"))
a.append(element)
print("The list is:")
print(a)
print("Sum of items in list:")
b=sum_arr(a,n)
print(b)
Program Explanation
1. User must enter the number of elements in the list and store it in a variable.
2. User must enter the values to the same number of elements into the list.
3. The append function obtains each element from the user and adds the same to the end
of the list as many times as the number of elements taken.
4. The list and the size of the list are passed as arguments to a recursive function.
5. If the size of the function reduces to 0, 0 is returned.
6. Otherwise the sum of the last element of the list along with the recursive function call
(with the size reduced by 1) is returned.
7. The returned values are stored in a list and the sum of the elements in the list is printed.

Runtime Test Cases


Case 1:
Enter the number of elements for list:3
Enter element:3
Enter element:56
Enter element:7
The list is:
[3, 56, 7]
Sum of items in list:
66

Case 2:
Enter the number of elements for list:5
Enter element:23
Enter element:45
Enter element:62
Enter element:10
Enter element:56
The list is:
[23, 45, 62, 10, 56]
Sum of items in list:
196

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):
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: 20
Binary equivalent:
1 0 1 0 0

Case 2:
Enter a number: 7
Binary equivalent:
1 1 1
Python Program to Find the Sum of the Digits of the Number
Recursively
This is a Python Program to find the sum of the digits of the number recursively.

Problem Description
The program takes a number and finds the sum of the digits of the 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, get each digit and append it to the list.
5. Find the sum of the digits in the list outside the function.
6. Print the total sum.
7. 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 sum_digits(b):
if(b==0):
return l
dig=b%10
l.append(dig)
sum_digits(b//10)
n=int(input("Enter a number: "))
sum_digits(n)
print(sum(l))
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 obtained using a modulus operator and appended to the list.
5. The function is then called with the number taken from the user and the sum of the digits
in the list is found out.
6. The total sum is printed.

Runtime Test Cases


Case 1:
Enter a number: 135
9

Case 2:
Enter a number: 546
15

Python Program to Find the LCM of Two Numbers Using


Recursion
This is a Python Program to find the LCM of two numbers using recursion.

Problem Description
The program takes two numbers and finds the LCM of two numbers using recursion.

Problem Solution
1. Take two numbers from the user.
2. Initialize the multiple variable with the maximum value among two given numbers.
3. Check whether the multiple variable clearly divides both the number or not.
4. If it does, then end the process and return the multiple as the LCM.
5. If multiple doesn’t clearly divides both given numbers then increment the multiple by the
max values among both the given numbers.
5. Return the multiple variable and print the LCM of the two variables.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the LCM of two numbers using recursion.
The program output is also shown below.
def lcm(a,b):
lcm.multiple=lcm.multiple+b
if((lcm.multiple % a == 0) and (lcm.multiple % b == 0)):
return lcm.multiple;
else:
lcm(a, b)
return lcm.multiple
lcm.multiple=0
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
if(a>b):
LCM=lcm(b,a)
else:
LCM=lcm(a,b)
print(LCM)
Program Explanation
1. User must take two numbers from the user.
2. The multiple variable are initialized with the maximum value among two given numbers.
3. The multiple variable is checked if clearly divides both the numbers or not.
4. If it does, then the process is ended and the multiple is returned as the LCM.
5. If multiple doesn’t clearly divides both given numbers then the multiple variable is
returned by the max values among both the given numbers.
5. The multiple variable is returned and the LCM of the two variables is printed.

Runtime Test Cases


Case 1:
Enter first number:126
Enter second number:12
LCM is:
252

Case 2:
Enter first number:25
Enter second number:5
LCM is:
25

Python Program to Find the GCD of Two Numbers Using


Recursion
This is a Python Program to find the GCD of two numbers using recursion.

Problem Description
The program takes two numbers and finds the GCD of two numbers using recursion.

Problem Solution
1. Take two numbers from the user.
2. Pass the two numbers as arguments to a recursive function.
3. When the second number becomes 0, return the first number.
4. Else recursively call the function with the arguments as the second number and the
remainder when the first number is divided by the second number.
5. Return the first number which is the GCD of the two numbers.
6. Print the GCD.
7. Exit.

Program/Source Code
Here is source code of the Python Program to find the GCD of two numbers using
recursion. The program output is also shown below.
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
GCD=gcd(a,b)
print("GCD is: ")
print(GCD)
Program Explanation
1. User must enter two numbers.
2. The two numbers are passed as arguments to a recursive function.
3. When the second number becomes 0, the first number is returned.
4. Else the function is recursively called with the arguments as the second number and the
remainder when the first number is divided by the second number.
5. The first number is then returned which is the GCD of the two numbers.
6. The GCD is then printed.

Runtime Test Cases


Case 1:
Enter first number:5
Enter second number:15
GCD is:
5

Case 2:
Enter first number:30
Enter second number:12
GCD is:
6

Python Program to Find if a Number is Prime or Not Prime


Using Recursion
This is a Python Program to find if a number is prime or not using recursion.

Problem Description
The program takes a number and finds if the number is prime or not using recursion.

Problem Solution
1. Take a number from the user.
2. Pass the number as an argument to a recursive function and initialize the divisor count to
NULL.
3. Then check the number of divisors of the number using recursion and either True or
False is returned.
4. The final result is printed.
5. Exit.

Program/Source Code
Here is source code of the Python Program to find if a number is prime or not using
recursion. The program output is also shown below.
def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print("Number not prime")
return False
else:
return check(n, div-1)
else:
print("Number is prime")
return 'True'
n=int(input("Enter number: "))
check(n)
Program Explanation
1. User must enter a number.
2. The number is passed as an argument to a recursive function and the divisor count is
initialized to NULL.
3. The divisor is initialized to the number minus 1.
4. The number of divisors of the number is checked using recursion and either True or
False is returned.
5. Final result is printed.

Runtime Test Cases


Case 1:
Enter number: 13
Number is prime

Case 2:
Enter number: 30
Number not prime
Python Program to Find the Product of two Numbers Using
Recursion
This is a Python Program to find the product of two numbers using recursion.

Problem Description
The program takes two numbers and finds the product of two numbers using recursion.

Problem Solution
1. Take two numbers from the user.
2. Pass the numbers as arguments to a recursive function to find the product of the two
numbers.
3. Give the base condition that if the first number is lesser than the second, recursively call
the function with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, again call the function recursively, else return 0.
5. Print the final product of the two numbers.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the binary equivalent of a number using
recursion. The program output is also shown below.
def product(a,b):
if(a<b):
return product(b,a)
elif(b!=0):
return(a+product(a,b-1))
else:
return 0
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
print("Product is: ",product(a,b))
Program Explanation
1. User must enter two numbers.
2. The two numbers are passed as arguments to a recursive function to find the product of
the two numbers.
3. The base condition that if the first number is lesser than the second, the function is
recursively called with the arguments as the numbers interchanged.
4. If the second number isn’t equal to 0, the function is called recursively, else 0 is returned.
5. The final product of the two numbers is printed.

Runtime Test Cases


Case 1:
Enter first number: 12
Enter second number: 10
Product is: 120

Case 2:
Enter first number: 12
Enter second number: 11
Product is: 132

Python Program to Find the Power of a Number Using


Recursion
This is a Python Program to find the power of a number using recursion.

Problem Description
The program takes a base and a power and finds the power of the base using recursion.

Problem Solution
1. Take the base and exponential value from the user.
2. Pass the numbers as arguments to a recursive function to find the power of the number.
3. Give the base condition that if the exponential power is equal to 1, return the base
number.
4. If the exponential power isn’t equal to 1, return the base number multiplied with the power
function called recursively with the arguments as the base and power minus 1.
5. Print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the power of a number using recursion.
The program output is also shown below.
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
Program Explanation
1. User must enter the base and exponential value.
2. The numbers are passed as arguments to a recursive function to find the power of the
number.
3. The base condition is given that if the exponential power is equal to 1, the base number
is returned.
4. If the exponential power isn’t equal to 1, the base number multiplied with the power
function is called recursively with the arguments as the base and power minus 1.
5. The final result is printed.

Runtime Test Cases


Case 1:
Enter base: 2
Enter exponential value: 5
Result: 32

Case 2:
Enter base: 5
Enter exponential value: 3
Result: 125

Python Program to Check Whether a String is a Palindrome or


not Using Recursion
This is a Python Program to check whether a string is a palindrome or not using recursion.

Problem Description
The program takes a string and checks whether a string is a palindrome or not using
recursion.

Problem Solution
1. Take a string from the user.
2. Pass the string as an argument to a recursive function.
3. In the function, if the length of the string is less than 1, return True.
4. If the last letter is equal to the first letter, recursively call the function with the argument as
the sliced list with the first character and last character removed else return False.
5. Use an if statement if check if the returned value is True of False and print the final result.
6. Exit.

Program/Source Code
Here is source code of the Python Program to check whether a string is a palindrome or not
using recursion. The program output is also shown below.
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("String isn't a palindrome!")
Program Explanation
1. User must enter a string.
2. The string is passed as an argument to a recursive function.
3. In the function, if the length of the string is less than 1, True is returned.
4. If the last letter is equal to the first letter, the function is called recursively with the
argument as the sliced list with the first character and last character removed, else return
False.
5. The if statement is used to check if the returned value is True or False and the final result
is printed.

Runtime Test Cases


Case 1:
Enter string:mom
String is a palindrome!

Case 2:
Enter string:hello
String isn't a palindrome!

Python Program to Reverse a String Using Recursion


This is a Python Program to reverse a string using recursion.

Problem Description
The program takes a string and reverses the string using recursion.

Problem Solution
1. Take a string from the user.
2. Pass the string as an argument to a recursive function to reverse the string.
3. In the function, put the base condition that if the length of the string is equal to 0, the
string is returned.
4. Otherwise recursively call the reverse function to slice the part of the string except the
first character and concatenate the first character to the end of the sliced string.
5. Print the reversed string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to reverse a string using recursion. The
program output is also shown below.
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))
print(reverse(a))
Program Explanation
1. User must enter a string.
2. The string is passed as an argument to a recursive function to reverse the string.
3. In the function, the base condition is that if the length of the string is equal to 0, the string
is returned.
4. If not equal to 0, the reverse function is recursively called to slice the part of the string
except the first character and concatenate the first character to the end of the sliced string.
5. The reversed string is printed.

Runtime Test Cases


Case 1:
Enter the string to be reversed: hello world
dlrow olleh

Case 2:
Enter the string to be reversed: first
tsrif

Python Program to Flatten a Nested List using Recursion


This is a Python Program to flatten a nested list using recursion.

Problem Description
The program takes a nested list and flattens it using recursion.

Problem Solution
1. Initialize a variable to a nested list.
2. Pass the list as an argument to a recursive function to flatten the list.
3. In the function, if the list is empty, return the list.
4. Otherwise call the function is recursively with the sublists as the parameters until the
entire list is flattened.
5. Print the flattened list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to flatten a nested list using recursion. The
program output is also shown below.
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
s=[[1,2],[3,4]]
print("Flattened list is: ",flatten(s))
Program Explanation
1. A variable is initialized to contain a nested list.
2. The list is passed as an argument to a recursive function to flatten the list.
3. In the function, if the list is empty, the list is returned.
4. Otherwise the function is recursively called with the sublists as the parameters until the
entire list is flattened.
5. The flattened list is printed.

Runtime Test Cases


Case 1:
Flattened list is: [1, 2, 3, 4]

Python Program to Find the Total Sum of a Nested List Using


Recursion
This is a Python Program to find the total sum of a nested list using recursion.

Problem Description
The program takes a nested list and finds the total sum of the nested list using recursion.

Problem Solution
1. Initialize a variable to a nested list.
2. Pass the list as an argument to a recursive function to find the sum of elements of the list.
3. In the function, use a for loop and recursion to obtain the elements inside the sublists and
store the summed up elements in a variable.
4. Return the total sum of the elements.
5. Print the sum of the nested list.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of a nested list using recursion.
The program output is also shown below.
def sum1(lst):
total = 0
for element in lst:
if (type(element) == type([])):
total = total + sum1(element)
else:
total = total + element
return total
print( "Sum is:",sum1([[1,2],[3,4]]))
Program Explanation
1. A variable is initialized to a nested list.
2. The list is passed as an argument to a recursive function to find the sum of elements of
the list.
3. In the function, A for loop and repeated recursion to obtain the elements inside the
sublists.
4. The total sum of the elements is found out and is returned.
5. The sum of the elements in the nested list is printed.

Runtime Test Cases


Case 1:
Sum is: 10

Python Program to Find the Length of a List Using Recursion


This is a Python Program to find the length of a list recursively.

Problem Description
The program takes a list and finds the length of the list recursively.
Problem Solution
1. Define a recursive function which takes a list as the argument.
2. Initialize a variable to a list.
3. In the function, put the condition that if it is not the original list, return 0.
4. Otherwise, recursively call the function to find the length of the list.
5. Print the final result of the string.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the length of a list recursively. The
program output is also shown below.
def length(lst):
if not lst:
return 0
return 1 + length(lst[1::2]) + length(lst[2::2])
a=[1,2,3]
print("Length of the string is: ")
print(a)
Program Explanation
1. Define a recursive function which takes a list as the argument.
2. Initialize a variable to a list.
3. In the function, put the condition that if it is not the original list, return 0.
4. Otherwise, recursively call the function to find the length of the list.
5. Print the final result of the string.

Runtime Test Cases


Case 1:
Length of the string is:
[1, 2, 3]

8. Python Programs without Recursions

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.
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
0 1 1 2
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

Python Program to find the factorial of a number without


recursion
This is a Python Program to find the factorial of a number without using recursion.

Problem Description
The program takes a number and finds the factorial of that number without using recursion.

Problem Solution
1. Take a number from the user.
2. Initialize a factorial variable to 1.
3. Use a while loop to multiply the number to the factorial variable and then decrement the
number.
4. Continue this till the value of the number is greater than 0.
5. Print the factorial of the number.
6. Exit.

Program/Source Code
Here is source code of the Python Program to find the factorial of a number without using
recursion. The program output is also shown below.
n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)
Program Explanation
1. User must enter a number.
2. A factorial variable is initialized to 1.
3. A while loop is used to multiply the number to the factorial variable and then the number
is decremented each time.
4. This continues till the value of the number is greater than 0.
5. The factorial of the number is printed.
Runtime Test Cases
Case 1:
Enter number:5
Factorial of the number is:
120

Case 2:
Enter number:4
Factorial of the number is:
24

Python Program to Flatten a List without using Recursion


This is a Python Program to flatten a nested list without using recursion.

Problem Description
The program takes a nested list and flattens the nested list without using recursion.

Problem Solution
1. A variable must be initialized with a nested list.
2. Use a lambda function and map() to map the flatten function to each element in the
nested list to flatten the list.
3. Print the flattened list.
4. Exit.

Program/Source Code
Here is source code of the Python Program to flatten a nested list without using recursion.
The program output is also shown below.
a=[[1,[[2]],[[[3]]]],[[4],5]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print(flatten(a))
Program Explanation
1. A variable is initialized with a nested list.
2. Using a lambda function and map(), the function flatten is mapped to each element in the
nested list to flatten the list.
3. The flattened list is then printed.

Runtime Test Cases


Case 1:
[1, 2, 3, 4, 5]
Python Program to Reverse a String without using Recursion
This is a Python Program to reverse a string without using recursion.

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

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

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])
Program Explanation
1. User must enter a string.
2. By giving the increment value as -1, string slicing is used to reverse the list.
3. The reversed string is printed.

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

Python Program to Find the Binary Equivalent of a Number


without Using Recursion
This is a Python Program to find the binary equivalent of a number without using recursion.

Problem Description
The program takes a number and finds the binary equivalent of the number without using
recursion.

Problem Solution
1. Take a number from the user.
2. Using a while loop, convert each digit into binary and append it to the list.
3. Reverse the list and using a for loop print the elements of the list.
4. Exit.

Program/Source Code
Here is source code of the Python Program to find the binary equivalent of a number
without using recursion. The program output is also shown below.
n=int(input("Enter a number: "))
a=[]
while(n>0):
dig=n%2
a.append(dig)
n=n//2
a.reverse()
print("Binary Equivalent is: ")
for i in a:
print(i,end=" ")
Program Explanation
1. User must enter a number.
3. The condition for the while loop is that the number should be greater than 0.
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 which is the
binary equivalent of the number.

Runtime Test Cases


Case 1:
Enter a number: 2
Binary Equivalent is:
1 0

Case 2:
Enter a number: 7
Binary Equivalent is:
1 1 1
Python Program to Find All Numbers which are Odd and
Palindromes Between a Range of Numbers without using
Recursion
This is a Python Program to find all numbers which are odd and palindromes between a
range of numbers without using recursion.

Problem Description
The program takes a range and prints all numbers which are odd and palindromes between
the range without using recursion.

Problem Solution
1. Take a upper limit and lower limit from the user.
2. Using list comprehension, store all the numbers in the list that are odd and palindromes.
3. Print the list.
4. Exit.

Program/Source Code
Here is source code of the Python Program to find all numbers which are odd and
palindromes between a range of numbers without using recursion. The program output is
also shown below.
a=[]
l=int(input("Enter lower limit: "))
u=int(input("Enter upper limit: "))
a=[x for x in range(l,u+1) if x%2!=0 and str(x)==str(x)[::-1]]
print("The numbers are: ",a)
Program Explanation
1. User must enter a upper and lower limit.
2. Using list comprehension, the numbers which are odd(determined using the modulus
operator) and that are palindromes(determined using string slicing) are stored into a list.
3. The list is printed.

Runtime Test Cases


Case 1:
Enter lower limit: 100
Enter upper limit: 150
The numbers are: [101, 111, 121, 131, 141]

Case 2:
Enter lower limit: 300
Enter upper limit: 400
The numbers are: [303, 313, 323, 333, 343, 353, 363, 373, 383, 393]
Python Program to Find the Sum of Digits in a Number without
Recursion
This is a Python Program to find the sum of digits in a number without using recursion.

Problem Description
The program takes a number and finds the sum of digits without using recursion.

Problem Solution
1. Take a number from the user.
2. Using a while loop, obtain each digit and append it to the list.
3. Use the sum() function to obtain the sum of digits in the list.
4. Exit.

Program/Source Code
Here is source code of the Python Program to find the sum of digits in a number without
using recursion. The program output is also shown below.
l=[]
b=int(input("Enter a number: "))
while(b>0):
dig=b%10
l.append(dig)
b=b//10
print("Sum is:")
print(sum(l))
Program Explanation
1. User must enter a number.
3. The condition for the while loop is that the number should be greater than 0.
4. Otherwise, each digit is obtain and appended to the list.
5. The sum of elements in the list is obtained using the sum() function and printed which is
the sum of digits of the number.

Runtime Test Cases


Case 1:
Enter a number: 123
Sum is:
6

Case 2:
Enter a number: 567
Sum is:
18
9. Python Programs on File Handling

Python Program to Read the Contents of a File


This is a Python Program to read the contents of a file.

Problem Description
The program takes the file name from the user and reads the contents of that file.

Problem Solution
1. Take the file name from the user.
2. Use readline() function for the first line first.
3. Use a while loop to print the first line and then read the remaining lines and print it till the
end of file.
4. Exit.

Program/Source Code
Here is source code of the Python Program to read the contents of a file. The program
output is also shown below.
a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3.The readline() outside the while loop is used to read the first line of the file.
4. Inside the loop, the first line is first printed and then the remaining lines are read and
subsequently printed.
5. This continues this the end of file.
6. The file is then closed.

Runtime Test Cases


Case 1:
Contents of file:
Hello world
Output:
Enter the name of the file with .txt extension: data1.txt

Case 2:
Contents of file:
This programming language is
Python.

Output:
Enter the name of the file with .txt extension: data2.txt
This programming language is
Python.

Python Program to Count the Number of Words in a Text File


This is a Python Program to count the number of words in a text file.

Problem Description
The program takes the file name from the user and counts number of words in that file.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Find the length of items in the list and print it.
4. Exit.

Program/Source Code
Here is source code of the Python Program to count the number of words in a text file. The
program output is also shown below.
fname = input("Enter file name: ")

num_words = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. The number of words in each line is counted using len() and the count variable is
incremented.
6. The number of words in the file is printed.

Runtime Test Cases


Case 1:
Contents of file:
Hello world

Output:
Enter file name: data1.txt
Number of words:
2

Case 2:
Contents of file:
This programming language is
Python

Output:
Enter file name: data2.txt
Number of words:
5

Python Program to Count the Number of Lines in a Text File


This is a Python Program to count the number of lines in a text file.

Problem Description
The program takes the file name from the user and counts number of lines in that file.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file and increment the count variable
3. Print the line count.
4. Exit.

Program/Source Code
Here is source code of the Python Program to count the number of lines in a text file. The
program output is also shown below.
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f:
for line in f:
num_lines += 1
print("Number of lines:")
print(num_lines)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. The line count is incremented each time and the final count is printed.

Runtime Test Cases


Case 1:
Contents of file:
Hello world

Output:
Enter file name: data1.txt
Number of lines:
1

Case 2:
Contents of file:
This programming language is
Python

Output:
Enter file name: data2.txt
Number of lines:
2

Python Program to Read a String from the User and Append it


into a File
This is a Python Program to read a string from the user and appends it into a file

Problem Description
The program takes a string from the user and appends the string into an existing file.

Problem Solution
1. Take the file name from the user.
2. Open the file in append mode.
2. Take in a string from the user, append it to the existing file and close the file.
3. Open the file again in read mode and display the contents of the file.
4. Exit.
Program/Source Code
Here is source code of the Python Program to read a string from the user and appends it
into a file. The program output is also shown below.
fname = input("Enter file name: ")
file3=open(fname,"a")
c=input("Enter string to append: \n");
file3.write("\n")
file3.write(c)
file3.close()
print("Contents of appended file:");
file4=open(fname,'r')
line1=file4.readline()
while(line1!=""):
print(line1)
line1=file4.readline()
file4.close()
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the append mode.
3. A string is taken from the user, appended to the existing file and is closed.
4. The file is opened again in the read mode.
5. The readline() in the while loop reads each and every line in the file and print() prints the
contents on the output screen.

Runtime Test Cases


Case 1:
Contents of file:
Hello world

Output:
Enter file name: test.txt
Enter string to append:
test
Contents of appended file:
Hello world

test

Case 2:
Contents of file:
This programming language is
Python

Output:
Enter file name: test1.txt
Enter string to append:
test
Contents of appended file:
This programming language is
Python

test

Python Program to Count the Occurrences of a Word in a Text


File
This is a Python Program to count the occurrences of a word in a text file.

Problem Description
The program takes a word from the user and counts the number of occurrences of that word
in a file.

Problem Solution
1. Take the file name and the word to be counted from the user.
2. Read each line from the file and split the line to form a list of words.
3. Check if the word provided by the user and any of the words in the list are equal and if
they are, increment the word count.
4. Exit.

Program/Source Code
Here is source code of the Python Program to count the occurrences of a word in a text file.
The program output is also shown below.
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
Program Explanation
1. User must enter a file name and the word to be searched.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. Another for loop is used to traverse through the list and each word in the list is compared
with the word provided by the user.
6. If both the words are equal, the word count is incremented.
7. The final count of occurrences of the word is printed.

Runtime Test Cases


Case 1:
Contents of file:
hello world hello
hello

Output:
Enter file name: test.txt
Enter word to be searched:hello
Occurrences of the word:
3

Case 2:
Contents of file:
hello world
test
test test

Output:
Enter file name: test1.txt
Enter word to be searched:test
Occurrences of the word:
4

Python Program to Copy the Contents of One File into Another


This is a Python Program to copy the contents of one file into another.

Problem Description
The program copies the contents of one file and writes it into another.

Problem Solution
1. Open one file called test.txt in read mode.
2. Open another file out.txt in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.

Program/Source Code
Here is source code of the Python Program to copy the contents of one file into another.
The program output is also shown below.
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
Program Explanation
1. The file test.txt is opened using the open() function using the f stream.
2. Another file out.txt is opened using the open() function in the write mode using the f1
stream.
3. Each line in the file is iterated over using a for loop (in the input stream).
4. Each of the iterated lines is written into the output file.

Runtime Test Cases


Case 1:
Contents of file(test.txt):
Hello world

Output(out.text):
Hello world

Case 2:
Contents of file(test.txt):
Sanfoundry

Output(out.text):
Sanfoundry

Python Program that Reads a Text File and Counts the Number
of Times a Certain Letter Appears in the Text File
This is a Python Program to count the occurrences of a letter in a text file.

Problem Description
The program takes a letter from the user and counts the number of occurrences of that
letter in a file.

Problem Solution
1. Take the file name and the letter to be counted from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse
through the letters in the word.
4. Check if the letter provided by the user and the letter encountered over iteration is equal
and if they are, increment the letter count.
5. Exit.

Program/Source Code
Here is source code of the Python Program to count the occurrences of a letter in a text file.
The program output is also shown below.
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
Program Explanation
1. User must enter a file name and the letter to be searched.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. A for loop is used to traverse through the words list and another for loop is used to
traverse through the letters in the word.
6. If the letter provided by the user and the letter encountered over iteration are equal, the
letter count is incremented.
7. The final count of occurrences of the letter is printed.

Runtime Test Cases


Case 1:
Contents of file:
hello world hello
hello

Output:
Enter file name: out.txt
Enter letter to be searched:o
Occurrences of the letter:
5

Case 2:
Contents of file:
hello world
test
test test

Output:
Enter file name: out1.txt
Enter letter to be searched:e
Occurrences of the letter:
6

Python Program to Read a Text File and Print all the Numbers
Present in the Text File
This is a Python Program to read a text file and print all numbers present in the text file.

Problem Description
The program takes the name of a file from the user and prints all the numbers present in the
text file.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse
through the letters in the word.
3. Check if the letter provided by the user is a digit and if it is, print it.
4. Exit.

Program/Source Code
Here is source code of the Python Program to print all the numbers present in a text file.
The program output is also shown below.
fname = input("Enter file name: ")

with open(fname, 'r') as f:


for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. A for loop is used to traverse through the words list and another for loop is used to
traverse through the letters in the word.
6. If the letter encountered is a digit, the digit is printed.

Runtime Test Cases


Case 1:
Contents of file:
hello world hello5
hello6

Output:
Enter file name: out.txt
5
6

Case 2:
Contents of file:
hello world7
test2
test test8

Output:
Enter file name: out1.txt
7
2
8

Python Program to Append the Contents of One File to Another


File
This is a Python Program to append the contents of one file to another file.

Problem Description
The program takes the name of the file to be read from and the file to append into from the
user and appends the contents of one file to another.

Problem Solution
1. Take the name of the file to be read from and the file to append into from the user.
2. Open the file to be read and read the content of the file and store it in a variable.
3. Open the file to append the data to and write the data stored in the variable into the file.
4. Close both the files.
5. Exit.
Program/Source Code
Here is source code of the Python Program to append the contents of one file to another
file. The program output is also shown below.
name1 = input("Enter file to be read from: ")
name2 = input("Enter file to be appended to: ")
fin = open(name1, "r")
data2 = fin.read()
fin.close()
fout = open(name2, "a")
fout.write(data2)
fout.close()
Program Explanation
1. User must enter the name of the file to be read from and the file to append into.
2. The file to be read is opened using open() function in the read mode.
3. The contents of the file read using read() function is stored in a variable and then the file
is closed.
3. The file to append the data to is opened in the append mode and the data stored in the
variable is written into the file.
4. The second file is then closed..

Runtime Test Cases


Case 1:

Output:
Enter file to be read from: test.txt
Enter file to be appended to: test1.txt

Contents of file test.txt:


Appending!!

Contents of file test1.txt (before appending):


Original

Contents of file test1.txt (after appending):


Original Appending!!

Case 2:
Enter file to be read from: out.txt
Enter file to be appended to: out1.txt

Contents of file test.txt:


world
Contents of file test1.txt (before appending):
Hello

Contents of file test1.txt (after appending):


Hello world
Python Program to Count the Number of Blank Spaces in a
Text File
This is a Python Program to count the number of blank spaces in a text file.

Problem Description
The program reads a file and counts the number of blank spaces in a text file.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file and split the line to form a list of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse
through the letters in the word.
4. Check if the letter is a space and if it is, increment the variable count.
5. Print the final count of the number of spaces.
6. Exit.

Program/Source Code
Here is source code of the Python Program to count the number of blank spaces in a text
file. The program output is also shown below.
fname = input("Enter file name: ")
k = 0

with open(fname, 'r') as f:


for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print("Occurrences of blank spaces:")
print(k)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. A for loop is used to traverse through the words list and another for loop is used to
traverse through the letters in the word.
6. If the letter iterated over is a space, the letter count is incremented.
7. The final count of occurrences of blank spaces is printed.

Runtime Test Cases


Case 1:
Contents of file:
he l l o world hello

Output:
Enter file name: read.txt
Occurrences of blank spaces:
5

Case 2:
Contents of file:
t e st

Output:
Enter file name: read2.txt
Occurrences of blank spaces:
2

Python Program to Read a File and Capitalize the First Letter of


Every Word in the File
This is a Python Program to read a file and capitalize the first letter of every word in the file.

Problem Description
The program reads a file and capitalizes the first letter of every word in the file.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file and use the title() function to capitalize each word in the line.
3. Print the altered lines of the file.
5. Exit.

Program/Source Code
Here is source code of the Python Program that reads a file and capitalizes the first letter of
every word in the file. The program output is also shown below.
fname = input("Enter file name: ")

with open(fname, 'r') as f:


for line in f:
l=line.title()
print(l)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each word in the line is capitalized using the title() function.
5. The altered lines are printed.

Runtime Test Cases


Case 1:
Contents of file:
hello world
hello

Output:
Enter file name: read.txt
Hello World
Hello

Case 2:
Contents of file:
test1 test2

Output:
Enter file name: read2.txt
Test1 Test2

Python Program to Read the Contents of a File in Reverse


Order
This is a Python Program to read the contents of a file in reverse order.

Problem Description
The program takes a file name from the user and reads the contents of the file in reverse
order.

Problem Solution
1. Take the file name from the user.
2. Read each line from the file using for loop and store it in a list.
3. Print the elements of list in reverse order.
4. Exit.

Program/Source Code
Here is source code of the Python Program to read the contents of the file in reverse order.
The program output is also shown below.
filename=input("Enter file name: ")
for line in reversed(list(open(filename))):
print(line.rstrip())
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function and all lines are stored in a list.
3. reversed() function produces a reverse iterator.
4. All the lines are then printed in reverse order using a for loop and rstrip() function strips
all the blank spaces from the end of the line.

Runtime Test Cases


Case 1:
Contents of file:
hello world
hello

Output:
Enter file name: read.txt
hello
hello word

Case 2:
Contents of file:
line1
line2
line3

Output:
Enter file name: read2.txt
line3
line2
line1

10. Python Programs on Classes and Objects

Python Program to Find the Area of a Rectangle Using Classes


This is a Python Program to find the area of a rectangle using classes.

Problem Description
The program takes the length and breadth from the user and finds the area of the rectangle
using classes.

Problem Solution
1. Take the value of length and breadth from the user.
2. Create a class and using a constructor initialise values of that class.
3. Create a method called as area and return the area of the class.
4. Create an object for the class.
5. Using the object, call the method area() with the parameters as the length and breadth
taken from the user.
6. Print the area.
7. Exit

Program/Source Code
Here is the source code of the Python Program to take the length and breadth from the user
and find the area of the rectangle. The program output is also shown below.
class rectangle():
def __init__(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
return self.breadth*self.length
a=int(input("Enter length of rectangle: "))
b=int(input("Enter breadth of rectangle: "))
obj=rectangle(a,b)
print("Area of rectangle:",obj.area())

print()
Program Explanation
1. User must enter the value of length and breadth.
2. A class called rectangle is created and the __init__() method is used to initialise values of
that class.
3. A method called as area, returns self.length*self.breadth which is the area of the class.
4. An object for the class is created.
5. Using the object, the method area() is called with the parameters as the length and
breadth taken from the user.
6. The area is printed.

Runtime Test Cases


Case 1:
Enter length of rectangle: 4
Enter breadth of rectangle: 5
Area of rectangle: 20

Case 2:
Enter length of rectangle: 15
Enter breadth of rectangle: 13
Area of rectangle: 195

Python Program to Append, Delete and Display Elements of a


List Using Classes
This is a Python Program to append, delete and display elements of a list using classes.

Problem Description
The program appends, deletes and displays elements of a list using classes.

Problem Solution
1. Create a class and using a constructor initialize values of that class.
2. Create methods for adding, removing and displaying elements of the list and return the
respective values.
3. Create an object for the class.
4. Using the object, call the respective function depending on the choice taken from the
user.
5. Print the final list.
6. Exit

Program/Source Code
Here is the source code of the Python Program to append, delete and display elements of a
list using classes. The program output is also shown below.
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)

obj=check()

choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
choice=int(input("Enter choice: "))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List: ",obj.dis())

elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())

elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")

print()
Program Explanation
1. A class called check is created and the __init__() method is used to initialize values of
that class.
2. Methods for adding, removing and displaying elements of the list have been defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created.
5. Using the object, the respective method is called according to the choice taken from the
user.
6. The final list is printed.

Runtime Test Cases


Case 1:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 23
List: [23]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 45
List: [23, 45]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 56
List: [23, 45, 56]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 2
Enter number to remove: 45
List: [23, 56]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!

Case 2:
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 10
List: [10]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 1
Enter number to append: 7
List: [10, 7]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!

Python Program to Create a Class and Compute the Area and


the Perimeter of the Circle
This is a Python Program to compute the area and perimeter of the circle using classes.

Problem Description
The program takes the radius from the user and finds the area of the circle using classes.

Problem Solution
1. Take the value of radius from the user.
2. Create a class and using a constructor initialise values of that class.
3. Create a method called as area which returns the area of the class and a method called
as perimeter which returns the perimeter of the class.
4. Create an object for the class.
5. Using the object, call both the methods.
6. Print the area and perimeter of the circle.
7. Exit

Program/Source Code
Here is the source code of the Python Program to take the radius from the user and find the
area of the circle using classes. The program output is also shown below.
import math
class circle():
def __init__(self,radius):
self.radius=radius
def area(self):
return math.pi*(self.radius**2)
def perimeter(self):
return 2*math.pi*self.radius

r=int(input("Enter radius of circle: "))


obj=circle(r)
print("Area of circle:",round(obj.area(),2))
print("Perimeter of circle:",round(obj.perimeter(),2))
Program Explanation
1. User must enter the value of radius.
2. A class called circle is created and the __init__() method is used to initialize values of
that class.
3. A method called as area returns math.pi*(self.radius**2) which is the area of the class.
3. Another method called perimeter returns 2*math.pi*self.radius which is the perimeter of
the class.
5. An object for the class is created.
6. Using the object, the methods area() and perimeter() are called.
7. The area and perimeter of the circle is printed.

Runtime Test Cases


Case 1:
Enter radius of circle: 5
Area of circle: 78.54
Perimeter of circle: 31.42
Case 2:
Enter radius of circle: 10
Area of circle: 314.16
Perimeter of circle: 62.83

Python Program to Create a Class which Performs Basic


Calculator Operations
This is a Python Program to find the area of a rectangle using classes.

Problem Description
The program takes the length and breadth from the user and finds the area of the rectangle
using classes.

Problem Solution
1. Create a class and using a constructor to initialize values of that class.
2. Create methods for adding, substracting, multiplying and dividing two numbers and
returning the respective results.
3. Take the two numbers as inputs and create an object for the class passing the two
numbers as parameters to the class.
4. Using the object, call the respective function depending on the choice taken from the
user.
5. Print the final result.
6. Exit

Program/Source Code
Here is the source code of the Python Program to take the length and breadth from the user
and find the area of the rectangle. The program output is also shown below.
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")

print()
Program Explanation
1. A class called cal is created and the __init__() method is used to initialize values of that
class.
2. Methods for adding, substracting, multiplying, dividing two numbers and returning their
respective results is defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created with the two numbers taken from the user passed as
parameters.
5. Using the object, the respective method is called according to the choice taken from the
user.
6. When the choice is 0, the loop is exited.
7. The final result is printed.

Runtime Test Cases


Case 1:
Enter first number: 2
Enter second number: 4
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 1
Result: 6
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 3
Result: 8
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 0
Exiting!

Case 2:
Enter first number: 150
Enter second number: 50
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 2
Result: 100
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 4
Result: 3.0
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 0
Exiting!

Python Program to Create a Class in which One Method


Accepts a String from the User and Another Prints it
This is a Python Program to accept and print a string using classes.

Problem Description
The program takes the string from the user and prints the string using classes.

Problem Solution
1. Create a class and using a constructor initialize values of that class.
3. Create two methods called as get which takes in the value of a string and another called
put that prints the string.
4. Create an object for the class.
5. Using the object, call both the methods.
6. The string is printed.
7. Exit

Program/Source Code
Here is the source code of the Python Program that takes the string from the user and prints
the string using classes. The program output is also shown below.
class print1():
def __init__(self):
self.string=""

def get(self):
self.string=input("Enter string: ")

def put(self):
print("String is:")
print(self.string)

obj=print1()
obj.get()
obj.put()
Program Explanation
1. A class called print1 is created and the __init__() method is used to initialize the value of
the string to “”.
3. The first method, get, takes the value of the string from the user.
3. The second string, put, is used to print the value of the string.
5. An object for the class called obj is created.
6. Using the object, the methods get() and put() is printed.
7. The value of the string is printed.

Runtime Test Cases


Case 1:
Enter string: Hello world
String is:
Hello world

Case 2:
Enter string: Sanfoundry is a very helpful website
String is:
Sanfoundry is a very helpful website
Python Program to Create a Class and Get All Possible
Subsets from a Set of Distinct Integers
This is a Python Program to create a class and get all possible subsets from a set of distinct
integers.

Problem Description
The program creates a class to get all possible subsets from a set of distinct integers.

Problem Solution
1. Create a class and define two methods in the class.
3. Method f1 is used to pass an empty list and the sorted list taken from the user to method
f2.
4. Method f2 is used to compute all possible subsets of the list.
5. Then the result is returned from the function and printed.
6. Exit

Program/Source Code
Here is the source code of the Python Program to create a class to get all possible subsets
from a set of distinct integers. The program output is also shown below.
class sub:
def f1(self, s1):
return self.f2([], sorted(s1))

def f2(self, curr, s1):


if s1:
return self.f2(curr, s1[1:]) + self.f2(curr + [s1[0]], s1[1:])
return [curr]
a=[]
n=int(input("Enter number of elements of list: "))
for i in range(0,n):
b=int(input("Enter element: "))
a.append(b)
print("Subsets: ")
print(sub().f1(a))
Program Explanation
1. A class called sub is created and two methods f1 and f2 are defined.
3. In main, the number of elements is taken from the user.
3. Using a for loop, the elements are taken from the user and appended to an empty list.
5. Then, the method f1 of the class sub is called by passing the list taken from the user as
the parameter.
6. Method f1 in turn calls method f2 with an empty list and the sorted list taken from the user
as parameters.
7. Method f2 is a recursive function.
8. This method computes all the possible subsets by splitting the current list part by part
starting from an empty list and updating the value of the current list.
9. This continues till the list becomes empty.
10. The current value of the list which is a list containing subsets as separate lists is
returned.
11. The final result is printed.

Runtime Test Cases


Case 1:
Enter number of elements of list: 2
Enter element: 4
Enter element: 5
Subsets:
[[], [5], [4], [4, 5]]

Case 2:
Enter number of elements of list: 4
Enter element: 3
Enter element: 5
Enter element: 7
Enter element: 28
Subsets:
[[], [28], [7], [7, 28], [5], [5, 28], [5, 7], [5, 7, 28], [3], [3, 28], [3, 7], [3,
7, 28], [3, 5], [3, 5, 28], [3, 5, 7], [3, 5, 7, 28]]

Linked lists

Python Programming Examples on Linked Lists

1. Python Examples on Creating and Displaying the Elements of a Linked List

Python Program to Read a Linked List in Reverse


This is a Python program to read a linked list in reverse.

Problem Description
The program creates a singly linked list and allows the user to enter data items to the list in
reverse.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the singly linked list.
4. Define methods insert_at_beg and display.
5. The method insert_at_beg inserts a node at the first position of the list.
6. The method display traverses the list from the first node and prints the data of each node.
7. Create an instance of LinkedList and prepend the data items input by the user.

Program/Source Code
Here is the source code of a Python program to read a linked list in reverse. The program
output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def insert_at_beg(self, new_node):


if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
node = Node(data)
a_llist.insert_at_beg(node)

print('The linked list: ', end = '')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to provide data items for the list.
3. The insert_at_beg method is used to enter the data to the list in reverse.

Runtime Test Cases


Case 1:
How many elements would you like to add? 4
Enter data item: 5
Enter data item: 3
Enter data item: 10
Enter data item: 2
The linked list: 2 10 3 5

Case 2:
How many elements would you like to add? 1
Enter data item: 8
The linked list: 8

Case 3:
How many elements would you like to add? 3
Enter data item: 1
Enter data item: 2
Enter data item: 3
The linked list: 3 2 1

Python Program to Create a Linked List & Display the Elements


in the List
This is a Python program to create a linked list and display its elements.

Problem Description
The program creates a linked list using data items input from the user and displays it.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Create an instance of LinkedList, append data to it and display the list.

Program/Source Code
Here is the source code of a Python program to create a linked list and display its elements.
The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is asked for the number of elements they would like to add. This is stored in n.
3. Using a loop, data from the user is appended to the linked list n times.
4. The linked list is displayed.

Runtime Test Cases


Case 1:
How many elements would you like to add? 5
Enter data item: 3
Enter data item: -2
Enter data item: 1
Enter data item: 5
Enter data item: 0
The linked list: 3 -2 1 5 0

Case 2:
How many elements would you like to add? 1
Enter data item: 6
The linked list: 6

Case 3:
How many elements would you like to add? 4
Enter data item: 2
Enter data item: 9
Enter data item: 3
Enter data item: 2
The linked list: 2 9 3 2

2. Python Examples on Search and Display Functions of a Linked List

Python Program to Search for an Element in the Linked List


using Recursion
This is a Python program to search for an element in a linked list using recursion.

Problem Description
The program prompts the user for a key to search in a linked list and displays its index.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define methods find_index and find_index_helper.
5. find_index calls find_index_helper to search for the key recursively.
6. Create an instance of LinkedList, append data to it and display the list.
7. Prompt the user for a key to search and search for it.

Program/Source Code
Here is the source code of a Python program to search for an element in a linked list using
recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

def find_index(self, key):


return self.find_index_helper(key, 0, self.head)

def find_index_helper(self, key, start, node):


if node is None:
return -1

if node.data == key:
return start
else:
return self.find_index_helper(key, start + 1, node.next)

a_llist = LinkedList()
for data in [3, 5, 0, 10, 7]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()

key = int(input('What data item would you like to search for? '))
index = a_llist.find_index(key)
if index == -1:
print(str(key) + ' was not found.')
else:
print(str(key) + ' is at index ' + str(index) + '.')
Program Explanation
1. An instance of LinkedList is created.
2. Some elements are appended to the list.
3. The linked list is displayed.
4. The user is prompted for a key to search.
5. find_index_helper searches for the index. It returns -1 if the key is not found.
6. The index is displayed if found.
Runtime Test Cases
Case 1:
The linked list: 3 5 0 10 7
What data item would you like to search for? 5
5 is at index 1.

Case 2:
The linked list: 3 5 0 10 7
What data item would you like to search for? 7
7 is at index 4.

Case 3:
The linked list: 3 5 0 10 7
What data item would you like to search for? 4
4 was not found.

Python Program to Search for an Element in the Linked List


without using Recursion
This is a Python program to search for an element in a linked list without using recursion.

Problem Description
The program prompts the user for a key to search in a linked list and displays its index.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define method find_index to search for the key.
5. find_index uses a loop to iterate over the nodes of the linked list to search for the key.
6. Create an instance of LinkedList, append data to it and display the list.
7. Prompt the user for a key to search and search for it.

Program/Source Code
Here is the source code of a Python program to search for an element in a linked list without
using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

def find_index(self, key):


current = self.head

index = 0
while current:
if current.data == key:
return index
current = current.next
index = index + 1

return -1

a_llist = LinkedList()
for data in [4, -3, 1, 0, 9, 11]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()

key = int(input('What data item would you like to search for? '))
index = a_llist.find_index(key)
if index == -1:
print(str(key) + ' was not found.')
else:
print(str(key) + ' is at index ' + str(index) + '.')
Program Explanation
1. An instance of LinkedList is created.
2. Some elements are appended to the list.
3. The linked list is displayed.
4. The user is prompted for a key to search.
5. find_index searches for the index. It returns -1 if the key is not found.
6. The index is displayed if found.

Runtime Test Cases


Case 1:
The linked list: 4 -3 1 0 9 11
What data item would you like to search for? 9
9 is at index 4.

Case 2:
The linked list: 4 -3 1 0 9 11
What data item would you like to search for? 11
11 is at index 5.

Case 3:
The linked list: 4 -3 1 0 9 11
What data item would you like to search for? 3
3 was not found.

Python Program to Display the Nodes of a Linked List in


Reverse using Recursion
This is a Python program to display the nodes of a linked list in reverse using recursion.

Problem Description
The program creates a linked list using data items input from the user and displays it in
reverse.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define methods display_reversed and display_reversed_helper.
5. display_reversed calls display_reversed_helper to display the list recursively in reverse.
6. Create an instance of LinkedList, append data to it and display the list in reverse order.

Program/Source Code
Here is the source code of a Python program to display the nodes of a linked list in reverse
using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display_reversed(self):
self.display_reversed_helper(self.head)

def display_reversed_helper(self, current):


if current is None:
return

self.display_reversed_helper(current.next)
print(current.data, end = ' ')

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)

print('The reversed linked list: ', end = '')


a_llist.display_reversed()
Program Explanation
1. An instance of LinkedList is created.
2. The user is asked for the number of elements they would like to add. This is stored in n.
3. Using a loop, data from the user is appended to the linked list n times.
4. The linked list is displayed in reverse by calling the method display_reversed.

Runtime Test Cases


Case 1:
How many elements would you like to add? 5
Enter data item: 3
Enter data item: 8
Enter data item: 14
Enter data item: 2
Enter data item: 1
The reversed linked list: 1 2 14 8 3

Case 2:
How many elements would you like to add? 1
Enter data item: 3
The reversed linked list: 3

Case 3:
How many elements would you like to add? 2
Enter data item: 0
Enter data item: 1
The reversed linked list: 1 0

Python Program to Display all the Nodes in a Linked List using


Recursion
This is a Python program to display the nodes of a linked list using recursion.

Problem Description
The program creates a linked list using data items input from the user and displays it.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define methods display and display_helper.
5. display calls display_helper to display the linked list recursively.
6. Create an instance of LinkedList, append data to it and display the list.

Program/Source Code
Here is the source code of a Python program to display the nodes of a linked list using
recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
self.display_helper(self.head)

def display_helper(self, current):


if current is None:
return

print(current.data, end = ' ')


self.display_helper(current.next)

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)

print('The linked list: ', end = '')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is asked for the number of elements they would like to add. This is stored in n.
3. Using a loop, data from the user is appended to the linked list n times.
4. The linked list is displayed by calling the method display.

Runtime Test Cases


Case 1:
How many elements would you like to add? 3
Enter data item: 7
Enter data item: 2
Enter data item: 1
The linked list: 7 2 1

Case 2:
How many elements would you like to add? 1
Enter data item: 2
The linked list: 2

Case 3:
How many elements would you like to add? 5
Enter data item: 4
Enter data item: 2
Enter data item: 3
Enter data item: 5
Enter data item: 1
The linked list: 4 2 3 5 1

Python Program to Display the Nodes of a Linked List in


Reverse without using Recursion
This is a Python program to display the nodes of a linked list in reverse without using
recursion.
Problem Description
The program creates a linked list using data items input from the user and displays it in
reverse.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define the method display_reversed.
5. display_reversed uses the variable end_node to keep track of the last node that was
printed. The variable current then iterates through the list until it reaches the node before
end_node. That node is then displayed.
6. Create an instance of LinkedList, append data to it and display the list in reverse order.

Program/Source Code
Here is the source code of a Python program to display the nodes of a linked list in reverse
without using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display_reversed(self):
end_node = None

while end_node != self.head:


current = self.head
while current.next != end_node:
current = current.next
print(current.data, end = ' ')
end_node = current
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)

print('The reversed linked list: ', end = '')


a_llist.display_reversed()
Program Explanation
1. An instance of LinkedList is created.
2. The user is asked for the number of elements they would like to add. This is stored in n.
3. Using a loop, data from the user is appended to the linked list n times.
4. The linked list is displayed in reverse by calling the method display_reversed.

Runtime Test Cases


Case 1:
How many elements would you like to add? 4
Enter data item: 7
Enter data item: 2
Enter data item: 1
Enter data item: 9
The reversed linked list: 9 1 2 7

Case 2:
How many elements would you like to add? 1
Enter data item: 5
The reversed linked list: 5

Case 3:
How many elements would you like to add? 2
Enter data item: 3
Enter data item: 1
The reversed linked list: 1 3

3. Python Examples on Implementation of Count, Length and Print Operations on

a Linked List

Python Program to Find the Length of the Linked List using


Recursion
This is a Python program to find the length of a linked list using recursion.

Problem Description
The program prompts the user to enter the elements of the linked list to create and then
displays its length.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define method append inside the class LinkedList to append data to the linked list.
4. Define methods length and length_helper.
5. length calls length_helper to find the length of the linked list recursively.
6. Create an instance of LinkedList and prompt the user for its elements.
7. Display the length of the list by calling the method length.

Program/Source Code
Here is the source code of a Python program to find the length of a linked list using
recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def length(self):
return self.length_helper(self.head)

def length_helper(self, current):


if current is None:
return 0
return 1 + self.length_helper(current.next)

a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))

print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted for the elements of the list.
3. The elements are then appended to the linked list.
4. The method length calculates the length of the list.
5. The length is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 3 4 10
The length of the linked list is 3.

Case 2:
Please enter the elements in the linked list: 7
The length of the linked list is 1.

Case 3:
Please enter the elements in the linked list: 3 4 1 -1 3 9
The length of the linked list is 6.

Python Program to Find the Length of the Linked List without


using Recursion
This is a Python program to find the length of a linked list without using recursion.

Problem Description
The program prompts the user to enter the elements of the linked list to create and then
displays its length.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define method append inside the class LinkedList to append data to the linked list.
4. Define method length.
5. The method length uses a loop to iterate over the nodes of the list to calculate its length.
6. Create an instance of LinkedList and prompt the user for its elements.
7. Display the length of the list by calling the method length.

Program/Source Code
Here is the source code of a Python program to find the length of a linked list without using
recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def length(self):
current = self.head
length = 0
while current:
length = length + 1
current = current.next
return length

a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))

print('The length of the linked list is ' + str(a_llist.length()) + '.', end = '')
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted for the elements of the list.
3. The elements are then appended to the linked list.
4. The method length calculates the length of the list.
5. The length is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 8 1
The length of the linked list is 2.

Case 2:
Please enter the elements in the linked list:
The length of the linked list is 0.

Case 3:
Please enter the elements in the linked list: 7 5 9 12
The length of the linked list is 4.
Python Program to Count the Number of Occurrences of an
Element in the Linked List using Recursion
This is a Python program to count the number of occurrences of an element in a linked list
using recursion.

Problem Description
The program prompts the user for a key and displays the number of times the key occurs in
the linked list.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define methods count and count_helper.
5. count calls count_helper to count the linked list recursively.
6. Create an instance of LinkedList, append data to it and display the list.
7. Prompt the user for a key and display the number of times it occurs by calling the method
count.

Program/Source Code
Here is the source code of a Python program to count the number of occurrences of an
element in a linked list using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def count(self, key):


return self.count_helper(self.head, key)

def count_helper(self, current, key):


if current is None:
return 0

if current.data == key:
return 1 + self.count_helper(current.next, key)
else:
return self.count_helper(current.next, key)

a_llist = LinkedList()
for data in [7, 3, 7, 4, 7, 11, 4, 0, 3, 7]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()

key = int(input('Enter data item: '))


count = a_llist.count(key)
print('{0} occurs {1} time(s) in the list.'.format(key, count))
Program Explanation
1. An instance of LinkedList is created.
2. Some elements are appended to the list.
3. The linked list is displayed.
4. The user is prompted for a key to enter.
5. count_helper counts the number of times the key occurs in the list.
6. The count determined is then displayed.

Runtime Test Cases


Case 1:
The linked list: 7 3 7 4 7 11 4 0 3 7
Enter data item: 3
3 occurs 2 time(s) in the list.

Case 2:
The linked list: 7 3 7 4 7 11 4 0 3 7
Enter data item: 7
7 occurs 4 time(s) in the list.

Case 3:
The linked list: 7 3 7 4 7 11 4 0 3 7
Enter data item: 2
2 occurs 0 time(s) in the list.
Python Program to Count the Number of Occurrences of an
Element in the Linked List without using Recursion
This is a Python program to count the number of occurrences of an element in a linked list
without using recursion.

Problem Description
The program prompts the user for a key and displays the number of times the key occurs in
the linked list.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
4. Define method count.
5. count uses a loop and a variable to count the number of occurrences of a key.
6. Create an instance of LinkedList, append data to it and display the list.
7. Prompt the user for a key and display the number of times it occurs by calling the method
count.

Program/Source Code
Here is the source code of a Python program to count the number of occurrences of an
element in a linked list without using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def count(self, key):


current = self.head

count = 0
while current:
if current.data == key:
count = count + 1
current = current.next

return count

a_llist = LinkedList()
for data in [5, 1, 3, 5, 5, 15, 4, 9, 2]:
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
print()

key = int(input('Enter data item: '))


count = a_llist.count(key)
print('{0} occurs {1} time(s) in the list.'.format(key, count))
Program Explanation
1. An instance of LinkedList is created.
2. Some elements are appended to the list.
3. The linked list is displayed.
4. The user is prompted for a key to enter.
5. count counts the number of times the key occurs in the list.
6. The count determined is then displayed.

Runtime Test Cases


Case 1:
The linked list: 5 1 3 5 5 15 4 9 2
Enter data item: 5
5 occurs 3 time(s) in the list.

Case 2:
The linked list: 5 1 3 5 5 15 4 9 2
Enter data item: 3
3 occurs 1 time(s) in the list.

Case 3:
The linked list: 5 1 3 5 5 15 4 9 2
Enter data item: 7
7 occurs 0 time(s) in the list.
Python Program to Print the Alternate Nodes in a Linked List
using Recursion
This is a Python program to print the alternate nodes of a linked list using recursion.

Problem Description
The program creates a linked list using data items input from the user and displays the
alternate data items.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define method append inside the class LinkedList to append data to the linked list.
4. Define methods alternate and alternate_helper.
5. alternate calls alternate_helper to print the alternate nodes of the linked list recursively.
6. Create an instance of LinkedList and prompt the user for its elements.
7. Display the alternate data items of the linked list.

Program/Source Code
Here is the source code of a Python program to print the alternate nodes of a linked list
using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def alternate(self):
self.alternate_helper(self.head)

def alternate_helper(self, current):


if current is None:
return
print(current.data, end = ' ')
if current.next:
self.alternate_helper(current.next.next)

a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))

print('The alternate nodes of the linked list: ', end = '')


a_llist.alternate()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted for the elements of the list.
3. The elements are then appended to the linked list.
4. The method alternate is called to display the alternate nodes of the list.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 7 2 1 40 3 10
The alternate nodes of the linked list: 7 1 3

Case 2:
Please enter the elements in the linked list: 4 9 1
The alternate nodes of the linked list: 4 1

Case 3:
Please enter the elements in the linked list: 3
The alternate nodes of the linked list: 3

Python Program to Print the Alternate Nodes in a Linked List


without using Recursion
This is a Python program to print the alternate nodes of a linked list without using recursion.

Problem Description
The program creates a linked list using data items input from the user and displays the
alternate data items.

Problem Solution
1. Create a class Node.
2. Create a class LinkedList.
3. Define method append inside the class LinkedList to append data to the linked list.
4. Define method alternate.
5. The method alternate uses a loop to iterate over the alternate nodes of the list and
display them.
6. Create an instance of LinkedList and prompt the user for its elements.
7. Display the alternate data items of the linked list.

Program/Source Code
Here is the source code of a Python program to print the alternate nodes of a linked list
without using recursion. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def alternate(self):
current = self.head
while current:
print(current.data, end = ' ')
if current.next is not None:
current = current.next.next
else:
break

a_llist = LinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_llist.append(int(data))

print('The alternate nodes of the linked list: ', end = '')


a_llist.alternate()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted for the elements of the list.
3. The elements are then appended to the linked list.
4. The method alternate is called to display the alternate nodes of the list.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 7 1 4 1 9 10 3
The alternate nodes of the linked list: 7 4 9 3

Case 2:
Please enter the elements in the linked list: 1 2
The alternate nodes of the linked list: 1

Case 3:
Please enter the elements in the linked list: 9
The alternate nodes of the linked list: 9

4. Python Examples on Implementation of other Data Structures using Linked List

Python Program to Implement a Stack using Linked List


This is a Python program to implement a stack using a linked list.

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

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class Stack with instance variable head.
3. The variable head points to the first element in the linked list.
4. Define methods push and pop inside the class Stack.
5. The method push adds a node at the front of the linked list.
6. The method pop returns the data of the node at the front of the linked list and removes
the node. It returns None if there are no nodes.
7. Create an instance of Stack and present a menu to the user to perform operations on the
stack.

Program/Source Code
Here is the source code of a Python program to implement a stack using a linked list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class Stack:
def __init__(self):
self.head = None

def push(self, data):


if self.head is None:
self.head = Node(data)
else:
new_node = Node(data)
new_node.next = self.head
self.head = new_node

def pop(self):
if self.head is None:
return None
else:
popped = self.head.data
self.head = self.head.next
return popped

a_stack = 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':
a_stack.push(int(do[1]))
elif operation == 'pop':
popped = a_stack.pop()
if popped is None:
print('Stack is empty.')
else:
print('Popped value: ', int(popped))
elif operation == 'quit':
break
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.

Runtime Test Cases


Case 1:
push <value>
pop
quit
What would you like to do? push 15
push <value>
pop
quit
What would you like to do? push 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 15
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

Case 2:
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

Python Program to Implement Queue Data Structure using


Linked List
This is a Python program to implement a queue using a linked list.

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 Node with instance variables data and next.
2. Create a class Queue with instance variables head and last.
3. The variable head points to the first element in the linked list while last points to the last
element.
4. Define methods enqueue and dequeue inside the class Queue.
5. The method enqueue adds a node at the end of the linked list.
6. The method dequeue returns the data of the node at the front of the linked list and
removes the node. It returns None if there are no nodes.
7. 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 using a linked list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class Queue:
def __init__(self):
self.head = None
self.last = None

def enqueue(self, data):


if self.last is None:
self.head = Node(data)
self.last = self.head
else:
self.last.next = Node(data)
self.last = self.last.next

def dequeue(self):
if self.head is None:
return None
else:
to_return = self.head.data
self.head = self.head.next
return to_return

a_queue = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
dequeued = a_queue.dequeue()
if dequeued is None:
print('Queue is empty.')
else:
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
Program Explanation
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.

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 4
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 3
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 4
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 5
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 5
enqueue <value>
dequeue
quit
What would you like to do? quit

Python Program to Implement Binary Tree using Linked List


This is a Python program to implement a binary tree using a linked list.

Problem Description
The program creates a binary tree and presents a menu to the user to insert elements into
the tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, inorder and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method inorder displays the inorder traversal.
6. The method search returns a node with a specified key.

Program/Source Code
Here is the source code of a Python program to implement a binary tree using a linked list.
The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

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 insert_left(self, new_node):


self.left = new_node
def insert_right(self, new_node):
self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('quit')

while True:
print('inorder traversal of binary tree: ', end='')
if btree is not None:
btree.inorder()
print()

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to construct the binary tree.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
quit
inorder traversal of binary tree:
What would you like to do? insert 3 at root
inorder traversal of binary tree: 3
What would you like to do? insert 5 left of 3
inorder traversal of binary tree: 5 3
What would you like to do? insert 2 right of 5
inorder traversal of binary tree: 5 2 3
What would you like to do? insert 11 right of 3
inorder traversal of binary tree: 5 2 3 11
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
quit
inorder traversal of binary tree:
What would you like to do? insert 1 at root
inorder traversal of binary tree: 1
What would you like to do? insert 2 left of 1
inorder traversal of binary tree: 2 1
What would you like to do? insert 3 right of 1
inorder traversal of binary tree: 2 1 3
What would you like to do? insert 4 left of 2
inorder traversal of binary tree: 4 2 1 3
What would you like to do? insert 5 right of 2
inorder traversal of binary tree: 4 2 5 1 3
What would you like to do? insert 6 left of 3
inorder traversal of binary tree: 4 2 5 1 6 3
What would you like to do? insert 7 right of 3
inorder traversal of binary tree: 4 2 5 1 6 3 7
What would you like to do? quit

5. Python Examples dealing with the Operations on the Elements of a Linked List
Python Program to Check whether 2 Linked Lists are Same
This is a Python program to check whether two linked lists are the same.

Problem Description
The program creates two linked lists using data items input from the user and checks
whether they are the same.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define a function is_equal which takes two linked lists as arguments.
6. The function is_equal returns True only if the two linked lists are of the same length and
contain the same data items.
7. Create two instances of LinkedList and append data to it.
8. Check whether they are the same.

Program/Source Code
Here is the source code of a Python program to check whether two linked lists are the
same. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def is_equal(llist1, llist2):


current1 = llist1.head
current2 = llist2.head
while (current1 and current2):
if current1.data != current2.data:
return False
current1 = current1.next
current2 = current2.next
if current1 is None and current2 is None:
return True
else:
return False

llist1 = LinkedList()
llist2 = LinkedList()

data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))

data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))

if is_equal(llist1, llist2):
print('The two linked lists are the same.')
else:
print('The two linked list are not the same.', end = '')
Program Explanation
1. Two instances of LinkedList are created.
2. The user is prompted to enter the data items for the two lists.
3. The function is_equal determines whether the two linked lists are the same.
4. This result is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the first linked list: 5 8 10 12
Please enter the elements in the second linked list: 5 8 10 12
The two linked lists are the same.

Case 2:
Please enter the elements in the first linked list: 12 3 4 5 0
Please enter the elements in the second linked list: 12 3
The two linked list are not the same.

Case 3:
Please enter the elements in the first linked list: 4 1
Please enter the elements in the second linked list: 2 19 4
The two linked list are not the same.
Python Program to Detect the Cycle in a Linked List
This is a Python program to check whether a linked list has a cycle.

Problem Description
The program creates a linked list using data items input from the user and determines
whether it has a cycle.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define method get_node which takes an index as argument and returns the node at that
index.
6. Define a function has_cycle which returns True if the linked list has a cycle.
7. The function has_cycle uses the Floyd’s cycle-finding algorithm.
8. In this algorithm, one pointer traverses the list one node at a time while another pointer
traverses it two nodes at a time. If the two pointers equal before the faster pointer reaches
None, then the list has a cycle.
9. Create an instance of LinkedList, append data to it and determine whether it has a cycle.

Program/Source Code
Here is the source code of a Python program to check whether a linked list has a cycle.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def get_node(self, index):


current = self.head
for i in range(index):
current = current.next
if current is None:
return None
return current

def has_cycle(llist):
slow = llist.head
fast = llist.head
while (fast != None and fast.next != None):
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

length = len(data_list)
if length != 0:
values = '0-' + str(length - 1)
last_ptr = input('Enter the index [' + values + '] of the node'
' to which you want the last node to point'
' (enter nothing to make it point to None): ').strip()
if last_ptr == '':
last_ptr = None
else:
last_ptr = a_llist.get_node(int(last_ptr))
a_llist.last_node.next = last_ptr

if has_cycle(a_llist):
print('The linked list has a cycle.')
else:
print('The linked list does not have a cycle.')
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is then prompted to select which node they would like the last node to point to
or whether they would like it to point to None.
4. The function has_cycle is called with the linked list as argument to determine whether it
has a cycle.
5. The result is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 2 3
Enter the index [0-2] of the node to which you want the last node to point (enter
nothing to make it point to None): 0
The linked list has a cycle.

Case 2:
Please enter the elements in the linked list: 4 5
Enter the index [0-1] of the node to which you want the last node to point (enter
nothing to make it point to None): 1
The linked list has a cycle.

Case 3:
Please enter the elements in the linked list: 9 1 4 5
Enter the index [0-3] of the node to which you want the last node to point (enter
nothing to make it point to None):
The linked list does not have a cycle.

Python Program to Find the Largest Element in a Doubly Linked


List
This is a Python program to find the largest element in a doubly linked list.

Problem Description
The program creates a doubly linked list and finds the largest element in the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class DoublyLinkedList with instance variables first and last.
3. The variable first points to the first element in the doubly linked list while last points to the
last element.
4. Define methods insert_at_end and append.
5. The method insert_at_end inserts a node at the last position of the list.
6. The method append takes a data item as argument and appends a node with that data
item to the list.
7. The function find_largest takes a linked list as argument and returns the largest element
in the list. It returns None if the list is empty.
8. Create an instance of DoublyLinkedList, append data to it and find the largest element in
it.
Program/Source Code
Here is the source code of a Python program to find the largest element in a doubly linked
list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class DoublyLinkedList:
def __init__(self):
self.first = None
self.last = None

def append(self, data):


self.insert_at_end(Node(data))

def insert_at_end(self, new_node):


if self.last is None:
self.last = new_node
self.first = new_node
else:
new_node.prev = self.last
self.last.next = new_node
self.last = new_node

def find_largest(dllist):
if dllist.first is None:
return None
largest = dllist.first.data
current = dllist.first.next
while current:
if current.data > largest:
largest = current.data
current = current.next
return largest

a_dllist = DoublyLinkedList()

data_list = input('Please enter the elements in the doubly linked list: ').split()
for data in data_list:
a_dllist.append(int(data))

largest = find_largest(a_dllist)
if largest:
print('The largest element is {}.'.format(largest))
else:
print('The list is empty.')
Program Explanation
1. An instance of DoublyLinkedList is created.
2. The user is prompted to enter the data items of the list.
3. The largest element is found by calling find_largest.
4. The result is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the doubly linked list: 5 10 9 3
The largest element is 10.

Case 2:
Please enter the elements in the doubly linked list:
The list is empty.

Case 3:
Please enter the elements in the doubly linked list: 234 10 4 200
The largest element is 234.

Python Program to Add Corresponding Positioned Elements of


2 Linked Lists
This is a Python program to add the corresponding elements of two linked lists.

Problem Description
The program creates two linked lists using data items input from the user and creates a
linked list consisting of the sum of data items of the two lists.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define a function add_linked_lists which takes two linked lists as arguments.
6. The function add_linked_lists returns a linked list which has its elements as the sum of
the data items of the two lists passed to it. If one list is shorter, then the rest of the elements
are appended from the longer list.
7. Create two instances of LinkedList and append data to it.
8. Create the sum linked list and display it.
Program/Source Code
Here is the source code of a Python program to add the corresponding elements of two
linked lists. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

def add_linked_lists(llist1, llist2):


sum_llist = LinkedList()
current1 = llist1.head
current2 = llist2.head
while (current1 and current2):
sum = current1.data + current2.data
sum_llist.append(sum)
current1 = current1.next
current2 = current2.next
if current1 is None:
while current2:
sum_llist.append(current2.data)
current2 = current2.next
else:
while current1:
sum_llist.append(current1.data)
current1 = current1.next
return sum_llist

llist1 = LinkedList()
llist2 = LinkedList()
data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))

data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))

sum_llist = add_linked_lists(llist1, llist2)

print('The sum linked list: ', end = '')


sum_llist.display()
Program Explanation
1. Two instances of LinkedList are created.
2. The user is prompted to enter the data items for the two lists.
3. The function add_linked_lists is called to create the sum linked list.
4. This list is then displayed using the display method.

Runtime Test Cases


Case 1:
Please enter the elements in the first linked list: 1 9 10 15
Please enter the elements in the second linked list: 2 5 4
The sum linked list: 3 14 14 15

Case 2:
Please enter the elements in the first linked list: 3 4 5
Please enter the elements in the second linked list:
The sum linked list: 3 4 5

Case 3:
Please enter the elements in the first linked list: 7 10
Please enter the elements in the second linked list: 6 5 4 3 2
The sum linked list: 13 15 4 3 2

Python Program to Find the first Common Element between the


2 given Linked Lists
This is a Python program to find the first element of the first linked list that is common to
both the lists.

Problem Description
The program creates two linked lists using data items input from the user and determines
the first element in the first linked list that is in both the lists.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define a function first_common which takes two linked lists as arguments.
6. The function first_common returns the first element in the first linked list that is common
to both the linked lists using two nested loops.
7. Create two instances of LinkedList and append data to it.
8. Find the common element and display the result.

Program/Source Code
Here is the source code of a Python program to find the first common element in two linked
lists.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def first_common(llist1, llist2):


current1 = llist1.head
while current1:
data = current1.data
current2 = llist2.head
while current2:
if data == current2.data:
return data
current2 = current2.next
current1 = current1.next
return None
llist1 = LinkedList()
llist2 = LinkedList()

data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
llist1.append(int(data))

data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
llist2.append(int(data))

common = first_common(llist1, llist2)

if common:
print('The element that appears first in the first linked list that'
' is common to both is {}.'.format(common))
else:
print('The two lists have no common elements.')
Program Explanation
1. Two instances of LinkedList are created.
2. The user is prompted to enter the data items for the two lists.
3. The function first_common is called to find the common element.
4. The result is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the first linked list: 4 5 1 3 10
Please enter the elements in the second linked list: 8 3 40 1
The element that appears first in the first linked list that is common to both is 1.

Case 2:
Please enter the elements in the first linked list: 1 4 5
Please enter the elements in the second linked list: 3 10
The two lists have no common elements.

Case 3:
Please enter the elements in the first linked list: 6 8 9
Please enter the elements in the second linked list: 7 10 6 4 9 8
The element that appears first in the first linked list that is common to both is 6

6. Python Examples on Print, Reverse and Read Operations

Python Program to Remove Duplicates from a Linked List


This is a Python program to remove duplicates from a linked list.
Problem Description
The program creates a linked list and removes duplicates from it.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append, get_prev_node, remove and display.
5. The method append takes a data item as argument and appends a node with that data
item to the list.
6. The method get_prev_node takes a reference node as argument and returns the
previous node. It returns None when the reference node is the first node.
7. The method remove takes a node as argument and removes it from the list.
8. The method display traverses the list from the first node and prints the data of each node.
9. Define a function remove_duplicates which takes a linked list as argument and removes
duplicates from it.
10. The function remove_duplicates uses two nested loops to remove duplicate nodes.
11. Create an instance of LinkedList, remove duplicate nodes and display the list.

Program/Source Code
Here is the source code of a Python program to remove duplicates from a linked list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def remove(self, node):


prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def remove_duplicates(llist):
current1 = llist.head
while current1:
data = current1.data
current2 = current1.next
while current2:
if current2.data == data:
llist.remove(current2)
current2 = current2.next
current1 = current1.next

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

remove_duplicates(a_llist)

print('The list with duplicates removed: ')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The function remove_duplicates is called to remove duplicates from the list.
4. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 5 2 1 4 5 4 5
The list with duplicates removed:
1 5 2 4
Case 2:
Please enter the elements in the linked list: 3 4 1
The list with duplicates removed:
3 4 1

Case 3:
Please enter the elements in the linked list: 1 3 3 14 5 1 0
The list with duplicates removed:
1 3 14 5 0

Python Program to Reverse a Linked List


This is a Python program to reverse a linked list.

Problem Description
The program creates a linked list and reverses it.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display.
5. The method append takes a data item as argument and appends a node with that data
item to the list.
6. The method display traverses the list from the first node and prints the data of each node.
7. Define a function reverse_llist which takes a linked list as argument and reverses it.
8. The function reverse_llist iterates through the list using three pointers to reverse it.
9. Create an instance of LinkedList, reverse the list and display it.

Program/Source Code
Here is the source code of a Python program to reverse a linked list. The program output is
shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def reverse_llist(llist):
before = None
current = llist.head
if current is None:
return
after = current.next
while after:
current.next = before
before = current
current = after
after = after.next
current.next = before
llist.head = current

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

reverse_llist(a_llist)

print('The reversed list: ')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The function reverse_llist is called to reverse the list.
4. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 7 1 30 4
The reversed list:
4 30 1 7
Case 2:
Please enter the elements in the linked list: 3
The reversed list:
3

Case 3:
Please enter the elements in the linked list: 1 2
The reversed list:
2 1

Python Program to Reverse only First N Elements of a Linked


List
This is a Python program to reverse the first N elements of a linked list.

Problem Description
The program creates a linked list and reverses its first N elements.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display.
5. The method append takes a data item as argument and appends a node with that data
item to the list.
6. The method display traverses the list from the first node and prints the data of each node.
7. Define a function reverse_llist which takes a linked list as argument and a number n.
8. The function reverse_llist iterates through the list using three pointers to reverse the first
n elements.
9. Create an instance of LinkedList, reverse the first n elements of the list and display it.

Program/Source Code
Here is the source code of a Python program to reverse the first N elements of a linked list.
The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def reverse_llist(llist, n):


if n == 0:
return
before = None
current = llist.head
if current is None:
return
after = current.next
for i in range(n):
current.next = before
before = current
current = after
if after is None:
break
after = after.next
llist.head.next = current
llist.head = before

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))
n = int(input('Enter the number of elements you want to reverse in the list: '))

reverse_llist(a_llist, n)

print('The new list: ')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is asked for n, the number of elements they would like to reverse.
4. The function reverse_llist is called to reverse the first n elements.
5. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 2 3 4 5 6 7
Enter the number of elements you want to reverse in the list: 4
The new list:
4 3 2 1 5 6 7

Case 2:
Please enter the elements in the linked list: 7 2 4
Enter the number of elements you want to reverse in the list: 1
The new list:
7 2 4

Case 3:
Please enter the elements in the linked list: 8 3 2
Enter the number of elements you want to reverse in the list: 3
The new list:
2 3 8

Python Program to Print Middle most Node of a Linked List


This is a Python program to print the middle node(s) of a linked list.

Problem Description
The program creates a linked list using data items input from the user and prints the middle
node(s) of the linked list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define a function print_middle that prints the middle element(s) of the list.
6. The function print_middle iterates through the list to find its length and then iterates again
to half its length. If the length of the list is even, it prints two middle elements.
7. Create an instance of LinkedList, append data to it and print its middle element(s).
Program/Source Code
Here is the source code of a Python program to print the middle element(s) of a linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def print_middle(llist):
current = llist.head
length = 0
while current:
current = current.next
length = length + 1

current = llist.head
for i in range((length - 1)//2):
current = current.next

if current:
if length % 2 == 0:
print('The two middle elements are {} and {}.'
.format(current.data, current.next.data))
else:
print('The middle element is {}.'.format(current.data))
else:
print('The list is empty.')

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

print_middle(a_llist)
Program Explanation
1. An instances of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The function print_middle is called to print the middle element(s) of the list.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 2 3 4 5 6 7 8
The two middle elements are 4 and 5.

Case 2:
Please enter the elements in the linked list: 5
The middle element is 5.

Case 3:
Please enter the elements in the linked list: 3 1 0 4 2
The middle element is 0.

Python Program to Print Nth Node from the last of a Linked List
This is a Python program to print the Nth node from the end of a linked list.

Problem Description
The program creates a linked list and prints the Nth node from the end of the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define method append.
5. The method append appends a node with the data item passed to the end of the list.
6. Define the function length_llist which takes a linked list as argument and returns its
length.
7. Define the function return_n_from_last which takes a linked list as argument and a
number n.
8. The function return_n_from_last returns the data item of the node which is n nodes from
the end of the list.
9. Create an instance of LinkedList, append data to it and print the nth-last element of the
list.

Program/Source Code
Here is the source code of a Python program to print the Nth-last node of the list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def length_llist(llist):
length = 0
current = llist.head
while current:
current = current.next
length = length + 1
return length

def return_n_from_last(llist, n):


l = length_llist(llist)
current = llist.head
for i in range(l - n):
current = current.next
return current.data

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

n = int(input('The nth element from the end will be printed. Please enter n: '))
value = return_n_from_last(a_llist, n)

print('The nth element from the end: {}'.format(value))


Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is asked to enter the value of n.
4. The function return_n_from_last is called to get the value of the nth-last element of the
list.
5. This value is then printed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 10 20 40 50 60
The nth element from the end will be printed. Please enter n: 3
The nth element from the end: 40

Case 2:
Please enter the elements in the linked list: 4 23 3
The nth element from the end will be printed. Please enter n: 1
The nth element from the end: 3

Case 3:
Please enter the elements in the linked list: 1 2
The nth element from the end will be printed. Please enter n: 2
The nth element from the end: 1

7. Python Examples on Binary Tree Implementation using Linked List

Python Program to Find Intersection & Union of 2 Linked Lists


This is a Python program to find the union and intersection of two linked lists.

Problem Description
The program creates two linked lists and finds their union and intersection.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the linked list.
4. Define methods get_prev_node, duplicate, insert_at_end, remove and display.
5. The method get_prev_node takes a reference node as argument and returns the
previous node. It returns None when the reference node is the first node.
6. The method insert_at_end inserts a node at the last position of the list.
7. The method remove takes a node as argument and removes it from the list.
8. The method display traverses the list from the first node and prints the data of each node.
9. The method duplicate creates a copy of the list and returns it.
10. Define the function remove_duplicates which removes duplicate elements from the list
passed as argument.
11. Define the function find_union which returns the union of the two linked lists passed to it.
12. Define the function find_intersection which returns the intersection of the two linked lists
passed to it.
13. Create two instances of LinkedList, append data to them and find their union and
intersection.

Program/Source Code
Here is the source code of a Python program to find the union and intersection of two linked
lists. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def duplicate(self):
copy = LinkedList()
current = self.head
while current:
node = Node(current.data)
copy.insert_at_end(node)
current = current.next
return copy

def insert_at_end(self, new_node):


if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node

def remove(self, node):


prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def remove_duplicates(llist):
current1 = llist.head
while current1:
current2 = current1.next
data = current1.data
while current2:
temp = current2
current2 = current2.next
if temp.data == data:
llist.remove(temp)
current1 = current1.next

def find_union(llist1, llist2):


if llist1.head is None:
union = llist2.duplicate()
remove_duplicates(union)
return union
if llist2.head is None:
union = llist1.duplicate()
remove_duplicates(union)
return union

union = llist1.duplicate()
last_node = union.head
while last_node.next is not None:
last_node = last_node.next
llist2_copy = llist2.duplicate()
last_node.next = llist2_copy.head
remove_duplicates(union)

return union

def find_intersection(llist1, llist2):


if (llist1.head is None or llist2.head is None):
return LinkedList()

intersection = LinkedList()
current1 = llist1.head
while current1:
current2 = llist2.head
data = current1.data
while current2:
if current2.data == data:
node = Node(data)
intersection.insert_at_end(node)
break
current2 = current2.next
current1 = current1.next
remove_duplicates(intersection)

return intersection

a_llist1 = LinkedList()
a_llist2 = LinkedList()
data_list = input('Please enter the elements in the first linked list: ').split()
for data in data_list:
node = Node(int(data))
a_llist1.insert_at_end(node)
data_list = input('Please enter the elements in the second linked list: ').split()
for data in data_list:
node = Node(int(data))
a_llist2.insert_at_end(node)

union = find_union(a_llist1, a_llist2)


intersection = find_intersection(a_llist1, a_llist2)

print('Their union: ')


union.display()
print()
print('Their intersection: ')
intersection.display()
print()
Program Explanation
1. Two instances of LinkedList are created.
2. The user is prompted to enter the data items for the two lists.
3. The functions find_union and find_intersection are called to find their union and
intersection respectively.
4. These are then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the first linked list: 1 2 3 4 5
Please enter the elements in the second linked list: 3 4 5 6 7 8
Their union:
1 2 3 4 5 6 7 8
Their intersection:
3 4 5

Case 2:
Please enter the elements in the first linked list:
Please enter the elements in the second linked list: 7 8
Their union:
7 8
Their intersection:

Case 3:
Please enter the elements in the first linked list: 8 4 2 1 10 3 4 7 8
Please enter the elements in the second linked list: 5 6 3 4 3 2 5 2 8
Their union:
8 4 2 1 10 3 7 5 6
Their intersection:
8 4 2 3

8. Python Examples on Interchange and Modify Operations

Python Program to Solve Josephus Problem using Linked List


This is a Python program to solve the Josephus problem using a linked list.

Problem Description
The program uses a circular single linked list to solve the Josephus problem.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the circular linked list.
4. Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_end,
remove and append.
5. The method get_node takes an index as argument and traverses the list from a specified
node that many times to return the node at that index. The specified node is given by the
second argument passed to it.
6. The method get_prev_node takes a reference node as argument and returns the
previous node.
7. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
8. The methods insert_at_end inserts a node at the last position of the list.
9. The method remove takes a node as argument and removes it from the list.
10. The method appends a node with the data item passed to the end of the list.
11. Define function has_one_node which returns True only if the circular list passed to it has
only one node.
12. Define function get_josephus_solution which takes a circular linked list and a number k
as argument.
13. The function get_josephus_solution returns the solution to the Josephus problem where
the people are represented by the nodes in the circular linked list and every kth person is
executed.
14. Create an instance of CircularLinkedList and find the solution to the Josephus problem
for a given k.

Program/Source Code
Here is the source code of a Python program to solve the Josephus problem using a linked
list. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def append(self, data):


node = Node(data)
self.insert_at_end(node)

def get_node(self, index, start):


if self.head is None:
return None
current = start
for i in range(index):
current = current.next
return current

def get_prev_node(self, ref_node):


if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current

def insert_after(self, ref_node, new_node):


new_node.next = ref_node.next
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)

def insert_at_end(self, new_node):


if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)

def remove(self, node):


if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)
prev_node.next = node.next
if self.head == node:
self.head = node.next

def has_one_node(cllist):
if cllist.head.next == cllist.head:
return True
else:
return False

def get_josephus_solution(cllist, k):


if cllist.head is None:
return None
start = cllist.head
while not has_one_node(cllist):
to_remove = cllist.get_node(k - 1, start)
start = to_remove.next
cllist.remove(to_remove)
return cllist.head.data

a_cllist = CircularLinkedList()
n = int(input('Input number of people: '))
k = int(input('The kth person will be executed. Input k: '))
for i in range(1, n + 1):
a_cllist.append(i)

ans = get_josephus_solution(a_cllist, k)
print('The person at position {} won\'t be killed.'.format(ans))
Program Explanation
1. The user is prompted to enter the values of n and k.
2. An instance of CircularLinkedList is created with n nodes where the nodes have values
from 1 to n.
3. The function get_josephus_solution is called with the circular linked list and k as
arguments.
4. The return value is the position of the person who won’t be executed in the Josephus
problem.

Runtime Test Cases


Case 1:
Input number of people: 5
The kth person will be executed. Input k: 3
The person at position 4 won't be killed.

Case 2:
Input number of people: 15
The kth person will be executed. Input k: 7
The person at position 5 won't be killed.

Case 3:
Input number of people: 8
The kth person will be executed. Input k: 2
The person at position 1 won't be killed.

Python Program to Interchange two Elements of the List without


touching the Key Field
This is a Python program to interchange two nodes in a linked list.

Problem Description
The program creates a single linked list and allows the user to interchange two nodes in the
list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods get_node, get_prev_node, append and display.
5. get_node takes an index as argument and traverses the list from the first node that many
times to return the node at that index.
6. get_prev_node takes a reference node as argument and returns the previous node.
7. The method display traverses the list from the first node and prints the data of each node.
8. The method append appends a node with the data item passed to the end of the list.
9. Define the function interchange which takes a linked list and two indices n and m as
arguments.
10. The function interchange interchanges the nodes at indices n and m.
11. Create an instance of LinkedList, append data to it and perform the exchange operation.

Program/Source Code
Here is the source code of a Python program to exchange two elements in a linked list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def get_node(self, index):


current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def interchange(llist, n, m):


node1 = llist.get_node(n)
node2 = llist.get_node(m)
prev_node1 = llist.get_prev_node(node1)
prev_node2 = llist.get_prev_node(node2)
if prev_node1 is not None:
prev_node1.next = node2
else:
llist.head = node2
if prev_node2 is not None:
prev_node2.next = node1
else:
llist.head = node1
temp = node2.next
node2.next = node1.next
node1.next = temp

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

ans = input('Please enter the two indices of the two elements that'
' you want to exchange: ').split()
n = int(ans[0])
m = int(ans[1])

interchange(a_llist, n, m)

print('The new list: ')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is asked to enter n and m, the indices of the nodes which will be interchanged.
4. The function interchange is called to perform the exchange operation.
5. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 2
Please enter the two indices of the two elements that you want to exchange: 0 1
The new list:
2 1

Case 2:
Please enter the elements in the linked list: 4 5 1
Please enter the two indices of the two elements that you want to exchange: 1 2
The new list:
4 1 5

Case 3:
Please enter the elements in the linked list: 3 1 30 4 5 10 23
Please enter the two indices of the two elements that you want to exchange: 2 5
The new list:
3 1 10 4 5 30 23
Python Program to Modify the Linked List such that All Even
Numbers appear before all the Odd Numbers in the Modified
Linked List
This is a Python program to move all even numbers before all the odd numbers in a linked
list.

Problem Description
The program creates a linked list and modifies the linked list so that all even numbers
appear before all the odd numbers in the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods get_node, get_prev_node, insert_at_beg, remove, append and display.
5. The method get_node takes an index as argument and traverses the list from the first
node that many times to return the node at that index.
6. The method get_prev_node takes a reference node as argument and returns the
previous node.
7. The method display traverses the list from the first node and prints the data of each node.
8. The method append appends a node with the data item passed to the end of the list.
9. The method insert_at_beg prepends a node to the list.
10. The method remove removes the node passed to it from the list.
11. Define the function move_even_before_odd which takes a linked list as argument.
12. The function move_even_before_odd removes the even elements in the list and
prepends them to the front.
13. Create an instance of LinkedList, append data to it and modify the list such that all even
numbers appear before the odd numbers.

Program/Source Code
Here is the source code of a Python program to move all even numbers before all the odd
numbers in a linked list. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

def get_node(self, index):


current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def insert_at_beg(self, new_node):


if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node

def remove(self, node):


prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next

def move_even_before_odd(llist):
current = llist.head
while current:
temp = current.next
if current.data % 2 == 0:
llist.remove(current)
llist.insert_at_beg(current)
current = temp

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

move_even_before_odd(a_llist)

print('The new list: ')


a_llist.display()
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The function move_even_before_odd is called to move all the even numbers before all
the odd numbers in the list.
4. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 3 1 0 4 30 12
The new list:
12 30 4 0 3 1

Case 2:
Please enter the elements in the linked list: 1 2
The new list:
2 1

Case 3:
Please enter the elements in the linked list: 1 2 3 4 5
The new list:
4 2 1 3 5

Python Program to Interchange the two Adjacent Nodes given a


circular Linked List
This is a Python program to interchange two adjacent nodes of a circular linked list.

Problem Description
The program creates a circular single linked list and allows the user to interchange two
adjacent nodes in the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class CircularLinkedList with instance variable head.
3. The variable head points to the first element in the circular single linked list.
4. Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_end,
append and display.
5. The method get_node takes an index as argument and traverses the list from the first
node that many times to return the node at that index. It stops if it reaches the first node
again.
6. The method get_prev_node takes a reference node as argument and returns the
previous node.
7. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
8. The method insert_at_end inserts a node at the last position of the list.
9. The method display traverses the list from the first node and prints the data of each node.
It stops when it reaches the first node again.
10. The method appends a node with the data item passed to the end of the list.
11. Define the function interchange which takes a linked list as argument and an index n.
12. The function interchange exchanges the nodes at indices n and n + 1 of the list.
13. Create an instance of CircularLinkedList, append data to it and perform the exchange
operation.

Program/Source Code
Here is the source code of a Python program to interchange two adjacent nodes of a
circular linked list. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def get_node(self, index):


if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current

def get_prev_node(self, ref_node):


if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current

def insert_after(self, ref_node, new_node):


new_node.next = ref_node.next
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)

def insert_at_end(self, new_node):


if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)

def append(self, data):


self.insert_at_end(Node(data))

def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break

def interchange(llist, n):


current = llist.get_node(n)
current2 = current.next
if current2.next != current:
before = llist.get_prev_node(current)
after = current2.next
before.next = current2
current2.next = current
current.next = after
if llist.head == current:
llist.head = current2
elif llist.head == current2:
llist.head = current

a_cllist = CircularLinkedList()
data_list = input('Please enter the elements in the linked list: ').split()
for data in data_list:
a_cllist.append(int(data))

n = int(input('The nodes at indices n and n+1 will be interchanged.'


' Please enter n: '))

interchange(a_cllist, n)

print('The new list: ')


a_cllist.display()
Program Explanation
1. An instance of CircularLinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is asked to enter n, the index of the node which will be interchanged with the
node following it.
4. The function interchange is called to perform the exchange operation.
5. The linked list is displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 1 2
The nodes at indices n and n+1 will be interchanged. Please enter n: 0
The new list:
2 1

Case 2:
Please enter the elements in the linked list: 4 1 5
The nodes at indices n and n+1 will be interchanged. Please enter n: 2
The new list:
5 1 4

Case 3:
Please enter the elements in the linked list: 3 18 40 1 6
The nodes at indices n and n+1 will be interchanged. Please enter n: 3
The new list:
3 18 40 6 1

9. Python Examples on Singly Linked Lists

Python Program to Illustrate the Operations of Singly Linked


List
This is a Python program to illustrate the operations of a singly linked list.
Problem Description
The program creates a singly linked list and presents the user with a menu to perform
various operations on the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the singly linked list.
4. Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_beg,
insert_at_end, remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many
times to return the node at that index.
6. get_prev_node takes a reference node as argument and returns the previous node. It
returns None when the reference node is the first node.
7. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
8. The methods insert_at_beg and insert_at_end insert a node at the first or last position of
the list.
9. The method remove takes a node as argument and removes it from the list.
10. The method display traverses the list from the first node and prints the data of each
node.
11. Create an instance of LinkedList and present the user with a menu to perform
operations on the list.

Program/Source Code
Here is the source code of a Python program to create a singly linked list and illustrate its
operations. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None

def get_node(self, index):


current = self.head
for i in range(index):
if current is None:
return None
current = current.next
return current

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def insert_after(self, ref_node, new_node):


new_node.next = ref_node.next
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)

def insert_at_beg(self, new_node):


if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node

def insert_at_end(self, new_node):


if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node

def remove(self, node):


prev_node = self.get_prev_node(node)
if prev_node is None:
self.head = self.head.next
else:
prev_node.next = node.next

def display(self):
current = self.head
while current:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()

print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')

while True:
print('The list: ', end = '')
a_llist.display()
print()
do = input('What would you like to do? ').split()

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

if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_llist.insert_at_beg(new_node)
elif position == 'end':
a_llist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_llist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_llist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_llist.insert_before(ref_node, new_node)

elif operation == 'remove':


index = int(do[1])
node = a_llist.get_node(index)
if node is None:
print('No such index.')
continue
a_llist.remove(node)

elif operation == 'quit':


break
Program Explanation
1. An instance of LinkedList is created.
2. The user is presented with a menu to perform various operations on the list.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 7 at beg
The list: 7
What would you like to do? insert 3 at end
The list: 7 3
What would you like to do? insert 1 after 0
The list: 7 1 3
What would you like to do? insert 9 before 2
The list: 7 1 9 3
What would you like to do? remove 2
The list: 7 1 3
What would you like to do? insert 12 at end
The list: 7 1 3 12
What would you like to do? remove 0
The list: 1 3 12
What would you like to do? quit

Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 5 after 0
No such index.
The list:
What would you like to do? insert 3 at end
The list: 3
What would you like to do? insert 1 after 0
The list: 3 1
What would you like to do? insert 2 before 1
The list: 3 2 1
What would you like to do? insert 0 at end
The list: 3 2 1 0
What would you like to do? remove 3
The list: 3 2 1
What would you like to do? remove 2
The list: 3 2
What would you like to do? quit

Python Program to Check whether a Singly Linked List is a


Palindrome
This is a Python program to check whether a singly linked list is a palindrome.

Problem Description
The program creates a linked list using data items input from the user and determines
whether it is a palindrome.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the linked list while last_node points to the
last.
4. Define methods append and display inside the class LinkedList to append data and
display the linked list respectively.
5. Define method get_prev_node which takes a reference node as argument and returns
the node before it.
6. Define a function is_palindrome which returns True if the linked list passed to it is a
palindrome.
7. The function is_palindrome iterates through the linked list from the start and the last node
towards the middle to check if the list is a palindrome.
8. Create an instance of LinkedList, append data to it and determine whether it is a
palindrome.

Program/Source Code
Here is the source code of a Python program to check whether a singly linked list is a
palindrome.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def get_prev_node(self, ref_node):


current = self.head
while (current and current.next != ref_node):
current = current.next
return current

def is_palindrome(llist):
start = llist.head
end = llist.last_node
while (start != end and end.next != start):
if start.data != end.data:
return False
start = start.next
end = llist.get_prev_node(end)
return True

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

if is_palindrome(a_llist):
print('The linked list is palindromic.')
else:
print('The linked list is not palindromic.')
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The function is_palindrome is called with the list as argument to determine whether it is a
palindrome.
4. The result is then displayed.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 7 8 1 8 7
The linked lists is palindromic.

Case 2:
Please enter the elements in the linked list: 1 2 3 3 2 1
The linked list is palindromic.

Case 3:
Please enter the elements in the linked list: 1 4 5 4 5 1
The linked list is not palindromic.

Python Program to Convert a given Singly Linked List to a


Circular List
This is a Python program to convert a given singly linked list to a circular list.
Problem Description
The program creates a singly linked list and converts it into a circular list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variables head and last_node.
3. The variable head points to the first element in the single linked list while last_node points
to the last.
4. Define method append to append data items to the list.
5. Define function convert_to_circular which takes a singly linked list as argument.
6. The function convert_to_circular converts the list passed into a circular list by making the
last node point to the first.
7. Define function print_last_node_points_to to display what the last node of the passed
linked list points to.
8. Create an instance of LinkedList, append data to it and convert it to a circular list.

Program/Source Code
Here is the source code of a Python program to convert a singly linked list to a circular list.
The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def convert_to_circular(llist):
if llist.last_node:
llist.last_node.next = llist.head

def print_last_node_points_to(llist):
last = llist.last_node
if last is None:
print('List is empty.')
return
if last.next is None:
print('Last node points to None.')
else:
print('Last node points to element with data {}.'.format(last.next.data))

a_llist = LinkedList()

data_list = input('Please enter the elements in the linked list: ').split()


for data in data_list:
a_llist.append(int(data))

print_last_node_points_to(a_llist)

print('Converting linked list to a circular linked list...')


convert_to_circular(a_llist)

print_last_node_points_to(a_llist)
Program Explanation
1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The singly linked list is converted to a circular list by passing the list to the function
convert_to_circular.
4. The user is shown to what the last node of the list points to before and after the
conversion by calling the function print_last_node_points_to.

Runtime Test Cases


Case 1:
Please enter the elements in the linked list: 7 2 3 40 1
Last node points to None.
Converting linked list to a circular linked list...
Last node points to element with data 7.

Case 2:
Please enter the elements in the linked list: 3
Last node points to None.
Converting linked list to a circular linked list...
Last node points to element with data 3.

Case 3:
Please enter the elements in the linked list: 1 2
Last node points to None.
Converting linked list to a circular linked list...
Last node points to element with data 1.
10. Python Examples on Circularly & Doubly Linked Lists

Python Program to Implement Circular Doubly Linked List


This is a Python program to implement a circular doubly linked list.

Problem Description
The program creates a circular doubly linked list and presents the user with a menu to
perform various operations on the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class CircularDoublyLinkedList with instance variable first.
3. The variable first points to the first element in the circular doubly linked list.
4. Define methods get_node, insert_after, insert_before, insert_at_beg, insert_at_end,
remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many
times to return the node at that index. It stops if it reaches the first node again.
6. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
7. The methods insert_at_beg and insert_at_end insert a node at the first or last position of
the list. insert_at_beg modifies the variable first to point to the new node.
8. The method remove takes a node as argument and removes it from the list.
9. The method display traverses the list from the first node and prints the data of each node
until it reaches the first node again.
10. Create an instance of CircularDoublyLinkedList and present the user with a menu to
perform operations on the list.

Program/Source Code
Here is the source code of a Python program to implement a circular doubly linked list. The
program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class CircularDoublyLinkedList:
def __init__(self):
self.first = None

def get_node(self, index):


current = self.first
for i in range(index):
current = current.next
if current == self.first:
return None
return current

def insert_after(self, ref_node, new_node):


new_node.prev = ref_node
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


self.insert_after(ref_node.prev, new_node)

def insert_at_end(self, new_node):


if self.first is None:
self.first = new_node
new_node.next = new_node
new_node.prev = new_node
else:
self.insert_after(self.first.prev, new_node)

def insert_at_beg(self, new_node):


self.insert_at_end(new_node)
self.first = new_node

def remove(self, node):


if self.first.next == self.first:
self.first = None
else:
node.prev.next = node.next
node.next.prev = node.prev
if self.first == node:
self.first = node.next

def display(self):
if self.first is None:
return
current = self.first
while True:
print(current.data, end = ' ')
current = current.next
if current == self.first:
break

a_cdllist = CircularDoublyLinkedList()

print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')

while True:
print('The list: ', end = '')
a_cdllist.display()
print()
do = input('What would you like to do? ').split()

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

if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cdllist.insert_at_beg(new_node)
elif position == 'end':
a_cdllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cdllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cdllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cdllist.insert_before(ref_node, new_node)

elif operation == 'remove':


index = int(do[1])
node = a_cdllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cdllist.remove(node)

elif operation == 'quit':


break
Program Explanation
1. An instance of CircularDoublyLinkedList is created.
2. The user is presented with a menu to perform various operations on the list.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 3 at beg
The list: 3
What would you like to do? insert 5 at end
The list: 3 5
What would you like to do? insert 1 after 0
The list: 3 1 5
What would you like to do? insert 2 after 2
The list: 3 1 5 2
What would you like to do? remove 0
The list: 1 5 2
What would you like to do? remove 2
The list: 1 5
What would you like to do? remove 1
The list: 1
What would you like to do? remove 0
The list:
What would you like to do? quit

Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 3 after 0
No such index.
The list:
What would you like to do? insert 10 at end
The list: 10
What would you like to do? insert 1 at beg
The list: 1 10
What would you like to do? insert 5 before 0
The list: 1 10 5
What would you like to do? insert 9 at beg
The list: 9 1 10 5
What would you like to do? remove 3
The list: 9 1 10
What would you like to do? quit

Python Program to Demonstrate Circular Single Linked List


This is a Python program to demonstrate a circular single linked list.

Problem Description
The program creates a circular single linked list and presents the user with a menu to
perform various operations on the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class CircularLinkedList with instance variable head.
3. The variable head points to the first element in the circular single linked list.
4. Define methods get_node, get_prev_node, insert_after, insert_before, insert_at_beg,
insert_at_end, remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many
times to return the node at that index. It stops if it reaches the first node again.
6. get_prev_node takes a reference node as argument and returns the previous node.
7. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
8. The methods insert_at_beg and insert_at_end insert a node at the first or last position of
the list.
9. The method remove takes a node as argument and removes it from the list.
10. The method display traverses the list from the first node and prints the data of each
node. It stops when it reaches the first node again.
11. Create an instance of CircularLinkedList and present the user with a menu to perform
operations on the list.

Program/Source Code
Here is the source code of a Python program to demonstrate a circular single linked list.
The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None

class CircularLinkedList:
def __init__(self):
self.head = None

def get_node(self, index):


if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current

def get_prev_node(self, ref_node):


if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current

def insert_after(self, ref_node, new_node):


new_node.next = ref_node.next
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)

def insert_at_end(self, new_node):


if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)

def insert_at_beg(self, new_node):


self.insert_at_end(new_node)
self.head = new_node

def remove(self, node):


if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)
prev_node.next = node.next
if self.head == node:
self.head = node.next

def display(self):
if self.head is None:
return
current = self.head
while True:
print(current.data, end = ' ')
current = current.next
if current == self.head:
break

a_cllist = CircularLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')

while True:
print('The list: ', end = '')
a_cllist.display()
print()
do = input('What would you like to do? ').split()

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

if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cllist.insert_at_beg(new_node)
elif position == 'end':
a_cllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cllist.insert_before(ref_node, new_node)

elif operation == 'remove':


index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cllist.remove(node)

elif operation == 'quit':


break
Program Explanation
1. An instance of CircularLinkedList is created.
2. The user is presented with a menu to perform various operations on the list.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 7 at beg
The list: 7
What would you like to do? insert 1 before 0
The list: 7 1
What would you like to do? insert 10 after 0
The list: 7 10 1
What would you like to do? insert 3 at end
The list: 7 10 1 3
What would you like to do? remove 2
The list: 7 10 3
What would you like to do? remove 0
The list: 10 3
What would you like to do? quit

Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 1 at beg
The list: 1
What would you like to do? insert 3 after 2
No such index.
The list: 1
What would you like to do? remove 1
No such index.
The list: 1
What would you like to do? insert 6 after 0
The list: 1 6
What would you like to do? remove 0
The list: 6
What would you like to do? quit

Python Program to Implement a Doubly Linked List & provide


Insertion, Deletion & Display Operations
This is a Python program to create a doubly linked list and implement insertion, deletion and
display operations on the list.
Problem Description
The program creates a doubly linked list and presents the user with a menu to perform
various operations on the list.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class DoublyLinkedList with instance variables first and last.
3. The variable first points to the first element in the doubly linked list while last points to the
last element.
4. Define methods get_node, insert_after, insert_before, insert_at_beg, insert_at_end,
remove and display.
5. get_node takes an index as argument and traverses the list from the first node that many
times to return the node at that index.
6. The methods insert_after and insert_before insert a node after or before some reference
node in the list.
7. The methods insert_at_beg and insert_at_end insert a node at the first or last position of
the list.
8. The method remove takes a node as argument and removes it from the list.
9. The method display traverses the list from the first node and prints the data of each node.
10. Create an instance of DoublyLinkedList and present the user with a menu to perform
operations on the list.

Program/Source Code
Here is the source code of a Python program to create a doubly linked list and implement
insertion, deletion and display operations on the list. The program output is shown below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class DoublyLinkedList:
def __init__(self):
self.first = None
self.last = None

def get_node(self, index):


current = self.first
for i in range(index):
if current is None:
return None
current = current.next
return current

def insert_after(self, ref_node, new_node):


new_node.prev = ref_node
if ref_node.next is None:
self.last = new_node
else:
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node

def insert_before(self, ref_node, new_node):


new_node.next = ref_node
if ref_node.prev is None:
self.first = new_node
else:
new_node.prev = ref_node.prev
new_node.prev.next = new_node
ref_node.prev = new_node

def insert_at_beg(self, new_node):


if self.first is None:
self.first = new_node
self.last = new_node
else:
self.insert_before(self.first, new_node)

def insert_at_end(self, new_node):


if self.last is None:
self.last = new_node
self.first = new_node
else:
self.insert_after(self.last, new_node)

def remove(self, node):


if node.prev is None:
self.first = node.next
else:
node.prev.next = node.next

if node.next is None:
self.last = node.prev
else:
node.next.prev = node.prev

def display(self):
current = self.first
while current:
print(current.data, end = ' ')
current = current.next

a_dllist = DoublyLinkedList()

print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')

while True:
print('The list: ', end = '')
a_dllist.display()
print()
do = input('What would you like to do? ').split()

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

if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_dllist.insert_at_beg(new_node)
elif position == 'end':
a_dllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_dllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_dllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_dllist.insert_before(ref_node, new_node)

elif operation == 'remove':


index = int(do[1])
node = a_dllist.get_node(index)
if node is None:
print('No such index.')
continue
a_dllist.remove(node)

elif operation == 'quit':


break
Program Explanation
1. An instance of DoublyLinkedList is created.
2. The user is presented with a menu to perform various operations on the list.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 5 at beg
The list: 5
What would you like to do? insert 3 at beg
The list: 3 5
What would you like to do? insert 1 at end
The list: 3 5 1
What would you like to do? insert 10 after 1
The list: 3 5 10 1
What would you like to do? insert 0 before 2
The list: 3 5 0 10 1
What would you like to do? remove 4
The list: 3 5 0 10
What would you like to do? remove 1
The list: 3 0 10
What would you like to do? remove 5
No such index.
The list: 3 0 10
What would you like to do? quit

Case 2:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 3 after 0
No such index.
The list:
What would you like to do? insert 2 at beg
The list: 2
What would you like to do? insert 3 before 0
The list: 3 2
What would you like to do? remove 0
The list: 2
What would you like to do? remove 0
The list:
What would you like to do? quit

Python Programming Examples on Stacks & Queues


1. Python Examples on Stack Implementation

Python Program to Implement a Stack


This is a Python program to implement a stack.

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

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.

Program/Source Code
Here is the source code of a Python program to implement a stack. The program output is
shown below.
class Stack:
def __init__(self):
self.items = []

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

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())
elif operation == 'quit':
break
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.

Runtime Test Cases


Case 1:
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
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

Case 2:
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? push 1
push <value>
pop
quit
What would you like to do? pop
Popped value: 1
push <value>
pop
quit
What would you like to do? quit

ython Program to Reverse a Stack using Recursion


This is a Python program to reverse a stack using recursion.

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

Problem Solution
1. Create a class Stack with instance variable items initialized to an empty list.
2. Define methods push, pop, is_empty and display 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. The method display prints the elements of the stack from top to bottom.
7. Define function insert_at_bottom which takes a stack and a data item as arguments.
8. The function insert_at_bottom adds the data item to the bottom of the stack using
recursion.
9. Define function reverse_stack which takes a stack as argument.
10. The function reverse_stack reverses the stack using recursion.
11. Create an instance of Stack, push data to it and reverse the stack.

Program/Source Code
Here is the source code of a Python program to reverse a stack. The program output is
shown below.
class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

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

def display(self):
for data in reversed(self.items):
print(data)

def insert_at_bottom(s, data):


if s.is_empty():
s.push(data)
else:
popped = s.pop()
insert_at_bottom(s, data)
s.push(popped)

def reverse_stack(s):
if not s.is_empty():
popped = s.pop()
reverse_stack(s)
insert_at_bottom(s, popped)

s = Stack()
data_list = input('Please enter the elements to push: ').split()
for data in data_list:
s.push(int(data))

print('The stack:')
s.display()
reverse_stack(s)
print('After reversing:')
s.display()
Program Explanation
1. An instance of Stack is created.
2. The user is prompted to enter data items to push to the stack.
3. The stack is displayed.
4. The stack is reversed by passing it to the function reverse_stack.
5. The stack is displayed again.

Runtime Test Cases


Case 1:
Please enter the elements to push: 7 3 1 5
The stack:
5
1
3
7
After reversing:
7
3
1
5

Case 2:
Please enter the elements to push: 3
The stack:
3
After reversing:
3

Case 3:
Please enter the elements to push: 1 2
The stack:
2
1
After reversing:
1
2

Python Program to Implement Stack using One Queue


This is a Python program to implement a stack using a single queue.

Problem Description
The program creates a stack using a single queue and allows the user to perform push and
pop operations on it.

Problem Solution
1. Create a class Queue.
2. Define methods enqueue, dequeue, is_empty and get_size inside the class Queue.
3. Create a class Stack with instance variable q initialized to an empty queue.
4. Pushing is done by enqueuing data to the queue.
5. To pop, the queue is dequeued and enqueued with the dequeued element n – 1 times
where n is the size of the queue. This causes the the last element added to the queue to
reach the rear of the queue. The queue is dequeued one more time to get the item to be
returned.
6. The method is_empty returns True iff the queue is empty.

Program/Source Code
Here is the source code of a Python program to implement a stack using a single queue.
The program output is shown below.
class Stack:
def __init__(self):
self.q = Queue()

def is_empty(self):
return self.q.is_empty()

def push(self, data):


self.q.enqueue(data)

def pop(self):
for _ in range(self.q.get_size() - 1):
dequeued = self.q.dequeue()
self.q.enqueue(dequeued)
return self.q.dequeue()

class Queue:
def __init__(self):
self.items = []
self.size = 0

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

def enqueue(self, data):


self.size += 1
self.items.append(data)

def dequeue(self):
self.size -= 1
return self.items.pop(0)

def get_size(self):
return self.size

s = Stack()

print('Menu')
print('push <value>')
print('pop')
print('quit')

while True:
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())
elif operation == 'quit':
break
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.

Runtime Test Cases


Case 1:
Menu
push <value>
pop
quit
What would you like to do? push 3
What would you like to do? push 5
What would you like to do? pop
Popped value: 5
What would you like to do? pop
Popped value: 3
What would you like to do? pop
Stack is empty.

Case 2:
Menu
push <value>
pop
quit
What would you like to do? push 1
What would you like to do? push 2
What would you like to do? push 3
What would you like to do? push 4
What would you like to do? pop
Popped value: 4
What would you like to do? pop
Popped value: 3
What would you like to do? pop
Popped value: 2
What would you like to do? pop
Popped value: 1
What would you like to do? pop
Stack is empty.
What would you like to do? quit

Python Program to Implement Stack Using Two Queues


This is a Python program to implement a stack using two queues.

Problem Description
The program creates a stack using two queues and allows the user to perform push and
pop 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 is empty.
6. Create a class Stack with instance variable queue1 and queue2 initialized to empty
queues.
7. Define methods push, pop and is_empty inside the class Stack.
8. The method push takes an argument and enqueues it in queue1. Then every element of
queue2 is dequeued and enqueued in queue1. The names of queue1 and queue2 are then
switched.
9. The method pop dequeues from queue2 and returns the dequeued value.
10. The method is_empty returns True only if queue2 is empty.

Program/Source Code
Here is the source code of a Python program to implement a stack using two queues. The
program output is shown below.
class Stack:
def __init__(self):
self.queue1 = Queue()
self.queue2 = Queue()

def is_empty(self):
return self.queue2.is_empty()

def push(self, data):


self.queue1.enqueue(data)
while not self.queue2.is_empty():
x = self.queue2.dequeue()
self.queue1.enqueue(x)
self.queue1, self.queue2 = self.queue2, self.queue1

def pop(self):
return self.queue2.dequeue()

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)

s = Stack()

print('Menu')
print('push <value>')
print('pop')
print('quit')

while True:
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())
elif operation == 'quit':
break
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.

Runtime Test Cases


Case 1:
Menu
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
What would you like to do? push 3
What would you like to do? push 4
What would you like to do? pop
Popped value: 4
What would you like to do? pop
Popped value: 3
What would you like to do? pop
Stack is empty.
What would you like to do? push 1
What would you like to do? push 2
What would you like to do? pop
Popped value: 2
What would you like to do? quit

Case 2:
Menu
push <value>
pop
quit
What would you like to do? push 1
What would you like to do? push 2
What would you like to do? push 5
What would you like to do? push 0
What would you like to do? pop
Popped value: 0
What would you like to do? pop
Popped value: 5
What would you like to do? pop
Popped value: 2
What would you like to do? pop
Popped value: 1
What would you like to do? pop
Stack is empty.
What would you like to do? quit

2. Python Examples on Queue Implementation

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 is 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')
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
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
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

Python Program to Implement Dequeue


This is a Python program to implement a dequeue.

Problem Description
The program creates a dequeue and allows the user to perform append and pop operations
on it from both sides.

Problem Solution
1. Create a class Dequeue with instance variable items initialized to an empty list.
2. Define methods append, append_left, pop, pop_left and is_empty inside the class
Dequeue.
3. The method append appends data to items from the right.
4. The method append_left appends data to items from the left.
5. The method pop pops from the right from items.
6. The method pop_left pops from the left from items.
7. The method is_empty returns True only if items is empty.

Program/Source Code
Here is the source code of a Python program to implement a dequeue. The program output
is shown below.
class Dequeue:
def __init__(self):
self.items = []

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

def append(self, data):


self.items.append(data)

def append_left(self, data):


self.items.insert(0, data)

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

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

q = Dequeue()
print('Menu')
print('append <value>')
print('appendleft <value>')
print('pop')
print('popleft')
print('quit')

while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'append':
q.append(int(do[1]))
elif operation == 'appendleft':
q.append_left(int(do[1]))
elif operation == 'pop':
if q.is_empty():
print('Dequeue is empty.')
else:
print('Popped value from right: ', q.pop())
elif operation == 'popleft':
if q.is_empty():
print('Dequeue is empty.')
else:
print('Popped value from left: ', q.pop_left())
elif operation == 'quit':
break
Program Explanation
1. An instance of Dequeue is created.
2. The user is presented with a menu to perform various operations on the dequeue.
3. The chosen operation is performed by calling the corresponding method of the dequeue.

Runtime Test Cases


Case 1:
Menu
append <value>
appendleft <value>
pop
popleft
quit
What would you like to do? append 3
What would you like to do? append 4
What would you like to do? appendleft 2
What would you like to do? appendleft 1
What would you like to do? pop
Popped value from right: 4
What would you like to do? popleft
Popped value from left: 1
What would you like to do? pop
Popped value from right: 3
What would you like to do? popleft
Popped value from left: 2
What would you like to do? pop
Dequeue is empty.
What would you like to do? quit

Case 2:
Menu
append <value>
appendleft <value>
pop
popleft
quit
What would you like to do? append 1
What would you like to do? append 2
What would you like to do? pop
Popped value from right: 2
What would you like to do? pop
Popped value from right: 1
What would you like to do? appendleft 1
What would you like to do? appendleft 2
What would you like to do? pop
Popped value from right: 1
What would you like to do? pop
Popped value from right: 2
What would you like to do? append 1
What would you like to do? append 2
What would you like to do? popleft
Popped value from left: 1
What would you like to do? popleft
Popped value from left: 2
What would you like to do? quit

Python Program to Implement Queues using Stacks


This is a Python program to implement a queue using two stacks.

Problem Description
The program creates a queue using stacks and allows the user to perform enqueue and
dequeue operations on it.

Problem Solution
1. Create a class Node with instance variables data and next.
2. Create a class Stack with instance variable items initialized to an empty list.
3. Define methods push, pop and is_empty inside the class Stack.
4. The method push appends data to items.
5. The method pop pops the first element in items.
6. The method is_empty returns True only if items is empty.
7. Create a class Queue with instance variables inbox and outbox, both initialized to an
empty stack.
8. Define methods enqueue, dequeue and is_empty inside the class Queue.
9. The method enqueue pushes data to the stack inbox.
10. The method dequeue pops from the stack outbox if it is not empty. If it is empty, then all
the elements from inbox are popped and pushed to outbox before popping from outbox.
11. The method is_empty returns True only if both the stacks inbox and outbox are empty.
12. 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 using two stacks. The
program output is shown below.
class Queue:
def __init__(self):
self.inbox = Stack()
self.outbox = Stack()

def is_empty(self):
return (self.inbox.is_empty() and self.outbox.is_empty())

def enqueue(self, data):


self.inbox.push(data)

def dequeue(self):
if self.outbox.is_empty():
while not self.inbox.is_empty():
popped = self.inbox.pop()
self.outbox.push(popped)
return self.outbox.pop()

class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

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

a_queue = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
if a_queue.is_empty():
print('Queue is empty.')
else:
dequeued = a_queue.dequeue()
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
Program Explanation
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.

Runtime Test Cases


Case 1:
enqueue <value>
dequeue
quit
What would you like to do? enqueue 7
enqueue <value>
dequeue
quit
What would you like to do? enqueue 8
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 7
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 8
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 1
enqueue <value>
dequeue
quit
What would you like to do? enqueue 2
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued element: 1
enqueue <value>
dequeue
quit
What would you like to do? quit

3. Python Examples on String Implementation

Python Program to Check if String is Palindrome using Stack


This is a Python program to check whether a string is a palindrome using a stack.

Problem Description
The program prompts the user for a string and determines whether it is a palindrome with
the help of a stack.

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. Prompt the user for a string and push all the characters to a stack.
7. Construct the reversed string by popping characters from the stack.
8. Deterime whether the string is palindromic by comparing the two strings.

Program/Source Code
Here is the source code of a Python program to check whether a string is a palindrome
using a stack. The program output is shown below.
class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

def pop(self):
return self.items.pop()
s = Stack()
text = input('Please enter the string: ')

for character in text:


s.push(character)

reversed_text = ''
while not s.is_empty():
reversed_text = reversed_text + s.pop()

if text == reversed_text:
print('The string is a palindrome.')
else:
print('The string is not a palindrome.')
Program Explanation
1. An instance of Stack is created.
2. The user is prompted to enter a string.
3. The characters of the string are pushed to the stack.
4. The reversed string is constructed by popping the characters from the stack.
5. If the reversed string and the original string are the same, then the string is palindromic.
6. The result is displayed.

Runtime Test Cases


Case 1:
Please enter the string: madam
The string is a palindrome.

Case 2:
Please enter the string: racecar
The string is a palindrome.

Case 3:
Please enter the string: palace
The string is not a palindrome.

Python Program to Check if Expression is Correctly


Parenthesized
This is a Python program to check whether an expression is correctly parenthesized.

Problem Description
The program prompts the user for a string and determines whether it is a palindrome with
the help of a stack.

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. Prompt the user for an expression.
7. Iterate through the characters of the expression and push to the stack if an open
parenthesis is encountered and pop if a close parenthesis is encountered.
8. Determine whether the expression has balanced parentheses.

Program/Source Code
Here is the source code of a Python program to check for balanced parentheses using a
stack. The program output is shown below.
class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

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

s = Stack()
exp = input('Please enter the expression: ')

for c in exp:
if c == '(':
s.push(1)
elif c == ')':
if s.is_empty():
is_balanced = False
break
s.pop()
else:
if s.is_empty():
is_balanced = True
else:
is_balanced = False

if is_balanced:
print('Expression is correctly parenthesized.')
else:
print('Expression is not correctly parenthesized.')
Program Explanation
1. An instance of Stack is created.
2. The user is prompted to enter an expression.
3. Iterate through the expression and push to the stack for every open parenthesis and pop
for every close parenthesis.
4. If a pop is required when the stack is empty or the stack is not empty when the
expression has been iterated over, then the expression is not correctly parenthesized.
5. Display the result.

Runtime Test Cases


Case 1:
Please enter the expression: (3 + 4 * (1 + (2))/(7 * (8 + 9)))
Expression is correctly parenthesized.

Case 2:
Please enter the expression: (a + b))(3)
Expression is not correctly parenthesized.

Case 3:
Please enter the expression: (4 + (3 * 2)
Expression is not correctly parenthesized.

Python Programming Examples on Searching and Sorting

1. Python Examples on Searching Algorithms

Python Program to Implement Linear Search


This is a Python program to implement linear search.

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

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.

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))
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.

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.

Python Program to Implement Binary Search without Recursion


This is a Python program to implement binary search without recursion.

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

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.

Program/Source Code
Here is the source code of a Python program to implement binary search without using
recursion. The program output is shown below.
def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
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))
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.

Runtime Test Cases


Case 1:
Enter the sorted list of numbers: 3 5 10 12 15 20
The number to search for: 12
12 was found at index 3.

Case 2:
Enter the sorted list of numbers: -3 0 1 5 6 7 8
The number to search for: 2
2 was not found.

Case 3:
Enter the sorted list of numbers: 5
The number to search for: 5
5 was found at index 0.

Python Program to Implement Binary Search with Recursion


This is a Python program to implement binary search with recursion.

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

Problem Solution
1. Create a function binary_search that takes a list and the variables start, end and key as
arguments. The function searches for the key in the range [start… end – 1].
2. The base case consists of testing whether start is less than end. If not, -1 is returned.
3. mid is calculated as the floor of the average of start and end.
4. If the element at index mid is less than key, binary_search is called again wit start=mid +
1 and if it is more than key, it is called with end=mid. Otherwise, mid is returned as the
index of the found element.

Program/Source Code
Here is the source code of a Python program to implement binary search using recursion.
The program output is shown below.
def binary_search(alist, start, end, key):
"""Search key in alist[start... end - 1]."""
if not start < end:
return -1
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid

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, 0, len(alist), key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
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 with start=0 and end=length of the list.
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.

Runtime Test Cases


Case 1:
Enter the sorted list of numbers: 4 5 6 7 8 9 10
The number to search for: 9
9 was found at index 5.

Case 2:
Enter the sorted list of numbers: 3 4 5 10
The number to search for: 8
8 was not found.

Case 3:
Enter the sorted list of numbers: 7
The number to search for: 7
7 was found at index 0.

Python Program to Select the ith Smallest Element from a List


in Expected Linear Time
This is a Python program to select the ith smallest element from a list in expected linear
time.
Problem Description
The program takes a list and i as input and prints the ith smallest element in the list.

Problem Solution
1. Create a function select which takes a list and variables start, end, i as arguments.
2. The function will return the ith smallest element in the range alist[start… end – 1].
3. The base case consists of checking whether there is only one element in the list and if
so, alist[start] is returned.
4. Otherwise, the list is partitioned using Hoare’s partitioning scheme.
5. If i is equal to the number of elements in alist[start… pivot], call it k, then the pivot is the
ith smallest element.
6. Otherwise, depending on whether i is greater or smaller than k, select is called on the
appropriate half of the list.

Program/Source Code
Here is the source code of a Python program to select the ith smallest element from a list in
expected linear time. The program output is shown below.
def select(alist, start, end, i):
"""Find ith smallest element in alist[start... end-1]."""
if end - start <= 1:
return alist[start]
pivot = partition(alist, start, end)

# number of elements in alist[start... pivot]


k = pivot - start + 1

if i < k:
return select(alist, start, pivot, i)
elif i > k:
return select(alist, pivot + 1, end, i - k)

return alist[pivot]

def partition(alist, start, end):


pivot = alist[start]
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: ')


alist = alist.split()
alist = [int(x) for x in alist]
i = int(input('The ith smallest element will be found. Enter i: '))

ith_smallest_item = select(alist, 0, len(alist), i)


print('Result: {}.'.format(ith_smallest_item))
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The user is then asked to enter i.
3. The ith smallest element is found by calling select.
4. The result is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 3 5 10 2 -1 0 2
The ith smallest element will be found. Enter i: 2
Result: 0.

Case 2:
Enter the list of numbers: 7
The ith smallest element will be found. Enter i: 1
Result: 7.

Case 3:
Enter the list of numbers: 5 4 3 2 1
The ith smallest element will be found. Enter i: 5
Result: 5.

Python Program to Select the ith Largest Element from a List in


Expected Linear Time
This is a Python program to select the ith largest element from a list in expected linear time.

Problem Description
The program takes a list and i as input and prints the ith largest element in the list.

Problem Solution
1. Create a function select which takes a list and variables start, end, i as arguments.
2. The function will return the ith largest element in the range alist[start… end – 1].
3. The base case consists of checking whether there is only one element in the list and if
so, alist[start] is returned.
4. Otherwise, the list is partitioned using Hoare’s partitioning scheme.
5. If i is equal to the number of elements in alist[pivot… end – 1], call it k, then the pivot is
the ith largest element.
6. Otherwise, depending on whether i is greater or smaller than k, select is called on the
appropriate half of the list.

Program/Source Code
Here is the source code of a Python program to select the ith largest element from a list in
expected linear time. The program output is shown below.
def select(alist, start, end, i):
"""Find ith largest element in alist[start... end-1]."""
if end - start <= 1:
return alist[start]
pivot = partition(alist, start, end)

# number of elements in alist[pivot... end - 1]


k = end - pivot

if i < k:
return select(alist, pivot + 1, end, i)
elif i > k:
return select(alist, start, pivot, i - k)

return alist[pivot]

def partition(alist, start, end):


pivot = alist[start]
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: ')


alist = alist.split()
alist = [int(x) for x in alist]
i = int(input('The ith smallest element will be found. Enter i: '))

ith_smallest_item = select(alist, 0, len(alist), i)


print('Result: {}.'.format(ith_smallest_item))
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The user is then asked to enter i.
3. The ith largest element is found by calling select.
4. The result is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 3 1 5 10 7 2 -2
The ith smallest element will be found. Enter i: 2
Result: 7.

Case 2:
Enter the list of numbers: 5 4 3 2 1
The ith smallest element will be found. Enter i: 5
Result: 1.

Case 3:
Enter the list of numbers: 3
The ith smallest element will be found. Enter i: 1
Result: 3.

2. Python Examples on Sorting Algorithms

Python Program to Implement Bubble Sort


This is a Python program to implement bubble sort.

Problem Description
The program sorts a list by bubble sort.

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.

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

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


alist = [int(x) for x in alist]
bubble_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 bubble_sort function.
3. The sorted list is displayed.

Runtime Test Cases


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

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: 7 3 1 -5 2 10
Sorted list: [-5, 1, 2, 3, 7, 10]

Python Program to Implement Selection Sort


This is a Python program to implement selection sort.

Problem Description
The program sorts a list by selection sort.

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

Program/Source Code
Here is the source code of a Python program to implement selection sort. The program
output is shown below.
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]

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


alist = [int(x) for x in alist]
selection_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 selection_sort function.
3. The sorted list is displayed.

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]

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.
def insertion_sort(alist):
for i in 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

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


alist = [int(x) for x in alist]
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: 2 4 1 5 8 0
Sorted list: [0, 1, 2, 4, 5, 8]

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]

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, 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]

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

Python Program to Implement Quicksort


This is a Python program to implement quicksort.

Problem Description
The program sorts a list by quicksort.
Problem Solution
1. Create a function quicksort 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 quicksort with the list and the variables start and p as arguments to sort the list from
start to p – 1.
5. Call quicksort 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 parititon uses Hoare’s partition scheme to partition the list.

Program/Source Code
Here is the source code of a Python program to implement quicksort. The program output is
shown below.
def quicksort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
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]
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)
Program Explanation
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.

Runtime Test Cases


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

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

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

Python Program to Implement Heapsort


This is a Python program to implement heapsort.

Problem Description
The program sorts a list by heapsort.

Problem Solution
1. Create a function heapsort 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]
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
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]

Python Program to Implement Heapsort


This is a Python program to implement heapsort.

Problem Description
The program sorts a list by heapsort.

Problem Solution
1. Create a function heapsort 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]
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
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]

Python Program to Implement Radix Sort


This is a Python program to implement radix sort.

Problem Description
The program sorts a list by radix sort.

Problem Solution
1. Create a function radix_sort that takes a list and a variable base as arguments.
2. Create an inner function key_factory that takes two variables digit and base as
arguments and returns a function.
3. The function key returned takes a list and a variable index as arguments. It returns a digit
of the element at that index in the list. The position of the digit it returns is given by the
variable digit passed to key_factory. The digit position is found with the element represented
in that base. The digit position uses zero-based numbering.
4. Inside the function radix_sort, find the largest element in the list.
5. Let exp iterate from 0 to the highest digit position of the largest element in the list.
6. For each value of exp, sort the elements of the list on digit exp.
7. The sorting is done by calling the counting_sort function. The function then sorts the list
using the fact that the largest element is base – 1 and using the function key. The function
key is returned by the key_factory function when it is passed exp as the digit position and
base as arguments.
8. Create a function counting_sort that takes a list, a variable largest and a function key as
arguments.
9. Inside the function create a list c of zeros of length largest + 1.
10. For each element in the input list, retrieve its key n by calling the function key and then
increment the nth index of the list c.
11. The list c now contains the frequency of each key in the input list.
12. For each index from 1 to the length of c – 1, add to the current element the previous
element. Before the loop, decrement c[0] since this will cause all the elements to be
decremented by one after the loop finishes. Thus, the list c will contain the last index of
each element in our sorted array.
13. Create the output array with size the same as that of the input array.
14. Create a loop where the loop variable i iterates from the length of the input list – 1 to 0.
15. In each iteration of the loop set the pth element of the output list equal to the ith element
of the input list. The value p is the element of the list c at the index given by the key of the
element of the input list. The value where p is stored in c is then decremented.

Program/Source Code
Here is the source code of a Python program to implement radix sort. The program output is
shown below.
def radix_sort(alist, base=10):
if alist == []:
return

def key_factory(digit, base):


def key(alist, index):
return ((alist[index]//(base**digit)) % base)
return key
largest = max(alist)
exp = 0
while base**exp <= largest:
alist = counting_sort(alist, base - 1, key_factory(exp, base))
exp = exp + 1
return alist

def counting_sort(alist, largest, key):


c = [0]*(largest + 1)
for i in range(len(alist)):
c[key(alist, i)] = c[key(alist, i)] + 1

# Find the last index for each element


c[0] = c[0] - 1 # to decrement each element for zero-based indexing
for i in range(1, largest + 1):
c[i] = c[i] + c[i - 1]

result = [None]*len(alist)
for i in range(len(alist) - 1, -1, -1):
result[c[key(alist, i)]] = alist[i]
c[key(alist, i)] = c[key(alist, i)] - 1

return result

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


alist = [int(x) for x in alist]
sorted_list = radix_sort(alist)
print('Sorted list: ', end='')
print(sorted_list)
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to the radix_sort function and the returned list is the sorted list.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of (nonnegative) numbers: 38 20 1 3 4 0 2 5 1 3 8 2 9 10
Sorted list: [0, 1, 1, 2, 2, 3, 3, 4, 5, 8, 9, 10, 20, 38]

Case 2:
Enter the list of (nonnegative) numbers: 7 5 3 2 1
Sorted list: [1, 2, 3, 5, 7]

Case 3:
Enter the list of (nonnegative) numbers: 3
Sorted list: [3]

Python Program to Implement Bucket Sort


This is a Python program to implement bucket sort.

Problem Description
The program sorts a list by bucket sort.

Problem Solution
1. Create a function bucket_sort that takes a list as argument.
2. Inside the function set largest to the maximum element in the list and set length equal to
the length of the list.
3. Set size = largest/length.
4. Create a list of empty lists and assign it to buckets.
5. Create a loop with loop variable i that iterates from 0 to the length of the list – 1.
6. In each iteration, determine to which bucket alist[i] belongs. This is done by taking the
floor of alist[i]/size and using the answer as the index of the bucket. If the answer equals
length, then alist[i] is placed in the last bucket, that is bucket[length -1 ].
7. Perform insertion sort on each bucket.
8. Concatenate the buckets to create the sorted list and return it.
9. Create a function insertion_sort that takes a list as argument.
10. Inside the function create a loop with a loop variable i that counts from 1 to the length of
the list – 1.
11. Set temp equal to the element at index i.
12. Set j equal to i – 1.
13. Create a while loop that runs as long as j is non-negative and temp is smaller than the
element at index j.
14. Inside the while loop, set the element at index j + 1 equal to the element at index j and
decrement j.
15. 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 bucket sort. The program output
is shown below.
def bucket_sort(alist):
largest = max(alist)
length = len(alist)
size = largest/length

buckets = [[] for _ in range(length)]


for i in range(length):
j = int(alist[i]/size)
if j != length:
buckets[j].append(alist[i])
else:
buckets[length - 1].append(alist[i])

for i in range(length):
insertion_sort(buckets[i])

result = []
for i in range(length):
result = result + buckets[i]

return result

def insertion_sort(alist):
for i in 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
alist = input('Enter the list of (nonnegative) numbers: ').split()
alist = [int(x) for x in alist]
sorted_list = bucket_sort(alist)
print('Sorted list: ', end='')
print(sorted_list)
Program Explanation
1. The user is prompted to enter a list of numbers.
2. The list is passed to the bucket_sort function and the sorted list is returned.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of (nonnegative) numbers: 2 1 5 10 3 5 7
Sorted list: [1, 2, 3, 5, 5, 7, 10]

Case 2:
Enter the list of (nonnegative) numbers: 8 7 5 3 2 1
Sorted list: [1, 2, 3, 5, 7, 8]

Case 3:
Enter the list of (nonnegative) numbers: 5
Sorted list: [5]

Python Program to Implement Gnome Sort


This is a Python program to implement gnome sort.

Problem Description
The program sorts a list by gnome sort.

Problem Solution
1. Create a function gnome_sort that takes a list as argument.
2. Inside the function create a loop with loop variable pos that iterates from 1 to the length of
the list – 1.
3. Inside the loop, create a while loop that runs as long as pos != 0 and alist[pos] and
alist[pos – 1] are out of order.
4. In the body of the while loop, swap alist[pos] and alist[pos – 1] and decrement pos.

Program/Source Code
Here is the source code of a Python program to implement gnome sort. The program output
is shown below.
def gnome_sort(alist):
for pos in range(1, len(alist)):
while (pos != 0 and alist[pos] < alist[pos - 1]):
alist[pos], alist[pos - 1] = alist[pos - 1], alist[pos]
pos = pos - 1

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


alist = [int(x) for x in alist]
gnome_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 gnome_sort function.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 2 3 2 51 38 1 10 3 0 7 8
Sorted list: [0, 1, 2, 2, 3, 3, 7, 8, 10, 38, 51]

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: 7
Sorted list: [7]

Python Program to Implement Cocktail Shaker Sort


This is a Python program to implement cocktail shaker sort.

Problem Description
The program sorts a list by cocktail shaker sort.

Problem Solution
1. Create a function cocktail_shaker_sort that takes a list as argument.
2. Set upper to length of the list – 1 and lower to 0.
3. Create a loop inside which bubble sort is performed on the list from indexes lower to
upper and then from upper to lower.
4. After bubble sort is performed from indexes lower to upper, decrement upper and after it
has been performed from upper to lower, increment lower.
5. Check if no swaps were performed in any iteration. If there were no swaps, then the list is
sorted.

Program/Source Code
Here is the source code of a Python program to implement cocktail shaker sort. The
program output is shown below.
def cocktail_shaker_sort(alist):
def swap(i, j):
alist[i], alist[j] = alist[j], alist[i]

upper = len(alist) - 1
lower = 0

no_swap = False
while (not no_swap and upper - lower > 1):
no_swap = True
for j in range(lower, upper):
if alist[j + 1] < alist[j]:
swap(j + 1, j)
no_swap = False
upper = upper - 1

for j in range(upper, lower, -1):


if alist[j - 1] > alist[j]:
swap(j - 1, j)
no_swap = False
lower = lower + 1

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


alist = [int(x) for x in alist]
cocktail_shaker_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 cocktail_shaker_sort function.
3. The sorted list is displayed.

Runtime Test Cases


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

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

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

Python Program to Implement Comb Sort


This is a Python program to implement comb sort.

Problem Description
The program sorts a list by comb sort.

Problem Solution
1. Create a function comb_sort that takes a list as argument.
2. Set gap equal to the length of the list.
3. Choose an appropriate shrink factor. Here shrink = 1.3.
4. Create a while loop that runs as long as there was at least one swap performed in the
previous iteration of the loop (or if this is the first iteration of the loop).
5. Set gap to the floor of gap/shrink.
6. If gap becomes less than 1, set it to 1.
7. Perform bubble sort on the list but only compare and swap elements that are at a
distance of gap.
8. If gap was not one, then continue the loop even if there weren’t any swaps performed.

Program/Source Code
Here is the source code of a Python program to implement comb sort. The program output
is shown below.
def comb_sort(alist):
def swap(i, j):
alist[i], alist[j] = alist[j], alist[i]

gap = len(alist)
shrink = 1.3

no_swap = False
while not no_swap:
gap = int(gap/shrink)

if gap < 1:
gap = 1
no_swap = True
else:
no_swap = False

i = 0
while i + gap < len(alist):
if alist[i] > alist[i + gap]:
swap(i, i + gap)
no_swap = False
i = i + 1

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


alist = [int(x) for x in alist]
comb_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 comb_sort function.
3. The sorted list is displayed.

Runtime Test Cases


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

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: 3
Sorted list: [3]

Python Program to Implement Shell Sort


This is a Python program to implement shell sort.

Problem Description
The program sorts a list by shell sort.

Problem Solution
1. Create a generator gaps that takes the size of the list as argument and returns the next
element in the sequence of gaps on each successive call. Here the gap sequence chosen is
given by 2^k – 1.
2. Create a function shell_sort that takes a list as argument.
3. For each gap returned by gaps, call insertion_sort_with_gap with gap as argument.
4. Create a function insertion_sort_with_gap that takes a variable gap as argument.
5. The function insertion_sort_with_gap performs insertion sort on all elements at a distance
of gap from each other. Thus it performs insertion sort on the indexes k, k + gap, k + 2*gap,
k + 3*gap, … of the list for all values of k.

Program/Source Code
Here is the source code of a Python program to implement shell sort. The program output is
shown below.
def gaps(size):
# uses the gap sequence 2^k - 1: 1, 3, 7, 15, 31, ...
length = size.bit_length()
for k in range(length - 1, 0, -1):
yield 2**k - 1

def shell_sort(alist):
def insertion_sort_with_gap(gap):
for i in range(gap, len(alist)):
temp = alist[i]
j = i - gap
while (j >= 0 and temp < alist[j]):
alist[j + gap] = alist[j]
j = j - gap
alist[j + gap] = temp

for g in gaps(len(alist)):
insertion_sort_with_gap(g)

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


alist = [int(x) for x in alist]
shell_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 shell_sort function.
3. The sorted list is displayed.

Runtime Test Cases


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

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

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

Python Program to Implement Introsort


This is a Python program to implement introsort.

Problem Description
The program sorts a list by introsort.
Problem Solution
1. Create a function introsort that takes a list argument.
2. In the function, an appropriate value for maxdepth is chosen. Here maxdepth is chosen
equal to 2 times floor of log base 2 of the length of the list.
3. Call introsort_helper with start=0 and end=len(alist).
4. The function introsort_helper takes a list and three variables, start, end and maxdepth as
arguments. The function sorts the list from indexes start to end – 1 inclusive.
5. The function returns if the length of the list to be sorted is not greater than 1.
6. It performs heapsort from indexes start to end – 1 on the list if maxdepth is 0.
7. Otherwise, partition is called on the list and introsort_helper is called on the two halves of
the list.
8. The function parititon uses Hoare’s partition scheme to partition the list.
9. Create a function heapsort that takes a list as argument and variables start and end
which specify the indexes across which the sort should be performed.
10. Call build_max_heap to rearrange the list into a list representation of a heap.
11. Swap the first element with the last element in the heap.
12. 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.
13. Repeat steps 11 and 12 until the size of the heap reduces to zero and the entire list is
sorted (i.e. from indexes start to end – 1 inclusive).
14. Define the function build_max_heap that rearranges a list specified between indexes
start to end – 1 inclusive to form a max heap.
15. 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.
16. 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 introsort. The program output is
shown below.
def introsort(alist):
maxdepth = (len(alist).bit_length() - 1)*2
introsort_helper(alist, 0, len(alist), maxdepth)

def introsort_helper(alist, start, end, maxdepth):


if end - start <= 1:
return
elif maxdepth == 0:
heapsort(alist, start, end)
else:
p = partition(alist, start, end)
introsort_helper(alist, start, p + 1, maxdepth - 1)
introsort_helper(alist, p + 1, end, maxdepth - 1)

def partition(alist, start, end):


pivot = alist[start]
i = start - 1
j = end

while True:
i = i + 1
while alist[i] < pivot:
i = i + 1
j = j - 1
while alist[j] > pivot:
j = j - 1

if i >= j:
return j

swap(alist, i, j)

def swap(alist, i, j):


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

def heapsort(alist, start, end):


build_max_heap(alist, start, end)
for i in range(end - 1, start, -1):
swap(alist, start, i)
max_heapify(alist, index=0, start=start, end=i)

def build_max_heap(alist, start, end):


def parent(i):
return (i - 1)//2
length = end - start
index = parent(length - 1)
while index >= 0:
max_heapify(alist, index, start, end)
index = index - 1

def max_heapify(alist, index, start, end):


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

size = end - start


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

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


alist = [int(x) for x in alist]
introsort(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 introsort function.
3. The sorted list is displayed.

Runtime Test Cases


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

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: 5
Sorted list: [5]

3. Python Examples on Sorting using Binary Trees

Python Program to Implement Binary Insertion Sort


This is a Python program to implement binary insertion sort.

Problem Description
The program sorts a list by binary insertion sort.

Problem Solution
1. Create a function binary 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. Call binary_search with key = temp, start = 0 and end = i.
5. Set pos equal to one plus the return value of the above call.
6. Shift all elements one position right from indexes pos + 1 to i inclusive and set alist[pos]
to temp.
7. Create a function binary_search that takes a list, a key and two indexes start and end as
arguments.
8. The function performs binary search to find key in the list between indexes start and end
– 1 inclusive. If the key is not found, it returns the index of the largest element smaller than
key. If key is smaller than the first element, it returns -1.

Program/Source Code
Here is the source code of a Python program to implement binary insertion sort. The
program output is shown below.
def binary_insertion_sort(alist):
for i in range(1, len(alist)):
temp = alist[i]
pos = binary_search(alist, temp, 0, i) + 1

for k in range(i, pos, -1):


alist[k] = alist[k - 1]

alist[pos] = temp

def binary_search(alist, key, start, end):


'''If key is in the list at index p, then return p.
If there are multiple such keys in the list, then return the index of any one.
If key is not in the list and a < key < b where a and b are elements in the list,
then return the index of a.
If key is not in the list and key < a where a is the first element in the list,
then return -1.
Only elements with indexes start to end - 1 inclusive are considered.
'''
if end - start <= 1:
if key < alist[start]:
return start - 1
else:
return start

mid = (start + end)//2


if alist[mid] < key:
return binary_search(alist, key, mid, end)
elif alist[mid] > key:
return binary_search(alist, key, start, mid)
else:
return mid

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


alist = [int(x) for x in alist]
binary_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 binary insertion_sort function.
3. The sorted list is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 5 2 7 10 3 5 2 1 8 9
Sorted list: [1, 2, 2, 3, 5, 5, 7, 8, 9, 10]

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

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

Python Program to Sort using a Binary Search Tree


This is a Python program to sort using a binary search tree.

Problem Description
The program sorts a list using a binary search tree.

Problem Solution
1. Create a class BSTNode with instance variables key, left, right and parent.
2. Define methods insert and inorder 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. Create a class BSTree with instance variable root.
6. Define methods inorder and add in BSTree.
7. The method inorder calls the inorder method of the root node.
8. The method add takes a key as argument and adds a node with that key by calling the
insert method of the root node.

Program/Source Code
Here is the source code of a Python program to sort a list using a binary search tree. 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()

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)

bstree = BSTree()

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


alist = [int(x) for x in alist]
for x in alist:
bstree.add(x)
print('Sorted list: ', end='')
bstree.inorder()
Program Explanation
1. The user is prompted to enter a list of numbers.
2. Each element in the list is added to the binary search tree.
3. The inorder traversal of the binary search tree is displayed.

Runtime Test Cases


Case 1:
Enter the list of numbers: 4 2 3 4 5 6 1 7 9 10 3
Sorted list: 1 2 3 3 4 4 5 6 7 9 10

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

Case 3:
Enter the list of numbers: 5
Sorted list: 5

Python Programming Examples on Trees

1. Python Examples on Tree Traversals

Python Program for Depth First Binary Tree Search using


Recursion
This is a Python program to perform depth-first search on a binary tree using recursion.

Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including depth-first search.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, depth_first and search.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method depth_first displays a depth first traversal of the tree.
6. The method search returns a node with a specified key.

Program/Source Code
Here is the source code of a Python program to perform depth-first search on a binary tree
using recursion. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def depth_first(self):
print('entering {}...'.format(self.key))
if self.left is not None:
self.left.depth_first()
print('at {}...'.format(self.key))
if self.right is not None:
self.right.depth_first()
print('leaving {}...'.format(self.key))

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('dfs')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'dfs':


print('depth-first search traversal:')
if btree is not None:
btree.depth_first()
print()

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method depth_first is called to display a DFS traversal of the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
dfs
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 4 left of 2
What would you like to do? insert 5 right of 2
What would you like to do? insert 6 left of 5
What would you like to do? insert 7 right of 5
What would you like to do? dfs
depth-first search traversal:
entering 1...
entering 2...
entering 4...
at 4...
leaving 4...
at 2...
entering 5...
entering 6...
at 6...
leaving 6...
at 5...
entering 7...
at 7...
leaving 7...
leaving 5...
leaving 2...
at 1...
entering 3...
at 3...
leaving 3...
leaving 1...

What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
dfs
quit
What would you like to do? insert 3 at root
What would you like to do? insert 4 left of 3
What would you like to do? insert 5 right of 3
What would you like to do? insert 6 left of 4
What would you like to do? dfs
depth-first search traversal:
entering 3...
entering 4...
entering 6...
at 6...
leaving 6...
at 4...
leaving 4...
at 3...
entering 5...
at 5...
leaving 5...
leaving 3...

What would you like to do? quit

Python Program for Depth First Binary Tree Search without


using Recursion
This is a Python program to perform depth-first search on a binary tree without using
recursion.

Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including depth-first search.

Problem Solution
1. Create a class Stack to implement a stack.
2. The class Stack will have methods is_empty, push and pop.
3. Create a class BinaryTree with instance variables key, left and right.
4. Define methods set_root, insert_left, insert_right, preorder_depth_first and search.
5. The method set_root takes a key as argument and sets the variable key equal to it.
6. The methods insert_left and insert_right insert a node as the left and right child
respectively.
7. The method search returns a node with a specified key.
8. The method preorder_depth_first displays a preorder DFS traversal of the tree.
9. The preorder traversal is implemented using a stack to avoid recursion.

Program/Source Code
Here is the source code of a Python program to perform depth-first search on a binary tree
without using recursion. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def preorder_depth_first(self):
s = Stack()
s.push(self)
while (not s.is_empty()):
node = s.pop()
print(node.key, end=' ')
if node.right is not None:
s.push(node.right)
if node.left is not None:
s.push(node.left)

class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

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

btree = BinaryTree()

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('dfs')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'dfs':


print('pre-order dfs traversal: ', end='')
if btree is not None:
btree.preorder_depth_first()
print()

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method preorder_depth_first is called to display a DFS pre-order traversal of the
tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
dfs
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 4 right of 2
What would you like to do? insert 5 left of 4
What would you like to do? dfs
pre-order dfs traversal: 1 2 4 5 3
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
dfs
quit
What would you like to do? insert 3 at root
What would you like to do? insert 6 left of 3
What would you like to do? insert 7 right of 3
What would you like to do? insert 8 left of 7
What would you like to do? insert 10 right of 7
What would you like to do? dfs
pre-order dfs traversal: 3 6 7 8 10
What would you like to do? quit

Python Program to Find Nth Node in the Inorder Traversal of a


Binary Tree
This is a Python program to find the Nth node in the in-order traversal of a binary tree.

Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including printing the Nth term in its in-order traversal.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, inorder_nth, inorder_nth_helper and
search.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method search returns a node with a specified key.
6. The method inorder_nth displays the nth element in the in-order traversal of the tree. It
calls the recursive method inorder_nth_helper.

Program/Source Code
Here is the source code of a Python program to find the Nth node in the in-order traversal of
a binary tree. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def inorder_nth(self, n):


return self.inorder_nth_helper(n, [])

def inorder_nth_helper(self, n, inord):


if self.left is not None:
temp = self.left.inorder_nth_helper(n, inord)
if temp is not None:
return temp
inord.append(self)
if n == len(inord):
return self
if self.right is not None:
temp = self.right.inorder_nth_helper(n, inord)
if temp is not None:
return temp

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('inorder <index>')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'inorder':


if btree is not None:
index = int(do[1].strip().lower())
node = btree.inorder_nth(index)
if node is not None:
print('nth term of inorder traversal: {}'.format(node.key))
else:
print('index exceeds maximum possible index.')
else:
print('Tree is empty.')

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the binary tree.
3. The corresponding methods are called to perform each operation.
4. The method inorder_nth is called to display the nth element in the in-order traversal of the
tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
inorder <index>
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? inorder 1
nth term of inorder traversal: 2
What would you like to do? inorder 2
nth term of inorder traversal: 1
What would you like to do? inorder 3
nth term of inorder traversal: 3
What would you like to do? inorder 4
index exceeds maximum possible index.
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
inorder <index>
quit
What would you like to do? insert 1 at root
What would you like to do? insert 3 left of 1
What would you like to do? insert 7 right of 1
What would you like to do? insert 5 right of 3
What would you like to do? insert 6 left of 5
What would you like to do? inorder 1
nth term of inorder traversal: 3
What would you like to do? inorder 2
nth term of inorder traversal: 6
What would you like to do? inorder 3
nth term of inorder traversal: 5
What would you like to do? inorder 4
nth term of inorder traversal: 1
What would you like to do? inorder 5
nth term of inorder traversal: 7
What would you like to do? inorder 6
index exceeds maximum possible index.
What would you like to do? quit

Python Program to Find the Largest value in a Binary Tree


using Inorder Traversal
This is a Python program to find the largest value of a binary tree using in-order traversal.

Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including finding the largest element in the tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, inorder_largest, inorder_largest_helper
and search.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method search returns a node with a specified key.
6. The method inorder_largest finds the largest element in the tree using in-order traversal.
It calls the recursive method inorder_largest_helper.

Program/Source Code
Here is the source code of a Python program to find the largest value of a binary tree using
in-order traversal. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def inorder_largest(self):
# largest will be a single element list
# this is a workaround to reference an integer
largest = []
self.inorder_largest_helper(largest)
return largest[0]

def inorder_largest_helper(self, largest):


if self.left is not None:
self.left.inorder_largest_helper(largest)
if largest == []:
largest.append(self.key)
elif largest[0] < self.key:
largest[0] = self.key
if self.right is not None:
self.right.inorder_largest_helper(largest)

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('largest')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'largest':


if btree is None:
print('Tree is empty.')
else:
print('Largest element: {}'.format(btree.inorder_largest()))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the binary tree.
3. The corresponding methods are called to perform each operation.
4. The method inorder_largest is called to find the largest element in the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
largest
quit
What would you like to do? insert 1 at rot
What would you like to do? largest
Largest element: 1
What would you like to do? insert 2 left of 1
What would you like to do? largest
Largest element: 2
What would you like to do? insert 3 right of 1
What would you like to do? largest
Largest element: 3
What would you like to do? insert 10 left of 3
What would you like to do? largest
Largest element: 10
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
largest
quit
What would you like to do? insert 3 at root
What would you like to do? insert 5 left of 3
What would you like to do? insert 2 right of 3
What would you like to do? largest
Largest element: 5
What would you like to do? quit

Python Program to Implement Depth First Search Traversal


using Post Order
This is a Python program to perform depth-first post-order traversal on a tree.

Problem Description
The program creates a tree and presents a menu to the user to perform operations on the
tree including post-order traversal.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, postorder and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method postorder displays a DFS post-order traversal of the tree.

Program/Source Code
Here is the source code of a Python program to perform depth-first post-order traversal on a
tree. The program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data

def add(self, node):


self.children.append(node)

def search(self, key):


if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def postorder(self):
for child in self.children:
child.postorder()
print(self.key, end=' ')

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('dfs')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'dfs':


print('Post-order traversal: ', end='')
tree.postorder()
print()
elif operation == 'quit':
break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method postorder is called on the tree to display a DFS post-order traversal.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
dfs
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 2
What would you like to do? add 4 below 2
What would you like to do? add 5 below 1
What would you like to do? add 6 below 1
What would you like to do? dfs
Post-order traversal: 3 4 2 5 6 1
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
dfs
quit
What would you like to do? add 3 at root
What would you like to do? add 5 below 3
What would you like to do? add 2 below 3
What would you like to do? add 1 below 5
What would you like to do? add 6 below 5
What would you like to do? dfs
Post-order traversal: 1 6 5 2 3
What would you like to do? quit

Python Program to Create a Mirror Copy of a Tree and Display


using BFS Traversal
This is a Python program to create a mirror copy of a binary tree and display its BFS
traversal.

Problem Description
The program creates a mirror copy of a binary tree and displays its BFS traversal.
Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, mirror_copy, bfs and search.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method bfs displays the BFS traversal.
6. The method search returns a node with a specified key.
7. The method mirror_copy returns a mirror copy of the tree.

Program/Source Code
Here is the source code of a Python program to create a mirror copy of a tree and display
its BFS traversal. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def mirror_copy(self):
mirror = BinaryTree(self.key)
if self.right is not None:
mirror.left = self.right.mirror_copy()
if self.left is not None:
mirror.right = self.left.mirror_copy()
return mirror
def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
if popped.left is not None:
queue.append(popped.left)
if popped.right is not None:
queue.append(popped.right)
print(popped.key, end=' ')

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('mirror')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'mirror':


if btree is not None:
print('Creating mirror copy...')
mirror = btree.mirror_copy()
print('BFS traversal of original tree: ')
btree.bfs()
print()
print('BFS traversal of mirror: ')
mirror.bfs()
print()
elif operation == 'quit':
break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method mirror_copy is called to construct a mirror copy of the tree and then the BFS
traversal of the original and the mirror copy is displayed.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
mirror
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 4 left of 2
What would you like to do? insert 5 left of 3
What would you like to do? insert 6 right of 3
What would you like to do? mirror
Creating mirror copy...
BFS traversal of original tree:
1 2 3 4 5 6
BFS traversal of mirror:
1 3 2 6 5 4
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
mirror
quit
What would you like to do? insert 1 at root
What would you like to do? mirror
Creating mirror copy...
BFS traversal of original tree:
1
BFS traversal of mirror:
1
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? mirror
Creating mirror copy...
BFS traversal of original tree:
1 2 3
BFS traversal of mirror:
1 3 2
What would you like to do? quit

Python Program to Build Binary Tree with Inorder and Postorder


Traversal as Input
This is a Python program to build a binary tree with in-order and post-order traversals as input.

Problem Description
The program builds a binary tree from their in-order and post-order traversals.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, inorder and postorder.
3. The method set_root takes a key as argument and sets the instance variable key equal to it.
4. The method inorder displays an in-order traversal of the binary tree.
5. The method postorder displays a post-order traversal of the binary tree.
6. Define the function construct_btree which takes two lists postord and inord as arguments.
7. The function construct_btree returns a binary tree that has post-order traversal postord and in-
order traversal inord.

Program/Source Code
Here is the source code of a Python program to build a binary tree with in-order and post-order
traversals as input. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

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 postorder(self):
if self.left is not None:
self.left.postorder()
if self.right is not None:
self.right.postorder()
print(self.key, end=' ')

def construct_btree(postord, inord):


if postord == [] or inord == []:
return None
key = postord[-1]
node = BinaryTree(key)
index = inord.index(key)
node.left = construct_btree(postord[:index], inord[:index])
node.right = construct_btree(postord[index:-1], inord[index + 1:])
return node

postord = input('Input post-order traversal: ').split()


postord = [int(x) for x in postord]
inord = input('Input in-order traversal: ').split()
inord = [int(x) for x in inord]

btree = construct_btree(postord, inord)


print('Binary tree constructed.')
print('Verifying:')
print('Post-order traversal: ', end='')
btree.postorder()
print()
print('In-order traversal: ', end='')
btree.inorder()
print()
Program Explanation
1. The user is prompted to enter the post-order and in-order traversals for the binary tree.
2. The function construct_btree is called to build the binary tree.
3. The constructed binary tree’s post-order and in-order traversals are displayed for verification.

Runtime Test Cases


Case 1:
Input post-order traversal: 4 5 2 8 6 7 3 1
Input in-order traversal: 4 2 5 1 6 8 3 7
Binary tree constructed.
Verifying:
Post-order traversal: 4 5 2 8 6 7 3 1
In-order traversal: 4 2 5 1 6 8 3 7

Case 2:
Input post-order traversal: 2 1 3
Input in-order traversal: 2 3 1
Binary tree constructed.
Verifying:
Post-order traversal: 2 1 3
In-order traversal: 2 3 1
2. Python Examples on Heap and Binary Tree Implementation

Python Program to Construct a Binary Search Tree and perform


deletion and inorder traversal
This is a Python program to construct a binary search tree and perform deletion and inorder
traversal.

Problem Description
The program creates a binary search tree and presents a menu to the user to perform
insertion, deletion and inorder traversal operations.

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.

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:
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:
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')

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
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.

Runtime Test Cases


Case 1:
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
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

Case 2:
Menu (this assumes no duplicate keys)
add <key>
remove <key>
inorder
quit
What would you like to do? add 2
What would you like to do? add 8
What would you like to do? inorder
Inorder traversal: 2 8
What would you like to do? add 5
What would you like to do? inorder
Inorder traversal: 2 5 8
What would you like to do? remove 2
What would you like to do? remove 8
What would you like to do? inorder
Inorder traversal: 5
What would you like to do? remove 5
What would you like to do? inorder
Inorder traversal:
What would you like to do? quit

Python Program To Find the Smallest and Largest Elements in


the Binary Search Tree
This is a Python program to find the smallest and largest elements in a binary search tree.

Problem Description
The program presents a menu to the user to perform various operations on a binary search
tree including finding the smallest and largest elements.

Problem Solution
1. Create a class BSTNode with instance variables key, left, right and parent.
2. Define methods insert 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 search takes a key as argument and returns the node with that key in the
BST with the BSTNode object as root.
5. Create a class BSTree with instance variable root.
6. Define methods add, search, get_smallest and get_largest in BSTree.
7. The method add takes a key as argument and adds a node with that key by calling the
insert method of the root node.
8. The method search takes a key as argument and returns the node with that key by calling
the search method of the root node.
9. The method get_smallest returns the smallest node by returning the left-most node.
10. The method get_largest returns the largest node by returning the right-most node.

Program/Source Code
Here is the source code of a Python program to find the smallest and largest elements in a
binary search tree. 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 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:
return None
return self

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

def add(self, key):


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

def search(self, key):


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

def get_smallest(self):
if self.root is not None:
current = self.root
while current.left is not None:
current = current.left
return current.key

def get_largest(self):
if self.root is not None:
current = self.root
while current.right is not None:
current = current.right
return current.key

bstree = BSTree()

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


print('add <key>')
print('smallest')
print('largest')
print('quit')

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)
if operation == 'smallest':
smallest = bstree.get_smallest()
print('Smallest element: {}'.format(smallest))
if operation == 'largest':
largest = bstree.get_largest()
print('Largest element: {}'.format(largest))
elif operation == 'quit':
break
Program Explanation
1. An instance of BSTree is created.
2. The user is presented with a menu to perform various operations including finding the
smallest and largest elements.
3. The corresponding methods are called to perform each operation.
Runtime Test Cases
Case 1:
Menu (this assumes no duplicate keys)
add <key>
smallest
largest
quit
What would you like to do? add 3
What would you like to do? add 2
What would you like to do? add 10
What would you like to do? add 4
What would you like to do? smallest
Smallest element: 2
What would you like to do? largest
Largest element: 10
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <key>
smallest
largest
quit
What would you like to do? add 10
What would you like to do? smallest
Smallest element: 10
What would you like to do? largest
Largest element: 10
What would you like to do? add 4
What would you like to do? add 12
What would you like to do? smallest
Smallest element: 4
What would you like to do? largest
Largest element: 12
What would you like to do? quit

3. Python Examples dealing with the Nodes of a Tree

Python Program to Count Number of Leaf Node in a Tree


This is a Python program to count the number of leaf nodes in a tree.

Problem Description
The program creates a tree and counts the number of leaf nodes in the tree.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, count_leaf_nodes, count_leaf_nodes_helper and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method count_leaf_nodes counts the number of leaf nodes and returns it. It calls the
recursive method count_leaf_nodes_helper.

Program/Source Code
Here is the source code of a Python program to count the number of leaf nodes in a tree.
The program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)

def search(self, key):


if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def count_leaf_nodes(self):
leaf_nodes = []
self.count_leaf_nodes_helper(leaf_nodes)
return len(leaf_nodes)

def count_leaf_nodes_helper(self, leaf_nodes):


if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_nodes_helper(leaf_nodes)

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('count')
print('quit')
while True:
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'count':


if tree is None:
print('Tree is empty.')
else:
count = tree.count_leaf_nodes()
print('Number of leaf nodes: {}'.format(count))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method count_leaf_nodes is called on the tree to calculate the number of leaf nodes
in the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 1
What would you like to do? count
Number of leaf nodes: 2
What would you like to do? quit
Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 2 at root
What would you like to do? add 7 below 2
What would you like to do? add 8 below 7
What would you like to do? add 9 below 8
What would you like to do? count
Number of leaf nodes: 1
What would you like to do? quit

Python Program to Count Number of Leaf Node in a Tree


This is a Python program to count the number of leaf nodes in a tree.

Problem Description
The program creates a tree and counts the number of leaf nodes in the tree.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, count_leaf_nodes, count_leaf_nodes_helper and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method count_leaf_nodes counts the number of leaf nodes and returns it. It calls the
recursive method count_leaf_nodes_helper.

Program/Source Code
Here is the source code of a Python program to count the number of leaf nodes in a tree.
The program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def count_leaf_nodes(self):
leaf_nodes = []
self.count_leaf_nodes_helper(leaf_nodes)
return len(leaf_nodes)

def count_leaf_nodes_helper(self, leaf_nodes):


if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_nodes_helper(leaf_nodes)

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('count')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'count':


if tree is None:
print('Tree is empty.')
else:
count = tree.count_leaf_nodes()
print('Number of leaf nodes: {}'.format(count))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method count_leaf_nodes is called on the tree to calculate the number of leaf nodes
in the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 1
What would you like to do? count
Number of leaf nodes: 2
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 2 at root
What would you like to do? add 7 below 2
What would you like to do? add 8 below 7
What would you like to do? add 9 below 8
What would you like to do? count
Number of leaf nodes: 1
What would you like to do? quit

Python Program to Print Border of given Binary Tree in


Anticlockwise Direction
This is a Python program to print the border of a binary tree in anticlockwise direction.

Problem Description
The program creates a binary tree and prints its border in anticlockwise direction.
Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, inorder, search, print_left_boundary,
print_right_boundary, print_leaves and print_border.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method inorder displays the inorder traversal.
6. The method search returns a node with a specified key.
7. The method print_left_boundary prints the left border of the binary tree except the last
leaf node.
8. The method print_right_boundary prints the right border of the binary tree in reverse
except the last leaf node.
9. The method print_leaves prints the leaf nodes of the binary tree from left to right.
10. The method print_border prints the border of the binary tree by calling the above
methods.

Program/Source Code
Here is the source code of a Python program to print the border of a binary tree in
anticlockwise direction. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

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 insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def print_left_boundary(self):
current = self
while True:
if current.left is not None:
print(current.key, end=' ')
current = current.left
elif current.right is not None:
print(current.key, end=' ')
current = current.right
else:
break

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

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

def print_border(self):
print(self.key, end=' ')
if self.left is not None:
self.left.print_left_boundary()
self.left.print_leaves()
if self.right is not None:
self.right.print_leaves()
self.right.print_right_boundary()

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('border')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'border':


if btree is not None:
print('Border of tree: ')
btree.print_border()
print()

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method print_border is called on the binary tree to print its border.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
border
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? border
Border of tree:
1 2 3
What would you like to do? insert 4 left of 2
What would you like to do? insert 5 right of 2
What would you like to do? insert 6 left of 3
What would you like to do? insert 7 right of 3
What would you like to do? border
Border of tree:
1 2 4 5 6 7 3
What would you like to do? insert 8 left of 4
What would you like to do? insert 9 right of 4
What would you like to do? insert 10 left of 5
What would you like to do? insert 11 right of 5
What would you like to do? insert 12 left of 6
What would you like to do? insert 13 right of 6
What would you like to do? insert 14 left of 7
What would you like to do? insert 15 right of 7
What would you like to do? border
Border of tree:
1 2 4 8 9 10 11 12 13 14 15 7 3
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
border
quit
What would you like to do? insert 1 at root
What would you like to do? insert 2 left of 1
What would you like to do? insert 3 left of 2
What would you like to do? insert 4 right of 2
What would you like to do? insert 5 left of 4
What would you like to do? insert 6 right of 4
What would you like to do? insert 7 right of 1
What would you like to do? insert 8 right of 7
What would you like to do? border
Border of tree:
1 2 3 5 6 8 7
What would you like to do? quit

Python Program to Count Number of Non Leaf Nodes of a given


Tree
This is a Python program to count the number of non-leaf nodes in a tree.

Problem Description
The program creates a tree and counts the number of non-leaf nodes in the tree.
Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, count_nonleaf_nodes and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method count_nonleaf_nodes counts the number of non-leaf nodes and returns it.

Program/Source Code
Here is the source code of a Python program to count the number of non-leaf nodes in a
tree. The program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)

def search(self, key):


if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def count_nonleaf_nodes(self):
nonleaf_count = 0
if self.children != []:
nonleaf_count = 1
for child in self.children:
nonleaf_count = nonleaf_count + child.count_nonleaf_nodes()
return nonleaf_count

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('count')
print('quit')
while True:
do = input('What would you like to do? ').split()

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'count':


if tree is None:
print('Tree is empty.')
else:
count = tree.count_nonleaf_nodes()
print('Number of nonleaf nodes: {}'.format(count))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method count_nonleaf_nodes is called on the tree to calculate the number of non-
leaf nodes in the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 1 at root
What would you like to do? count
Number of nonleaf nodes: 0
What would you like to do? add 2 below 1
What would you like to do? add 3 below 1
What would you like to do? count
Number of nonleaf nodes: 1
What would you like to do? add 4 below 2
What would you like to do? count
Number of nonleaf nodes: 2
What would you like to do? add 5 below 4
What would you like to do? count
Number of nonleaf nodes: 3
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
count
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 2
What would you like to do? add 4 below 3
What would you like to do? add 5 below 4
What would you like to do? count
Number of nonleaf nodes: 4
What would you like to do? add 6 below 4
What would you like to do? count
Number of nonleaf nodes: 4
What would you like to do? add 7 below 6
What would you like to do? count
Number of nonleaf nodes: 5
What would you like to do? quit

4. Python Examples on Special Properties of Binary Trees

Python Program to Find the Sum of all Nodes in a Tree


This is a Python program to find the sum of all nodes in a tree.

Problem Description
The program creates a tree and finds the sum of all nodes in the tree.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, sum_nodes and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method sum_nodes finds the sum of all nodes in the tree.
Program/Source Code
Here is the source code of a Python program to find the sum of all nodes in a tree. The
program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)

def search(self, key):


if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def sum_nodes(self):
summation = self.key
for child in self.children:
summation = summation + child.sum_nodes()
return summation

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('sum')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'sum':


if tree is None:
print('Tree is empty.')
else:
summation = tree.sum_nodes()
print('Sum of all nodes: {}'.format(summation))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method sum_nodes is called on the tree to calculate the sum of all nodes in the tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
sum
quit
What would you like to do? sum
Tree is empty.
What would you like to do? add 3 at root
What would you like to do? sum
Sum of all nodes: 3
What would you like to do? add 4 below 3
What would you like to do? sum
Sum of all nodes: 7
What would you like to do? add 5 below 3
What would you like to do? add 10 below 4
What would you like to do? sum
Sum of all nodes: 22
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
sum
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 1
What would you like to do? add 4 below 1
What would you like to do? add 5 below 2
What would you like to do? add 6 below 3
What would you like to do? add 7 below 4
What would you like to do? sum
Sum of all nodes: 28
What would you like to do? quit

5. Python Examples on BFS and DFS Traversals

Python Program to Construct a Tree & Perform Insertion,


Deletion, Display
This is a Python program to construct a tree and perform insertion, deletion and display
operations.

Problem Description
The program creates a tree and presents a menu to the user to perform insertion, deletion
and display operations.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, remove, bfs_display and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method remove removes the current node from the tree.
7. The method bfs_display displays the BFS traversal of the tree.

Program/Source Code
Here is the source code of a Python program to construct a tree and perform insertion,
deletion and display operations. The program output is shown below.
class Tree:
def __init__(self, data=None, parent=None):
self.key = data
self.children = []
self.parent = parent

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)
def search(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def remove(self):
parent = self.parent
index = parent.children.index(self)
parent.children.remove(self)
for child in reversed(self.children):
parent.children.insert(index, child)
child.parent = parent

def bfs_display(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')

tree = None

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


print('add <data> at root')
print('add <data> below <data>')
print('remove <data>')
print('display')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
new_node.parent = ref_node
ref_node.add(new_node)

elif operation == 'remove':


data = int(do[1])
to_remove = tree.search(data)
if tree == to_remove:
if tree.children == []:
tree = None
else:
leaf = tree.children[0]
while leaf.children != []:
leaf = leaf.children[0]
leaf.parent.children.remove(leaf)
leaf.parent = None
leaf.children = tree.children
tree = leaf
else:
to_remove.remove()

elif operation == 'display':


if tree is not None:
print('BFS traversal display: ', end='')
tree.bfs_display()
print()
else:
print('Tree is empty.')

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. If the node to be removed is the root node, the removal is carried out by finding a leaf
node and replacing the root with it. If the node to be removed is not the root node then the
remove method is called on the node.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
remove <data>
display
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? add 3 below 1
What would you like to do? add 4 below 2
What would you like to do? add 5 below 2
What would you like to do? display
BFS traversal display: 1 2 3 4 5
What would you like to do? remove 1
What would you like to do? display
BFS traversal display: 4 2 3 5
What would you like to do? remove 5
What would you like to do? display
BFS traversal display: 4 2 3
What would you like to do? remove 4
What would you like to do? display
BFS traversal display: 2 3
What would you like to do? remove 3
What would you like to do? remove 2
What would you like to do? display
Tree is empty.
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
remove <data>
display
quit
What would you like to do? add 5 at root
What would you like to do? add 7 below 5
What would you like to do? add 9 below 7
What would you like to do? add 11 below 9
What would you like to do? add 12 below 7
What would you like to do? display
BFS traversal display: 5 7 9 12 11
What would you like to do? remove 9
What would you like to do? display
BFS traversal display: 5 7 11 12
What would you like to do? remove 12
What would you like to do? display
BFS traversal display: 5 7 11
What would you like to do? remove 7
What would you like to do? display
BFS traversal display: 5 11
What would you like to do? remove 5
What would you like to do? display
BFS traversal display: 11
What would you like to do? quit

Python Program to Check whether a Tree is a Binary Search


Tree
This is a Python program to check whether a binary tree is a binary search tree.

Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including checking whether the tree is a binary search tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, search and is_bst_p.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method search returns a node with a specified key.
6. The method is_bst_p returns True iff the binary tree with the current object as root is a
binary search tree.

Program/Source Code
Here is the source code of a Python program to check whether a binary tree is a binary
search tree. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def is_bst_p(self):
if self.left is not None:
if self.key < self.left.key:
return False
elif not self.left.is_bst_p():
return False
if self.right is not None:
if self.key > self.right.key:
return False
elif not self.right.is_bst_p():
return False
return True

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('bst')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'bst':


if btree is not None:
if btree.is_bst_p():
print('Tree is a binary search tree.')
else:
print('Tree is not a binary search tree.')
else:
print('Tree is empty.')

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the binary tree.
3. The corresponding methods are called to perform each operation.
4. The method is_bst_p is called on the tree to determine whether it is a binary search tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 1 at root
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 0 left of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 2 right of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 3 left of 2
What would you like to do? bst
Tree is not a binary search tree.
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 5 at root
What would you like to do? insert 1 left of 5
What would you like to do? insert 10 right of 5
What would you like to do? insert 0 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 15 right of 10
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? quit

Python Program to Check whether a Tree is a Binary Search


Tree
This is a Python program to check whether a binary tree is a binary search tree.
Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including checking whether the tree is a binary search tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, search and is_bst_p.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method search returns a node with a specified key.
6. The method is_bst_p returns True iff the binary tree with the current object as root is a
binary search tree.

Program/Source Code
Here is the source code of a Python program to check whether a binary tree is a binary
search tree. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def is_bst_p(self):
if self.left is not None:
if self.key < self.left.key:
return False
elif not self.left.is_bst_p():
return False
if self.right is not None:
if self.key > self.right.key:
return False
elif not self.right.is_bst_p():
return False
return True

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('bst')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'bst':


if btree is not None:
if btree.is_bst_p():
print('Tree is a binary search tree.')
else:
print('Tree is not a binary search tree.')
else:
print('Tree is empty.')

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the binary tree.
3. The corresponding methods are called to perform each operation.
4. The method is_bst_p is called on the tree to determine whether it is a binary search tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 1 at root
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 0 left of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 2 right of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 3 left of 2
What would you like to do? bst
Tree is not a binary search tree.
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 5 at root
What would you like to do? insert 1 left of 5
What would you like to do? insert 10 right of 5
What would you like to do? insert 0 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 15 right of 10
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? quit

Python Program to Check whether a Tree is a Binary Search


Tree
This is a Python program to check whether a binary tree is a binary search tree.
Problem Description
The program creates a binary tree and presents a menu to the user to perform operations
on the tree including checking whether the tree is a binary search tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, search and is_bst_p.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method search returns a node with a specified key.
6. The method is_bst_p returns True iff the binary tree with the current object as root is a
binary search tree.

Program/Source Code
Here is the source code of a Python program to check whether a binary tree is a binary
search tree. The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

def insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def is_bst_p(self):
if self.left is not None:
if self.key < self.left.key:
return False
elif not self.left.is_bst_p():
return False
if self.right is not None:
if self.key > self.right.key:
return False
elif not self.right.is_bst_p():
return False
return True

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('bst')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'bst':


if btree is not None:
if btree.is_bst_p():
print('Tree is a binary search tree.')
else:
print('Tree is not a binary search tree.')
else:
print('Tree is empty.')

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the binary tree.
3. The corresponding methods are called to perform each operation.
4. The method is_bst_p is called on the tree to determine whether it is a binary search tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 1 at root
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 0 left of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 2 right of 1
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? insert 3 left of 2
What would you like to do? bst
Tree is not a binary search tree.
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
bst
quit
What would you like to do? insert 5 at root
What would you like to do? insert 1 left of 5
What would you like to do? insert 10 right of 5
What would you like to do? insert 0 left of 1
What would you like to do? insert 3 right of 1
What would you like to do? insert 15 right of 10
What would you like to do? bst
Tree is a binary search tree.
What would you like to do? quit

Python Program to Display the Nodes of a Tree using BFS


Traversal
This is a Python program to display the nodes of a tree using BFS traversal.
Problem Description
The program creates a tree and presents a menu to the user to perform various operations
including printing its BFS traversal.

Problem Solution
1. Create a class Tree with instance variables key and children.
2. Define methods set_root, add, bfs and search.
3. The method set_root takes a key as argument and sets the instance variable key equal to
it.
4. The method add appends a node to the list children.
5. The method search returns a node with a specified key.
6. The method bfs prints the BFS traversal of the tree. It uses a queue to do the traversal.

Program/Source Code
Here is the source code of a Python program to display the nodes of a tree using BFS
traversal. The program output is shown below.
class Tree:
def __init__(self, data=None):
self.key = data
self.children = []

def set_root(self, data):


self.key = data

def add(self, node):


self.children.append(node)

def search(self, key):


if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None

def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')

tree = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('bfs')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
tree = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if tree is not None:
ref_node = tree.search(key)
if ref_node is None:
print('No such key.')
continue
ref_node.add(new_node)

elif operation == 'bfs':


if tree is None:
print('Tree is empty.')
else:
print('BFS traversal: ', end='')
tree.bfs()
print()

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The method bfs is called on the tree to print its breadth-first traversal.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
bfs
quit
What would you like to do? add 1 at root
What would you like to do? add 2 below 1
What would you like to do? bfs
BFS traversal: 1 2
What would you like to do? add 3 below 1
What would you like to do? add 10 below 2
What would you like to do? add 12 below 2
What would you like to do? add 14 below 3
What would you like to do? add 7 below 14
What would you like to do? bfs
BFS traversal: 1 2 3 10 12 14 7
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
bfs
quit
What would you like to do? add 5 at root
What would you like to do? add 7 below 5
What would you like to do? add 8 below 5
What would you like to do? add 4 below 7
What would you like to do? add 3 below 7
What would you like to do? add 1 below 8
What would you like to do? add 2 below 1
What would you like to do? bfs
BFS traversal: 5 7 8 4 3 1 2
What would you like to do? quit

6. Python Examples on Inorder Traversal of a Binary Tree

Python Program to Find the Sum of All Nodes in a Binary Tree


This is a Python program to find the sum of all the nodes in a binary tree.

Problem Description
The program creates a binary tree and finds the sum of the nodes in the tree.

Problem Solution
1. Create a class BinaryTree with instance variables key, left and right.
2. Define methods set_root, insert_left, insert_right, inorder and search.
3. The method set_root takes a key as argument and sets the variable key equal to it.
4. The methods insert_left and insert_right insert a node as the left and right child
respectively.
5. The method inorder displays the inorder traversal.
6. The method search returns a node with a specified key.
7. Define the function sum_nodes which takes a binary tree as argument.
8. The recursive function sum_nodes returns the sum of the nodes in the binary tree.

Program/Source Code
Here is the source code of a Python program to find the sum of the nodes in a binary tree.
The program output is shown below.
class BinaryTree:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None

def set_root(self, key):


self.key = key

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 insert_left(self, new_node):


self.left = new_node

def insert_right(self, new_node):


self.right = new_node

def search(self, key):


if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None

def sum_nodes(node):
if node is None:
return 0
return node.key + sum_nodes(node.left) + sum_nodes(node.right)

btree = None

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


print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('sum')
print('quit')

while True:
print('inorder traversal of binary tree: ', end='')
if btree is not None:
btree.inorder()
print()

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree is not None:
ref_node = btree.search(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_left(new_node)
elif suboperation == 'right':
ref_node.insert_right(new_node)

elif operation == 'sum':


print('Sum of nodes in tree: {}'.format(sum_nodes(btree)))

elif operation == 'quit':


break
Program Explanation
1. A variable is created to store the binary tree.
2. The user is presented with a menu to perform operations on the tree.
3. The corresponding methods are called to perform each operation.
4. The function sum_nodes is called to find the sum of the nodes in the binary tree.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
sum
quit
inorder traversal of binary tree:
What would you like to do? insert 3 at root
inorder traversal of binary tree: 3
What would you like to do? insert 7 left of 3
inorder traversal of binary tree: 7 3
What would you like to do? sum
Sum of nodes in tree: 10
inorder traversal of binary tree: 7 3
What would you like to do? quit

Case 2:
Menu (this assumes no duplicate keys)
insert <data> at root
insert <data> left of <data>
insert <data> right of <data>
sum
quit
inorder traversal of binary tree:
What would you like to do? insert 2 at root
inorder traversal of binary tree: 2
What would you like to do? insert 10 left of 2
inorder traversal of binary tree: 10 2
What would you like to do? insert 1 right of 2
inorder traversal of binary tree: 10 2 1
What would you like to do? insert 5 left of 1
inorder traversal of binary tree: 10 2 5 1
What would you like to do? sum
Sum of nodes in tree: 18
inorder traversal of binary tree: 10 2 5 1
What would you like to do? quit

15. Python Programs on Heap

Python Program to Implement Binary Heap


This is a Python program to implement a binary heap.

Problem Description
The program creates a binary max-heap and presents a menu to the user to perform
various operations on it.

Problem Solution
1. Create a class BinaryHeap with an instance variable items set to an empty list. This
empty list is used to store the binary heap.
2. Define methods size, parent, left, right, get, get_max, extract_max, max_heapify, swap
and insert.
3. The method size returns the number of elements in the heap.
4. The method parent takes an index as argument and returns the index of the parent.
5. The method left takes an index as argument and returns the index of its left child.
6. The method right takes an index as argument and returns the index of its right child.
7. The method get takes an index as argument and returns the key at the index.
8. The method get_max returns the maximum element in the heap by returning the first
element in the list items.
9. The method extract_max returns the the maximum element in the heap and removes it.
10. The method max_heapify 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.
11. The method swap takes two indexes as arguments and swaps the corresponding
elements in the heap.
12. The method insert takes a key as argument and adds that key to the heap.

Program/Source Code
Here is the source code of a Python program to implement a binary heap. The program
output is shown below.
class BinaryHeap:
def __init__(self):
self.items = []

def size(self):
return len(self.items)

def parent(self, i):


return (i - 1)//2

def left(self, i):


return 2*i + 1

def right(self, i):


return 2*i + 2

def get(self, i):


return self.items[i]

def get_max(self):
if self.size() == 0:
return None
return self.items[0]

def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest

def max_heapify(self, i):


l = self.left(i)
r = self.right(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)

def swap(self, i, j):


self.items[i], self.items[j] = self.items[j], self.items[i]

def insert(self, key):


index = self.size()
self.items.append(key)

while (index != 0):


p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p

bheap = BinaryHeap()

print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(bheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(bheap.extract_max()))

elif operation == 'quit':


break
Program Explanation
1. Create an instance of BinaryHeap.
2. The user is presented with a menu to perform various operations on the heap.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data>
max get
max extract
quit
What would you like to do? insert 5
What would you like to do? insert 3
What would you like to do? insert -3
What would you like to do? insert 10
What would you like to do? insert 8
What would you like to do? max get
Maximum value: 10
What would you like to do? max extract
Maximum value removed: 10
What would you like to do? max extract
Maximum value removed: 8
What would you like to do? max extract
Maximum value removed: 5
What would you like to do? max extract
Maximum value removed: 3
What would you like to do? max get
Maximum value: -3
What would you like to do? quit

Case 2:
Menu
insert <data>
max get
max extract
quit
What would you like to do? insert 3
What would you like to do? insert 11
What would you like to do? insert 5
What would you like to do? max extract
Maximum value removed: 11
What would you like to do? max get
Maximum value: 5
What would you like to do? max extract
Maximum value removed: 5
What would you like to do? insert 15
What would you like to do? max get
Maximum value: 15
What would you like to do? quit

Python Program to Implement Binomial Tree


This is a Python program to implement a binomial tree.

Problem Description
The program creates binomial trees and presents a menu to the user to perform operations
on these trees.

Problem Solution
1. Create a class BinomialTree with instance variables key, children and order. children is
set to an empty list and order is set to 0 when an object is instantiated.
2. Define method add_at_end which takes a binomial tree of the same order as argument
and adds it to the current tree, increasing its order by 1.

Program/Source Code
Here is the source code of a Python program to implement a binomial tree. The program
output is shown below.
class BinomialTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0

def add_at_end(self, t):


self.children.append(t)
self.order = self.order + 1

trees = []

print('Menu')
print('create <key>')
print('combine <index1> <index2>')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'create':
key = int(do[1])
btree = BinomialTree(key)
trees.append(btree)
print('Binomial tree created.')
elif operation == 'combine':
index1 = int(do[1])
index2 = int(do[2])
if trees[index1].order == trees[index2].order:
trees[index1].add_at_end(trees[index2])
del trees[index2]
print('Binomial trees combined.')
else:
print('Orders of the trees need to be the same.')

elif operation == 'quit':


break

print('{:>8}{:>12}{:>8}'.format('Index', 'Root key', 'Order'))


for index, t in enumerate(trees):
print('{:8d}{:12d}{:8d}'.format(index, t.key, t.order))
Program Explanation
1. An empty list is created to store the binomial trees.
2. The user is presented with a menu to create and combine two binomial trees.
3. Only trees of the same order k are allowed to combine to form a tree of order k + 1.
4. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
create <key>
combine <index1> <index2>
quit
What would you like to do? create 7
Binomial tree created.
Index Root key Order
0 7 0
What would you like to do? create 3
Binomial tree created.
Index Root key Order
0 7 0
1 3 0
What would you like to do? create 4
Binomial tree created.
Index Root key Order
0 7 0
1 3 0
2 4 0
What would you like to do? create 1
Binomial tree created.
Index Root key Order
0 7 0
1 3 0
2 4 0
3 1 0
What would you like to do? combine 0 1
Binomial trees combined.
Index Root key Order
0 7 1
1 4 0
2 1 0
What would you like to do? combine 1 2
Binomial trees combined.
Index Root key Order
0 7 1
1 4 1
What would you like to do? combine 0 1
Binomial trees combined.
Index Root key Order
0 7 2
What would you like to do? quit

Case 2:
Menu
create <key>
combine <index1> <index2>
quit
What would you like to do? create 2
Binomial tree created.
Index Root key Order
0 2 0
What would you like to do? create 3
Binomial tree created.
Index Root key Order
0 2 0
1 3 0
What would you like to do? create 1
Binomial tree created.
Index Root key Order
0 2 0
1 3 0
2 1 0
What would you like to do? combine 2 0
Binomial trees combined.
Index Root key Order
0 3 0
1 1 1
What would you like to do? quit

Python Program to Implement Binomial Heap


This is a Python program to implement a binomial heap.

Problem Description
The program creates a binomial min-heap and presents a menu to the user to perform
various operations on it.

Problem Solution
1. Create a class BinomialTree with instance variables key, children and order. children is
set to an empty list and order is set to 0 when an object is instantiated.
2. Define method add_at_end which takes a binomial tree of the same order as argument
and adds it to the current tree, increasing its order by 1.
3. Create a class BinomialHeap with an instance variable trees set to an empty list. This list
will contain the set of binomial trees.
4. Define methods get_min, extract_min, combine_roots, merge and insert.
5. The method get_min returns the minimum element in the heap by returning the key of the
smallest root in the list trees.
6. The method merge takes a heap as argument and merges it with the current heap. It
iterates through the sorted (by order of each tree) list of trees and merges any two trees
with the same order. It also checks for the case for three consecutive trees of the same
order and merges the last two trees.
7. The method combine_roots takes a heap as argument and combines the current heap’s
list of trees with its list of trees and sorts them by order of each tree.
8. The method extract_min removes and returns the minimum element in the current heap.
It does so by removing the tree with the smallest root from the current heap’s list of trees
and creating a heap with the children of the smallest root as its list of trees. This new heap
is then merged with the current heap.
9. The method insert takes a key as argument and adds a node with that key to the heap. It
does so by creating an order 0 heap with that key and then merging it with the current heap.

Program/Source Code
Here is the source code of a Python program to implement a binomial heap. The program
output is shown below.
class BinomialTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0

def add_at_end(self, t):


self.children.append(t)
self.order = self.order + 1

class BinomialHeap:
def __init__(self):
self.trees = []

def extract_min(self):
if self.trees == []:
return None
smallest_node = self.trees[0]
for tree in self.trees:
if tree.key < smallest_node.key:
smallest_node = tree
self.trees.remove(smallest_node)
h = BinomialHeap()
h.trees = smallest_node.children
self.merge(h)
return smallest_node.key

def get_min(self):
if self.trees == []:
return None
least = self.trees[0].key
for tree in self.trees:
if tree.key < least:
least = tree.key
return least

def combine_roots(self, h):


self.trees.extend(h.trees)
self.trees.sort(key=lambda tree: tree.order)

def merge(self, h):


self.combine_roots(h)
if self.trees == []:
return
i = 0
while i < len(self.trees) - 1:
current = self.trees[i]
after = self.trees[i + 1]
if current.order == after.order:
if (i + 1 < len(self.trees) - 1
and self.trees[i + 2].order == after.order):
after_after = self.trees[i + 2]
if after.key < after_after.key:
after.add_at_end(after_after)
del self.trees[i + 2]
else:
after_after.add_at_end(after)
del self.trees[i + 1]
else:
if current.key < after.key:
current.add_at_end(after)
del self.trees[i + 1]
else:
after.add_at_end(current)
del self.trees[i]
i = i + 1

def insert(self, key):


g = BinomialHeap()
g.trees.append(BinomialTree(key))
self.merge(g)

bheap = BinomialHeap()

print('Menu')
print('insert <data>')
print('min get')
print('min extract')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'min':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Minimum value: {}'.format(bheap.get_min()))
elif suboperation == 'extract':
print('Minimum value removed: {}'.format(bheap.extract_min()))

elif operation == 'quit':


break
Program Explanation
1. Create an instance of BinomialHeap.
2. The user is presented with a menu to perform various operations on the heap.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data>
min get
min extract
quit
What would you like to do? insert 3
What would you like to do? insert 7
What would you like to do? insert 1
What would you like to do? insert 4
What would you like to do? min get
Minimum value: 1
What would you like to do? min extract
Minimum value removed: 1
What would you like to do? min extract
Minimum value removed: 3
What would you like to do? min extract
Minimum value removed: 4
What would you like to do? min extract
Minimum value removed: 7
What would you like to do? min extract
Minimum value removed: None
What would you like to do? quit

Case 2:
Menu
insert <data>
min get
min extract
quit
What would you like to do? insert 10
What would you like to do? insert 12
What would you like to do? insert 5
What would you like to do? insert 6
What would you like to do? min get
Minimum value: 5
What would you like to do? insert 3
What would you like to do? min get
Minimum value: 3
What would you like to do? insert 8
What would you like to do? min extract
Minimum value removed: 3
What would you like to do? min extract
Minimum value removed: 5
What would you like to do? insert 1
What would you like to do? min extract
Minimum value removed: 1
What would you like to do? quit

Python Program to Implement Fibonacci Heap


This is a Python program to implement a Fibonacci heap.

Problem Description
The program creates a Fibonacci min-heap and presents a menu to the user to perform
various operations on it.

Problem Solution
1. Create a class FibonacciTree with instance variables key, children and order. children is
set to an empty list and order is set to 0 when an object is instantiated.
2. Define method add_at_end which takes a Fibonacci tree of the same order as argument
and adds it to the current tree, increasing its order by 1.
3. Create a class FibonacciHeap with instance variables trees, least and count. The variable
trees is set to an empty list, least to None and count to 0 on instantiation. The list will
contain the set of Fibonacci trees, least will point to the tree with the least element and
count will contain the number of nodes in the heap.
4. Define methods get_min, extract_min, consolidate and insert.
5. The method get_min returns the minimum element in the heap by returning the key of the
variable least.
6. The method extract_min removes and returns the minimum element in the current heap.
It does so by removing the tree that least points to from the current heap’s list of trees and
then appending the children of the removed node to the list of trees. The method
consolidate is then called before returning the key of the least element.
7. The method consolidate combines the trees in the heap such that there is at most one
tree of any order. It also sets the variable least of the heap to the tree with the smallest
element.
8. The method insert takes a key as argument and adds a node with that key to the heap. It
does so by creating an order 0 Fibonacci tree with that key and appending it to list of trees
of the heap. It then updates count and, if required, least.
9. Define the function floor_log2 which takes a number as argument and returns the floor of
its base 2 logarithm.

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

class FibonacciTree:
def __init__(self, key):
self.key = key
self.children = []
self.order = 0

def add_at_end(self, t):


self.children.append(t)
self.order = self.order + 1

class FibonacciHeap:
def __init__(self):
self.trees = []
self.least = None
self.count = 0

def insert(self, key):


new_tree = FibonacciTree(key)
self.trees.append(new_tree)
if (self.least is None or key < self.least.key):
self.least = new_tree
self.count = self.count + 1

def get_min(self):
if self.least is None:
return None
return self.least.key

def extract_min(self):
smallest = self.least
if smallest is not None:
for child in smallest.children:
self.trees.append(child)
self.trees.remove(smallest)
if self.trees == []:
self.least = None
else:
self.least = self.trees[0]
self.consolidate()
self.count = self.count - 1
return smallest.key

def consolidate(self):
aux = (floor_log2(self.count) + 1)*[None]

while self.trees != []:


x = self.trees[0]
order = x.order
self.trees.remove(x)
while aux[order] is not None:
y = aux[order]
if x.key > y.key:
x, y = y, x
x.add_at_end(y)
aux[order] = None
order = order + 1
aux[order] = x

self.least = None
for k in aux:
if k is not None:
self.trees.append(k)
if (self.least is None
or k.key < self.least.key):
self.least = k

def floor_log2(x):
return math.frexp(x)[1] - 1

fheap = FibonacciHeap()

print('Menu')
print('insert <data>')
print('min get')
print('min extract')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
fheap.insert(data)
elif operation == 'min':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Minimum value: {}'.format(fheap.get_min()))
elif suboperation == 'extract':
print('Minimum value removed: {}'.format(fheap.extract_min()))

elif operation == 'quit':


break
Program Explanation
1. Create an instance of FibonacciHeap.
2. The user is presented with a menu to perform various operations on the heap.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu
insert <data>
min get
min extract
quit
What would you like to do? insert 3
What would you like to do? insert 2
What would you like to do? insert 7
What would you like to do? min get
Minimum value: 2
What would you like to do? min extract
Minimum value removed: 2
What would you like to do? min extract
Minimum value removed: 3
What would you like to do? min extract
Minimum value removed: 7
What would you like to do? min extract
Minimum value removed: None
What would you like to do? quit

Case 2:
Menu
insert <data>
min get
min extract
quit
What would you like to do? insert 1
What would you like to do? insert 2
What would you like to do? insert 3
What would you like to do? insert 4
What would you like to do? insert 0
What would you like to do? min extract
Minimum value removed: 0
What would you like to do? min extract
Minimum value removed: 1
What would you like to do? min extract
Minimum value removed: 2
What would you like to do? min extract
Minimum value removed: 3
What would you like to do? min extract
Minimum value removed: 4
What would you like to do? quit

ython Program to Implement Ternary Heap


This is a Python program to implement a ternary heap.

Problem Description
The program creates a ternary max-heap and presents a menu to the user to perform
various operations on it.

Problem Solution
1. Create a class TernaryHeap with an instance variable items set to an empty list. This
empty list is used to store the ternary heap.
2. Define methods size, parent, left, mid, right, get, get_max, extract_max, max_heapify,
swap and insert.
3. The method size returns the number of elements in the heap.
4. The method parent takes an index as argument and returns the index of the parent.
5. The method left takes an index as argument and returns the index of its left child.
6. The method mid takes an index as argument and returns the index of its middle child.
7. The method right takes an index as argument and returns the index of its right child.
8. The method get takes an index as argument and returns the key at the index.
9. The method get_max returns the maximum element in the heap by returning the first
element in the list items.
10. The method extract_max returns the the maximum element in the heap and removes it.
11. The method max_heapify 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.
12. The method swap takes two indexes as arguments and swaps the corresponding
elements in the heap.
13. The method insert takes a key as argument and adds that key to the heap.

Program/Source Code
Here is the source code of a Python program to implement a ternary heap. The program
output is shown below.
class TernaryHeap:
def __init__(self):
self.items = []

def size(self):
return len(self.items)
def parent(self, i):
return (i - 1)//3

def left(self, i):


return 3*i + 1

def mid(self, i):


return 3*i + 2

def right(self, i):


return 3*i + 3

def get(self, i):


return self.items[i]

def get_max(self):
if self.size() == 0:
return None
return self.items[0]

def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest

def max_heapify(self, i):


l = self.left(i)
r = self.right(i)
m = self.mid(i)
if (l <= self.size() - 1 and self.get(l) > self.get(i)):
largest = l
else:
largest = i
if (m <= self.size() - 1 and self.get(m) > self.get(largest)):
largest = m
if (r <= self.size() - 1 and self.get(r) > self.get(largest)):
largest = r
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)

def swap(self, i, j):


self.items[i], self.items[j] = self.items[j], self.items[i]

def insert(self, key):


index = self.size()
self.items.append(key)

while (index != 0):


p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p

theap = TernaryHeap()

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


print('insert <data>')
print('max get')
print('max extract')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
theap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(theap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(theap.extract_max()))

elif operation == 'quit':


break
Program Explanation
1. Create an instance of TernaryHeap.
2. The user is presented with a menu to perform various operations on the heap.
3. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Menu (this assumes no duplicate keys)
insert <data>
max get
max extract
quit
What would you like to do? insert 3
What would you like to do? insert 1
What would you like to do? insert 7
What would you like to do? max extract
Maximum value removed: 7
What would you like to do? max extract
Maximum value removed: 3
What would you like to do? max extract
Maximum value removed: 1
What would you like to do? max extract
Maximum value removed: None
What would you like to do? quit
Case 2:
Menu (this assumes no duplicate keys)
insert <data>
max get
max extract
quit
What would you like to do? insert 10
What would you like to do? insert 2
What would you like to do? max get
Maximum value: 10
What would you like to do? insert 15
What would you like to do? max extract
Maximum value removed: 15
What would you like to do? max extract
Maximum value removed: 10
What would you like to do? quit

Python Program to Implement D-ary-Heap


This is a Python program to implement a d-ary heap.

Problem Description
The program creates a d-ary max-heap and presents a menu to the user to perform various
operations on it.

Problem Solution
1. Create a class D_aryHeap with instance variables items set to an empty list and d. The
list items is used to store the d-ary heap while d represents the number of children each
node can have in the heap.
2. Define methods size, parent, child, get, get_max, extract_max, max_heapify, swap and
insert.
3. The method size returns the number of elements in the heap.
4. The method parent takes an index as argument and returns the index of the parent.
5. The method child takes an index and position as arguments and returns the index of the
child at that position from the left.
6. The method get takes an index as argument and returns the key at the index.
7. The method get_max returns the maximum element in the heap by returning the first
element in the list items.
8. The method extract_max returns the the maximum element in the heap and removes it.
9. The method max_heapify 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.
10. The method swap takes two indexes as arguments and swaps the corresponding
elements in the heap.
11. The method insert takes a key as argument and adds that key to the heap.

Program/Source Code
Here is the source code of a Python program to implement a d-ary heap. The program
output is shown below.
class D_aryHeap:
def __init__(self, d):
self.items = []
self.d = d

def size(self):
return len(self.items)

def parent(self, i):


return (i - 1)//self.d

def child(self, index, position):


return index*self.d + (position + 1)

def get(self, i):


return self.items[i]

def get_max(self):
if self.size() == 0:
return None
return self.items[0]

def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest

def max_heapify(self, i):


largest = i
for j in range(self.d):
c = self.child(i, j)
if (c < self.size() and self.get(c) > self.get(largest)):
largest = c
if (largest != i):
self.swap(largest, i)
self.max_heapify(largest)

def swap(self, i, j):


self.items[i], self.items[j] = self.items[j], self.items[i]

def insert(self, key):


index = self.size()
self.items.append(key)
while (index != 0):
p = self.parent(index)
if self.get(p) < self.get(index):
self.swap(p, index)
index = p

d = int(input('Enter the value of D: '));


dheap = D_aryHeap(d)

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


print('insert <data>')
print('max get')
print('max extract')
print('quit')

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

operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
dheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(dheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(dheap.extract_max()))

elif operation == 'quit':


break
Program Explanation
1. The user is prompted to enter the value of the number of children for each node in the
heap.
2. An instance of D_aryHeap is created.
3. The user is presented with a menu to perform various operations on the heap.
4. The corresponding methods are called to perform each operation.

Runtime Test Cases


Case 1:
Enter the value of D: 5
Menu (this assumes no duplicate keys)
insert <data>
max get
max extract
quit
What would you like to do? insert 3
What would you like to do? insert 4
What would you like to do? insert 11
What would you like to do? insert 7
What would you like to do? max get
Maximum value: 11
What would you like to do? max extract
Maximum value removed: 11
What would you like to do? max extract
Maximum value removed: 7
What would you like to do? max extract
Maximum value removed: 4
What would you like to do? max extract
Maximum value removed: 3
What would you like to do? max extract
Maximum value removed: None
What would you like to do? quit

Case 2:
Enter the value of D: 2
Menu (this assumes no duplicate keys)
insert <data>
max get
max extract
quit
What would you like to do? insert 1
What would you like to do? insert 3
What would you like to do? insert 2
What would you like to do? max extract
Maximum value removed: 3
What would you like to do? max extract
Maximum value removed: 2
What would you like to do? max extract
Maximum value removed: 1
What would you like to do? quit

16. Python Programming Examples on Graphs

1. Python Programming examples on “Connected Components using BFS”

Python Program to Implement Graph


This is a Python program to implement a graph.

Problem Description
The program creates a Graph data structure and allows the user to add vertices and edges to it.

Problem Solution
1. Create a class Graph.
2. Create a class Vertex.
3. Each object of Vertex has two instance variables, key and points_to.
4. key is the value of the Vertex object.
5. points_to is a dictionary with keys being the Vertex objects that the current object points to. Each
such Vertex object pointed to by the current object is mapped to the weight of the corresponding
directed edge.
6. The class Vertex provides methods to get the key, to add a neighbour, to get all neighbours, to get
the weight of a directed edge and to test whether a vertex is a neigbour of the current Vertex object.
7. The class Graph has one instance variable, vertices.
8. vertices is a dictionary that contains vertex values mapped to their corresponding Vertex objects.
Each Vertex object also stores the vertex value in its key instance variable.
9. The class Graph provides methods to add a vertex with a given key, get the Vertex object with a
given key, test whether a vertex with a given key is in the Graph, add an edge between two vertices
given their keys and weight and test whether an edge exists between two vertices given their keys.
The __iter__ method is implemented to allow iteration over the Vertex objects in the graph.
10. If whenever edge (u, v) is added to the graph, the reverse edge (v, u) is also added, then this
would become the implementation of an undirected graph.

Program/Source Code
Here is the source code of a Python program to implement a graph. The program output is shown
below.
class Graph:
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_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])
def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> [weight]')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
if len(do) == 5:
weight = int(do[4])
g.add_edge(src, dest, weight)
else:
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

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

elif operation == 'quit':


break
Program Explanation
1. An instance of Graph is created.
2. The user is presented with a menu to perform various operations on the graph.
3. The corresponding methods are called to perform each operation.
4. The operations are: add vertex with a given key, add edge from a source vertex to a destination
vertex (optionally with weight specified, otherwise weight=1 is assumed) and to display the all
vertices and edges in the graph.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest> [weight]
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? display
Vertices: 1 2
Edges:

What would you like to do? add edge 1 2


What would you like to do? add vertex 3
What would you like to do? display
Vertices: 1 2 3
Edges:
(src=1, dest=2, weight=1)

What would you like to do? add edge 1 3


What would you like to do? add edge 3 1
What would you like to do? display
Vertices: 1 2 3
Edges:
(src=1, dest=2, weight=1)
(src=1, dest=3, weight=1)
(src=3, dest=1, weight=1)

What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest> [weight]
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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 4 5
What would you like to do? display
Vertices: 1 2 3 4 5
Edges:
(src=1, dest=2, weight=1)
(src=2, dest=3, weight=1)
(src=4, dest=5, weight=1)

What would you like to do? add edge 5 4


What would you like to do? display
Vertices: 1 2 3 4 5
Edges:
(src=1, dest=2, weight=1)
(src=2, dest=3, weight=1)
(src=4, dest=5, weight=1)
(src=5, dest=4, weight=1)

What would you like to do? quit

Python Program to Implement Breadth-First Search on a Graph


This is a Python program to implement Breadth-First Search on a graph.

Problem Description
The program creates a graph object and allows the user to perform BFS traversal on it.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function display_bfs that takes a Vertex object as argument.
3. The function begins by creating an empty set called visited and a Queue object, q.
4. It enqueues the passed Vertex object and also adds it to the set visited.
5. A while loop is created which runs as long as the queue is not empty.
6. In each iteration of the loop, the queue is dequeued, the dequeued element is displayed,
and all of its neighbours are enqueued which have not already been visited.
7. In addition to enqueuing, they are also added to the visited set.
8. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to implement BFS traversal on a graph. The
program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

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)

def display_bfs(vertex):
"""Display BFS Traversal starting at vertex."""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
print(current.get_key(), end=' ')
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('bfs <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'bfs':


key = int(do[1])
print('Breadth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_bfs(vertex)
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To perform BFS traversal starting at some vertex, display_bfs is called on that vertex.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
bfs <vertex key>
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 vertex 7
What would you like to do? add vertex 8
What would you like to do? add vertex 9
What would you like to do? add vertex 10
What would you like to do? add edge 1 2
What would you like to do? add edge 1 3
What would you like to do? add edge 1 5
What would you like to do? add edge 2 6
What would you like to do? add edge 3 7
What would you like to do? add edge 3 8
What would you like to do? add edge 4 8
What would you like to do? add edge 8 10
What would you like to do? add edge 5 10
What would you like to do? add edge 6 9
What would you like to do? add edge 9 10
What would you like to do? bfs 1
Breadth-first Traversal: 1 3 2 5 7 8 6 10 9
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
bfs <vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? bfs 1
Breadth-first Traversal: 1
What would you like to do? add vertex 2
What would you like to do? add edge 1 2
What would you like to do? bfs 1
Breadth-first Traversal: 1 2
What would you like to do? bfs 2
Breadth-first Traversal: 2
What would you like to do? add edge 2 1
What would you like to do? bfs 2
Breadth-first Traversal: 2 1
What would you like to do? add vertex 3
What would you like to do? add edge 2 3
What would you like to do? bfs 1
Breadth-first Traversal: 1 2 3
What would you like to do? quit

Python Program to Find All Nodes Reachable from a Node


using BFS in a Graph
This is a Python program to find all nodes reachable from a node using BFS in a graph.

Problem Description
The program creates a graph object and allows the user to find all nodes reachable from a
node.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function find_all_reachable_nodes that takes a Vertex object as argument.
3. The function begins by creating an empty set called visited and a Queue object, q.
4. It enqueues the passed Vertex object and also adds it to the set visited.
5. A while loop is created which runs as long as the queue is no empty.
6. In each iteration of the loop, the queue is dequeued and all of its neighbours are
enqueued which have not already been visited.
7. In addition to enqueuing, they are also added to the visited set.
8. After the loop is finished, the set visited is returned. The set contains all vertices that can
be reached from the source vertex.
9. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to find all nodes reachable from a node using
BFS in a graph. The program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

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)

def find_all_reachable_nodes(vertex):
"""Return set containing all vertices reachable from vertex."""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)
return visited

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('reachable <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')
elif operation == 'reachable':
key = int(do[1])
vertex = g.get_vertex(key)
reachable = find_all_reachable_nodes(vertex)
print('All nodes reachable from {}:'.format(key),
[v.get_key() for v in reachable])

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all nodes reachable from a vertex, find_all_reachable_nodes is called.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
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? reachable 1
All nodes reachable from 1: [1]
What would you like to do? add edge 1 2
What would you like to do? reachable 1
All nodes reachable from 1: [2, 1]
What would you like to do? reachable 2
All nodes reachable from 2: [2]
What would you like to do? add edge 2 1
What would you like to do? reachable 2
All nodes reachable from 2: [2, 1]
What would you like to do? add vertex 3
What would you like to do? add edge 2 3
What would you like to do? add vertex 4
What would you like to do? add edge 3 4
What would you like to do? reachable 1
All nodes reachable from 1: [2, 3, 1, 4]
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 5 4
What would you like to do? reachable 4
All nodes reachable from 4: [4]
What would you like to do? reachable 5
All nodes reachable from 5: [4, 5]
What would you like to do? reachable 1
All nodes reachable from 1: [2, 3, 1]
What would you like to do? reachable 2
All nodes reachable from 2: [2, 3]
What would you like to do? reachable 3
All nodes reachable from 3: [3]
What would you like to do? quit

Python Program to Find All Connected Components using BFS


in an Undirected Graph
This is a Python program to find all connected components using BFS in an undirected
graph.

Problem Description
The program creates a graph object and allows the user to find all connected components.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function label_all_reachable that takes a Vertex object, a dictionary called
component and a label as argument.
3. The function begins by creating an empty set called visited and a Queue object, q.
4. It enqueues the passed Vertex object and also adds it to the set visited.
5. A while loop is created which runs as long as the queue is no empty.
6. In each iteration of the loop, the queue is dequeued, label is assigned to
component[dequeued vertex] and all of its neighbours are enqueued which have not
already been visited.
7. In addition to enqueuing, they are also added to the visited set.
8. Thus, after the function is called, each vertex in the connected component containing the
source vertex is assigned the given label in the dictionary called component.

Program/Source Code
Here is the source code of a Python program to find all connected components using BFS
in an undirected graph. The program output is shown below.
class Graph:
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_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])

def add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

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)

def label_all_reachable(vertex, component, label):


"""Set component[v] = label for all v in the component containing vertex."""
visited = set()
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
component[current] = label
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
q.enqueue(dest)

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

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])
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:
if not g.does_undirected_edge_exist(src, dest):
g.add_undirected_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'components':


component = dict.fromkeys(g, None)
label = 1
for v in g:
if component[v] is None:
label_all_reachable(v, component, label)
label += 1

max_label = label
for label in range(1, max_label):
component_vertices = [v.get_key() for v in component
if component[v] == label]
print('Component {}:'.format(label), component_vertices)

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all connected components, a dictionary called component is created that contains
all Vertex objects in the graph as keys and all of which are mapped to None.
4. Then for each Vertex object v in the graph, if v is mapped to None, label_all_reachable is
called on that vertex with a given label. The value of the label is incremented for the next
iteration of the loop.
5. The vertices in each component is then displayed.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest>
components
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? components
Component 1: [1]
Component 2: [2]
Component 3: [3]
Component 4: [4]
Component 5: [5]
What would you like to do? add edge 1 2
What would you like to do? add edge 3 4
What would you like to do? components
Component 1: [2, 1]
Component 2: [4, 3]
Component 3: [5]
What would you like to do? add edge 5 1
What would you like to do? add edge 4 2
What would you like to do? components
Component 1: [5, 2, 4, 1, 3]
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest>
components
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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add vertex 4
Vertex already exists.
What would you like to do? components
Component 1: [2, 3, 1]
Component 2: [4]
What would you like to do? quit

Python Program to Find Shortest Path From a Vertex using


BFS in an Unweighted Graph
This is a Python program to find shortest path from a vertex to all vertices using BFS in an
unweighted graph.

Problem Description
The program creates a graph object and allows the user to find the shortest path from a
vertex to all nodes.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function find_shortest_paths that takes a Vertex object called src as argument.
3. The function begins by creating an empty set called visited and a Queue object, q.
4. It also creates a dictionary parent which maps each vertex to its parent in the BFS tree.
src is mapped to None.
5. It also creates a dictionary distance that maps each vertex to the shortest distance
between src and that vertex. src is mapped to 0.
6. It enqueues the passed Vertex object and also adds it to the set visited.
7. A while loop is created which runs as long as the queue is no empty.
8. In each iteration of the loop, the queue is dequeued and all of its neighbours are
enqueued which have not already been visited.
9. In addition to enqueuing, they are also added to the set visited, parent of each of the
neighbours is set to the dequeued node, and distance of each neighbour is set to one plus
the distance of the dequeued node.
10. After the loop is finished, the dictionaries parent and distance are returned as a tuple.
11. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to find the shortest path from a source node to
all nodes using BFS in an unweighted graph. The program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
# dictionary containing destination vertices mapped to the weight of the
# edge with which they are joined to this vertex
self.points_to = {}

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

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)

def find_shortest_paths(src):
"""Returns tuple of two dictionaries: (parent, distance)

parent contains vertices mapped to their parent vertex in the shortest


path from src to that vertex.
distance contains vertices mapped to their shortest distance from src.
"""
parent = {src: None}
distance = {src: 0}

visited = set()
q = Queue()
q.enqueue(src)
visited.add(src)
while not q.is_empty():
current = q.dequeue()
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
parent[dest] = current
distance[dest] = distance[current] + 1
q.enqueue(dest)
return (parent, distance)
g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('shortest <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'shortest':


key = int(do[1])
src = g.get_vertex(key)
parent, distance = find_shortest_paths(src)

print('Path from destination vertices to source vertex {}:'.format(key))


for v in parent:
print('Vertex {} (distance {}): '.format(v.get_key(), distance[v]),
end='')
while parent[v] is not None:
print(v.get_key(), end = ' ')
v = parent[v]
print(src.get_key()) # print source vertex

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find the shortest paths from a source vertex, find_shortest_paths is called.
4. The dictionary parent is used to print the path while the dictionary distance is used to
print the distance from a particular vertex to the source vertex.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
shortest <vertex key>
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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? shortest 1
Path from destination vertices to source vertex 1:
Vertex 1 (distance 0): 1
Vertex 3 (distance 2): 3 2 1
Vertex 2 (distance 1): 2 1
What would you like to do? add edge 1 3
What would you like to do? shortest 1
Path from destination vertices to source vertex 1:
Vertex 1 (distance 0): 1
Vertex 3 (distance 1): 3 1
Vertex 2 (distance 1): 2 1
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
shortest <vertex key>
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? shortest 1
Path from destination vertices to source vertex 1:
Vertex 1 (distance 0): 1
What would you like to do? add edge 1 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 2 3
What would you like to do? add edge 2 4
What would you like to do? add edge 4 5
What would you like to do? add edge 4 6
What would you like to do? shortest 1
Path from destination vertices to source vertex 1:
Vertex 5 (distance 3): 5 4 2 1
Vertex 6 (distance 3): 6 4 2 1
Vertex 3 (distance 2): 3 2 1
Vertex 2 (distance 1): 2 1
Vertex 1 (distance 0): 1
Vertex 4 (distance 2): 4 2 1
What would you like to do? add edge 2 6
What would you like to do? add edge 1 5
What would you like to do? shortest 1
Path from destination vertices to source vertex 1:
Vertex 5 (distance 1): 5 1
Vertex 6 (distance 2): 6 2 1
Vertex 3 (distance 2): 3 2 1
Vertex 2 (distance 1): 2 1
Vertex 1 (distance 0): 1
Vertex 4 (distance 2): 4 2 1
What would you like to do? quit

Python Program to Find if Undirected Graph contains Cycle


using BFS
This is a Python program to find if an undirected graph contains a cycle using BFS.

Problem Description
The program creates a graph object and allows the user to determine whether the graph
contains a cycle.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function is_cycle_present that takes a Vertex object v and a set visited as
arguments.
3. The function begins by creating an empty set called visited and a Queue object q.
4. It also creates a dictionary parent which maps each vertex to its parent in the BFS tree. v
is mapped to None.
5. It enqueues v and also adds it to the set visited.
6. A while loop is created which runs as long as the queue is not empty.
7. In each iteration of the loop, the queue is dequeued and all of its neighbours are
enqueued which have not already been visited.
8. In addition to enqueuing, they are also added to the set visited and the parent of each
neighbour is set to the dequeued node.
9. If a neighbour is found to be already visited, it is checked if the parent of the dequeued
element is that neighbour. If it is not, the graph contains a cycle and True is returned.
10. After the loop is finished, False is returned to indicate no cycle is present.
11. Thus, the function returns True if there is a cycle in the connected component
containing v. It also puts all nodes reachable from the source vertex in the set visited.

Program/Source Code
Here is the source code of a Python program to find if an undirected graph contains a cycle
using BFS. The program output is shown below.
class Graph:
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 add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

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)

def is_cycle_present(vertex, visited):


"""Return True if cycle is present in component containing vertex and put
all vertices in component in set visited."""
parent = {vertex: None}
q = Queue()
q.enqueue(vertex)
visited.add(vertex)
while not q.is_empty():
current = q.dequeue()
for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
parent[dest] = current
q.enqueue(dest)
else:
if parent[current] is not dest:
return True
return False

g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <vertex1> <vertex2>')
print('cycle')
print('display')
print('quit')

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':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_undirected_edge_exist(v1, v2):
g.add_undirected_edge(v1, v2)
else:
print('Edge already exists.')

elif operation == 'cycle':


present = False
visited = set()
for v in g:
if v not in visited:
if is_cycle_present(v, visited):
present = True
break
if present:
print('Cycle present.')
else:
print('Cycle not present.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To determine whether the graph contains a cycle, is_cycle_present is called with a vertex
from the graph and an empty set visited.
4. If is_cycle_present returns True, a cycle is present. Otherwise, if not all vertices were
visited, is_cycle_present is called again with an unvisited source vertex.
5. This continues until all vertices have been visited or is_cycle_present returns True.
6. If all vertices have been visited, then there are no cycles in the graph.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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 edge 1 2
What would you like to do? cycle
Cycle not present.
What would you like to do? add vertex 3
What would you like to do? add edge 2 3
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 3 1
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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
What would you like to do? add edge 1 3
What would you like to do? add edge 2 4
What would you like to do? add edge 2 5
What would you like to do? add edge 6 5
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 6 2
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Python Program to Find if Undirected Graph is Bipartite using


BFS
This is a Python program to find if an undirected graph is bipartite using BFS.

Problem Description
The program creates a graph object and allows the user to determine whether the graph is
bipartite.

Problem Solution
1. Create classes for Graph, Vertex and Queue.
2. Create a function is_bipartite that takes a Vertex object v and a set visited as arguments.
3. The function works by painting each vertex a colour opposite to the colour of its
neighbours. If it is found not possible to do so, the graph is not bipartite.
4. The function begins by creating an empty set called visited and a Queue object, q.
5. It also creates a dictionary colour which maps each vertex to either 1 or 0 which
represent two different colours. The Vertex object passed is mapped to 0.
6. It enqueues the passed Vertex object and also adds it to the set visited.
7. A while loop is created which runs as long as the queue is not empty.
8. In each iteration of the loop, the queue is dequeued and all of its neighbours are
enqueued which have not already been visited.
9. In addition to enqueuing, they are also added to the set visited and the colour of each
neighbour is set to the colour opposite to the colour of the dequeued element.
10. If a neighbour is found to be already visited and its colour is the same as that of the
dequeued element, the graph is not bipartite and False is returned.
11. After the loop is finished, True is returned to indicate that the graph is bipartite.
12. Thus, the function returns True if the connected component containing v is bipartite. It
also puts all nodes reachable from the source vertex in the set visited.

Program/Source Code
Here is the source code of a Python program to find if an undirected graph is bipartite using
BFS. The program output is shown below.
class Graph:
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 add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))
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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

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)

def is_bipartite(vertex, visited):


"""Return True if component containing vertex is bipartite and put all
vertices in its component in set visited."""
colour = {vertex: 0}
visited.add(vertex)
q = Queue()
q.enqueue(vertex)
while not q.is_empty():
current = q.dequeue()

next_colour = 1 - colour[current] # switch colour


for dest in current.get_neighbours():
if dest not in visited:
visited.add(dest)
colour[dest] = next_colour
q.enqueue(dest)
else:
if colour[dest] != next_colour:
return False
return True

g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <vertex1> <vertex2>')
print('bipartite')
print('display')
print('quit')

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':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_undirected_edge_exist(v1, v2):
g.add_undirected_edge(v1, v2)
else:
print('Edge already exists.')

elif operation == 'bipartite':


bipartite = True
visited = set()
for v in g:
if v not in visited:
if not is_bipartite(v, visited):
bipartite = False
break

if bipartite:
print('Graph is bipartite.')
else:
print('Graph is not bipartite.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To determine whether the graph is bipartite, is_bipartite is called with a vertex from the
graph and an empty set visited.
4. If is_bipartite returns True, the graph is not bipartite. Otherwise, if not all vertices were
visited, is_bipartite is called again with an unvisited source vertex.
5. This continues until all vertices have been visited or is_bipartite returns False.
6. If all vertices have been visited, the graph is bipartite.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
bipartite
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 vertex 7
What would you like to do? add edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? add edge 5 6
What would you like to do? add edge 6 7
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 7 1
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 6 1
What would you like to do? bipartite
Graph is not bipartite.
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
bipartite
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? bipartite
Graph is bipartite.
What would you like to do? add edge 1 2
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 3 4
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 1 4
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 2 4
What would you like to do? bipartite
Graph is not bipartite.
What would you like to do? quit

2. Python Programming examples on “Connected Components using DFS”

Python Program to Implement Depth-First Search on a Graph


using Recursion
This is a Python program to implement Depth-First Search on a graph using recursion.
Problem Description
The program creates a graph object and allows the user to perform DFS traversal on it.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function display_dfs_helper that takes a Vertex object v and a set visited as
arguments.
3. The function begins by adding v to visited and displaying v.
4. For each neighbour of v that is not in visited, display_dfs_helper is called on the
neighbour.
5. Create a function display_dfs that takes a Vertex object v as argument.
6. It calls display_dfs_helper with v and an empty set for the set visited.
7. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to implement DFS traversal on a graph using
recursion. The program output is shown below.
class Graph:
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_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])

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

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 display_dfs(v):
"""Display DFS traversal starting at vertex v."""
display_dfs_helper(v, set())

def display_dfs_helper(v, visited):


"""Display DFS traversal starting at vertex v. Uses set visited to keep
track of already visited nodes."""
visited.add(v)
print(v.get_key(), end=' ')
for dest in v.get_neighbours():
if dest not in visited:
display_dfs_helper(dest, visited)

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('dfs <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'dfs':


key = int(do[1])
print('Depth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_dfs(vertex)
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To perform DFS traversal starting at some vertex, display_dfs is called.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
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 vertex 7
What would you like to do? add edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? add edge 3 5
What would you like to do? add edge 1 6
What would you like to do? add edge 6 2
What would you like to do? dfs 1
Depth-first Traversal: 1 6 2 3 4 5
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? dfs 1
Depth-first Traversal: 1
What would you like to do? add vertex 2
What would you like to do? add edge 1 2
What would you like to do? dfs 1
Depth-first Traversal: 1 2
What would you like to do? dfs 2
Depth-first Traversal: 2
What would you like to do? add edge 2 1
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 edge 2 3
What would you like to do? add edge 2 4
What would you like to do? dfs 1
Depth-first Traversal: 1 2 3 4
What would you like to do? dfs 2
Depth-first Traversal: 2 3 4 1
What would you like to do? quit

Python Program to Implement Depth-First Search on a Graph


without Recursion
This is a Python program to implement Depth-First Search on a graph without using
recursion.
Problem Description
The program creates a graph object and allows the user to perform DFS traversal on it.

Problem Solution
1. Create classes for Graph, Vertex and Stack.
2. Create a function display_dfs that takes a Vertex object v as argument.
3. The function begins by creating an empty set called visited and a Stack object, s.
4. It pushes the passed Vertex object on the stack.
5. A while loop is created which runs as long as the stack is not empty.
6. In each iteration of the loop, a node is popped from the stack.
7. If the popped node has already been visited, skip to the next iteration of the loop.
8. Otherwise, the popped element is displayed and added to the set visited.
9. All of the neighbours of the popped element which have not already been visited are
pushed on the stack.
10. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to implement DFS traversal on a graph
without using recursion. The program output is shown below.
class Graph:
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_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])
def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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

class Stack:
def __init__(self):
self.items = []

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

def push(self, data):


self.items.append(data)

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

def display_dfs(v):
visited = set()
s = Stack()
s.push(vertex)
while not s.is_empty():
current = s.pop()
if current in visited:
continue
print(current.get_key(), end=' ')
visited.add(current)
for dest in current.get_neighbours():
if dest not in visited:
s.push(dest)

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('dfs <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'dfs':


key = int(do[1])
print('Depth-first Traversal: ', end='')
vertex = g.get_vertex(key)
display_dfs(vertex)
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To perform DFS traversal starting at some vertex, display_dfs is called on that vertex.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
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 vertex 7
What would you like to do? add edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? add edge 1 5
What would you like to do? add edge 1 6
What would you like to do? add edge 5 6
What would you like to do? add edge 3 7
What would you like to do? dfs 1
Depth-first Traversal: 1 5 6 2 3 7 4
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
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? dfs 1
Depth-first Traversal: 1
What would you like to do? add edge 1 2
What would you like to do? add edge 2 3
What would you like to do? dfs 1
Depth-first Traversal: 1 2 3
What would you like to do? add vertex 4
What would you like to do? add edge 3 4
What would you like to do? dfs 1
Depth-first Traversal: 1 2 3 4
What would you like to do? quit

Python Program to Print DFS Numbering of a Graph


This is a Python program to print DFS numbering of a graph.

Problem Description
The program creates a graph object and allows the user to perform DFS traversal on it and print its
DFS numbering.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function dfs_helper that takes a Vertex object v, a set visited, two dictionaries pre and
post and a one-element list time as arguments.
3. time is used to keep track of the current time. It is passed as a one-element list so that it can be
passed by reference.
4. The function begins by adding v to visited, incrementing time and setting pre[v] to the current
value of time.
5. This is the discovered time.
6. For each neighbour of v that is not in visited, dfs_helper is called.
7. After the loop finishes, time is again incremented.
8. post[v] is set the current value of time.
9. This is the finished time.
10. Create a function dfs that takes a Vertex object v, and two dictionaries pre and post as
arguments.
11. It calls dfs_helper with arguments v, an empty set for the set visited, the dictionaries pre and
post, and a one-element list containing 0 for time.
12. Thus, the function dfs finds the DFS numbering starting at vertex v and stores the discovered
and finished times in the dictionaries pre and post respectively.
13. This algorithm also works for undirected graphs. In an undirected graph, whenever edge (u, v) is
added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to print DFS numbering of a graph. The program
output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 dfs(v, pre, post):


"""Display DFS traversal starting at vertex v. Stores pre and post times in
dictionaries pre and post."""
dfs_helper(v, set(), pre, post, [0])

def dfs_helper(v, visited, pre, post, time):


"""Display DFS traversal starting at vertex v. Uses set visited to keep
track of already visited nodes, dictionaries pre and post to store
discovered and finished times and the one-element list time to keep track of
current time."""
visited.add(v)
time[0] = time[0] + 1
pre[v] = time[0]
print('Visiting {}... discovered time = {}'.format(v.get_key(), time[0]))
for dest in v.get_neighbours():
if dest not in visited:
dfs_helper(dest, visited, pre, post, time)
time[0] = time[0] + 1
post[v] = time[0]
print('Leaving {}... finished time = {}'.format(v.get_key(), time[0]))

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('dfs <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'dfs':


key = int(do[1])
print('Depth-first Traversal: ')
vertex = g.get_vertex(key)
pre = dict()
post = dict()
dfs(vertex, pre, post)
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To print DFS numbering starting at some vertex, dfs is called on the vertex and two empty
dictionaries pre and post to store the discovered and finished times.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? add edge 1 5
What would you like to do? add vertex 6
What would you like to do? add edge 1 6
What would you like to do? add edge 5 6
What would you like to do? dfs 1
Depth-first Traversal:
Visiting 1... discovered time = 1
Visiting 2... discovered time = 2
Visiting 3... discovered time = 3
Visiting 4... discovered time = 4
Leaving 4... finished time = 5
Leaving 3... finished time = 6
Leaving 2... finished time = 7
Visiting 5... discovered time = 8
Visiting 6... discovered time = 9
Leaving 6... finished time = 10
Leaving 5... finished time = 11
Leaving 1... finished time = 12

What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
dfs <vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? dfs 1
Depth-first Traversal:
Visiting 1... discovered time = 1
Leaving 1... finished time = 2

What would you like to do? add vertex 2


What would you like to do? add edge 1 2
What would you like to do? dfs 1
Depth-first Traversal:
Visiting 1... discovered time = 1
Visiting 2... discovered time = 2
Leaving 2... finished time = 3
Leaving 1... finished time = 4

What would you like to do? quit

Python Program to Find All Nodes Reachable from a Node


using DFS in a Graph
This is a Python program to find all nodes reachable from a node using DFS in a graph.

Problem Description
The program creates a graph object and allows the user to find all nodes reachable from a
node.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function find_all_reachable_nodes_helper that takes a Vertex object v and a set
visited as arguments.
3. The function begins by adding v to visited.
4. For each neighbour of v that is not in visited, find_all_reachable_nodes_helper is called.
5. Create a function find_all_reachable_nodes that takes a Vertex object v as argument.
6. It creates an empty set reachable.
7. It calls find_all_reachable_nodes_helper with v and the set reachable for the visited
parameter.
8. The set reachable is returned.
9. Thus this function returns a set containing all nodes that can be reached from v.
10. This algorithm also works for undirected graphs. In an undirected graph, whenever edge
(u, v) is added to the graph, the reverse edge (v, u) is also added.

Program/Source Code
Here is the source code of a Python program to find all nodes reachable from a node using
DFS in a graph. The program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 find_all_reachable_nodes(v):
"""Return set containing all vertices reachable from vertex."""
reachable = set()
find_all_reachable_nodes_helper(v, reachable)
return reachable

def find_all_reachable_nodes_helper(v, visited):


"""Add all vertices visited by DFS traversal starting at v to the set visited."""
visited.add(v)
for dest in v.get_neighbours():
if dest not in visited:
find_all_reachable_nodes_helper(dest, visited)

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('reachable <vertex key>')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'reachable':


key = int(do[1])
vertex = g.get_vertex(key)
reachable = find_all_reachable_nodes(vertex)
print('All nodes reachable from {}:'.format(key),
[v.get_key() for v in reachable])

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all nodes reachable from a vertex, find_all_reachable_nodes is called.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
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 vertex 7
What would you like to do? add edge 1 2
What would you like to do? add edge 1 3
What would you like to do? add edge 4 5
What would you like to do? add edge 5 6
What would you like to do? reachable 1
All nodes reachable from 1: [2, 3, 1]
What would you like to do? reachable 4
All nodes reachable from 4: [6, 4, 5]
What would you like to do? reachable 7
All nodes reachable from 7: [7]
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
reachable <vertex key>
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? reachable 1
All nodes reachable from 1: [1]
What would you like to do? add edge 1 2
What would you like to do? reachable 1
All nodes reachable from 1: [2, 1]
What would you like to do? reachable 2
All nodes reachable from 2: [2]
What would you like to do? add edge 2 1
What would you like to do? reachable 2
All nodes reachable from 2: [2, 1]
What would you like to do? quit

Python Program to Find All Connected Components using DFS


in an Undirected Graph
This is a Python program to find all connected components using DFS in an undirected
graph.

Problem Description
The program creates a graph object and allows the user to find all connected components.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function label_all_reachable_helper that takes a Vertex object v, a set visited, a
dictionary component and a label as arguments.
3. The function begins by adding v to visited and setting component[v] to label.
4. For each neighbour of v that is not in visited, label_all_reachable_helper is called.
5. Create a function label_all_reachable that takes a Vertex object, a dictionary component
and a label as arguments.
6. It calls label_all_reachable_helper with v, an empty set for the set visited, component and
label as arugments.
7. Thus, after the function is called, for each vertex in the component containing the source
vertex, component[vertex] is set to label.

Program/Source Code
Here is the source code of a Python program to find all connected components using DFS
in an undirected graph. The program output is shown below.
class Graph:
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_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])

def add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 label_all_reachable(vertex, component, label):


"""Set component[v] = label for all v in the component containing vertex."""
label_all_reachable_helper(vertex, set(), component, label)

def label_all_reachable_helper(vertex, visited, component, label):


"""Set component[v] = label for all v in the component containing
vertex. Uses set visited to keep track of nodes alread visited."""
visited.add(vertex)
component[vertex] = label
for dest in vertex.get_neighbours():
if dest not in visited:
label_all_reachable_helper(dest, visited, component, label)

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

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])
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:
if not g.does_undirected_edge_exist(src, dest):
g.add_undirected_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'components':


component = dict.fromkeys(g, None)
label = 1
for v in g:
if component[v] is None:
label_all_reachable(v, component, label)
label += 1

max_label = label
for label in range(1, max_label):
print('Component {}:'.format(label),
[v.get_key() for v in component if component[v] == label])

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all connected components, a dictionary called component is created that contains
all Vertex objects in the graph as keys and all of which are mapped to None.
4. Then for each Vertex object v in the graph, if v is mapped to None, label_all_reachable is
called on that vertex with a given label. The value of the label is incremented for the next
iteration of the loop.
5. The vertices in each component is then displayed.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest>
components
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? components
Component 1: [1]
Component 2: [2]
Component 3: [3]
Component 4: [4]
Component 5: [5]
What would you like to do? add edge 1 2
What would you like to do? components
Component 1: [2, 1]
Component 2: [3]
Component 3: [4]
Component 4: [5]
What would you like to do? add edge 3 4
What would you like to do? components
Component 1: [2, 1]
Component 2: [4, 3]
Component 3: [5]
What would you like to do? add edge 1 5
What would you like to do? components
Component 1: [2, 5, 1]
Component 2: [4, 3]
What would you like to do? add edge 2 4
What would you like to do? components
Component 1: [4, 2, 5, 1, 3]
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest>
components
display
quit
What would you like to do? components
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? components
Component 1: [1]
Component 2: [2]
What would you like to do? add edge 1 2
What would you like to do? components
Component 1: [1, 2]
What would you like to do? add vertex 3
What would you like to do? components
Component 1: [1, 2]
Component 2: [3]
What would you like to do? quit

Python Program to Find if Undirected Graph is Bipartite using


DFS
This is a Python program to find if an undirected graph is bipartite using DFS.

Problem Description
The program creates a graph object and allows the user to determine whether the graph is
bipartite.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function is_bipartite_helper that takes a Vertex object v, a set visited and a
dictionary colour as arguments.
3. The function works by painting each vertex a colour opposite to the colour of its
neighbours. If it is found not possible to do so, the graph is not bipartite.
4. The function begins by adding v to visited.
5. For each neighbour of v that has not been visited, its colour is set to the colour opposite
of v’s colour and is_bipartite_helper on the neighbour is called to see whether it returns
False. If so, the graph is not bipartite and False is returned.
6. If a neghbour has already been visited, then it is checked to see whether the colour of the
neighbour is opposite to the colour of v. If not, False is returned.
7. After the loop is finished, True is returned to indicate that the graph is bipartite.
8. Create a function is_bipartite that takes a Vertex object v and an empty set visited as
arguments.
9. It creates a dictionary colour with v mapped to 0. The values 0 and 1 are used to
represent the two different colours.
10. It calls is_bipartite_helper with v, the set visited and the dictionary colour. Its returned
value is the return value of this function.
11. Thus, this function returns True if the connected component containing v is bipartite and
puts all vertices reachable from v in the set visited.

Program/Source Code
Here is the source code of a Python program to find if an undirected graph is bipartite using
DFS. The program output is shown below.
class Graph:
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 add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))

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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 is_bipartite(vertex, visited):


"""Return True if component containing vertex is bipartite and put all
vertices in its component in set visited."""
colour = {vertex: 0}
return is_bipartite_helper(vertex, visited, colour)

def is_bipartite_helper(v, visited, colour):


"""Return True if component containing vertex is bipartite and put all
vertices in its component in set visited. Uses dictionary colour to keep
track of colour of each vertex."""
visited.add(v)
next_colour = 1 - colour[v] # switch colour
for dest in v.get_neighbours():
if dest not in visited:
colour[dest] = next_colour
if not is_bipartite_helper(dest, visited, colour):
return False
else:
if colour[dest] != next_colour:
return False
return True
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <vertex1> <vertex2>')
print('bipartite')
print('display')
print('quit')

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':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_undirected_edge_exist(v1, v2):
g.add_undirected_edge(v1, v2)
else:
print('Edge already exists.')

elif operation == 'bipartite':


bipartite = True
visited = set()
for v in g:
if v not in visited:
if not is_bipartite(v, visited):
bipartite = False
break

if bipartite:
print('Graph is bipartite.')
else:
print('Graph is not bipartite.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To determine whether the graph is bipartite, is_bipartite is called with a vertex from the
graph and an empty set visited.
4. If is_bipartite returns True, the graph is not bipartite. Otherwise, if not all vertices were
visited, is_bipartite is called again with an unvisited source vertex.
5. This continues until all vertices have been visited or is_bipartite returns False.
6. If all vertices have been visited, the graph is bipartite.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
bipartite
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 edge 1 2
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 3 2
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 1 4
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 2 4
What would you like to do? bipartite
Graph is not bipartite.
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
bipartite
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
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 5 1
What would you like to do? add edge 6 4
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 6 5
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 6 2
What would you like to do? bipartite
Graph is bipartite.
What would you like to do? add edge 6 1
What would you like to do? bipartite
Graph is not bipartite.
What would you like to do? quit

Python Program to Find if Undirected Graph contains Cycle


using DFS
This is a Python program to find if an undirected graph contains a cycle using DFS.

Problem Description
The program creates a graph object and allows the user to determine whether the graph
contains a cycle.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function is_cycle_present_helper that takes a Vertex object v, a set visited and
a dictionary parent as arguments.
3. The function works by performing DFS traversal on the graph. If it finds a node that has
already been visited, it checks whether the found node is a child of the current node. If not,
the graph contains a cycle. The last check is needed because the graph is undirected which
means there are two edges between any two adjacent vertices which we do not want to
consider as a cycle.
4. The dictionary parent keeps track of the parent of each node in the DFS tree.
5. The function begins by adding v to visited.
6. For each neighbour of v that is not in visited, is_cycle_present_helper is called and its
parent is set to v.
7. If is_cycle_present_helper returns True, a cycle is present and True is returned.
8. If a neighbour has already been visited and the parent of v is not that neighbour, a cycle
is present and True is returned.
9. After the loop finishes, False is returned to indicate that no cycle is present.
10. Create a function is_cycle_present that takes a Vertex object and a set visited as
arguments.
11. It calls is_cycle_present_helper with v, the set visited and a dictionary that maps v to
None as the parent parameter. The return value of is_cycle_present_helper is returned.
12. Thus, this function returns True is a cycle is present in the connected component
containing v and puts all nodes in the component in set visited.

Program/Source Code
Here is the source code of a Python program to find if an undirected graph contains a cycle
using DFS. The program output is shown below.
class Graph:
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 add_undirected_edge(self, v1_key, v2_key, weight=1):


"""Add undirected edge (2 directed edges) between v1_key and v2_key with
given weight."""
self.add_edge(v1_key, v2_key, weight)
self.add_edge(v2_key, v1_key, weight)

def does_undirected_edge_exist(self, v1_key, v2_key):


"""Return True if there is an undirected edge between v1_key and v2_key."""
return (self.does_edge_exist(v1_key, v2_key)
and self.does_edge_exist(v1_key, v2_key))

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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 is_cycle_present(v, visited):


"""Return True if cycle is present in component containing vertex and put
all vertices in component in set visited."""
parent = {v: None}
return is_cycle_present_helper(v, visited, parent)

def is_cycle_present_helper(v, visited, parent):


"""Return True if cycle is present in component containing vertex and put
all vertices in component in set visited. Uses dictionary parent to keep
track of parents of nodes in the DFS tree."""
visited.add(v)
for dest in v.get_neighbours():
if dest not in visited:
parent[dest] = v
if is_cycle_present_helper(dest, visited, parent):
return True
else:
if parent[v] is not dest:
return True
return False

g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <vertex1> <vertex2>')
print('cycle')
print('display')
print('quit')

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':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_undirected_edge_exist(v1, v2):
g.add_undirected_edge(v1, v2)
else:
print('Edge already exists.')

elif operation == 'cycle':


present = False
visited = set()
for v in g:
if v not in visited:
if is_cycle_present(v, visited):
present = True
break

if present:
print('Cycle present.')
else:
print('Cycle not present.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To determine whether the graph contains a cycle, is_cycle_present is called with a vertex
from the graph and an empty set visited.
4. If is_cycle_present returns True, a cycle is present. Otherwise, if not all vertices were
visited, is_cycle_present is called again with an unvisited source vertex.
5. This continues until all vertices have been visited or is_cycle_present returns True.
6. If all vertices have been visited, then there are no cycles in the graph.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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 edge 1 2
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 2 3
What would you like to do? add edge 3 4
What would you like to do? add vertex 5
What would you like to do? add edge 4 5
What would you like to do? add edge 5 3
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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? cycle
Cycle not present.
What would you like to do? add edge 1 2
What would you like to do? add vertex 3
What would you like to do? add edge 2 3
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 3 1
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Python Program to Find if Directed Graph contains Cycle using


DFS
This is a Python program to find if a directed graph contains a cycle using DFS.

Problem Description
The program allows the user to determine whether a directed graph contains a cycle.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function is_cycle_present_helper that takes a Vertex object v, a set visited and
a set on_stack as arguments.
3. The function works by keeping track of the nodes that are on the stack. That is those
nodes whose children are still being traversed. If while performing traversal a node already
on the stack is found, then the graph contains a cycle.
4. The set on_stack keeps track of the nodes that are on the stack of the DFS traversal.
5. The functions begins by testing if v is in on_stack and if so, a cycle is present and it
returns True.
6. Otherwise, it adds v to on_stack.
7. For each neighbour of v that is not in visited, is_cycle_present_helper is called. If
is_cycle_present_helper returns True, a cycle is present and True is returned.
8. After the loop finishes, v is removed from on_stack and added to visited.
9. False is returned to indicate that no cycle is present.
10. Create a function is_cycle_present that takes a Graph object as argument.
11. It creates two empty sets, visited and on_stack.
12. For each vertex v in the graph, if v is not in visited, is_cycle_present_helper is called on
v.
13. If is_cycle_present_helper returns True, a cycle is present in the graph and True is
returned.
14. If the loop finishes, then no cycle is present and False is returned.
15. Thus, this function returns True if a cycle is present in the graph.

Program/Source Code
Here is the source code of a Python program to find if a directed graph contains a cycle
using DFS. The program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 is_cycle_present(graph):
"""Return True if cycle is present in the graph."""
on_stack = set()
visited = set()
for v in graph:
if v not in visited:
if is_cycle_present_helper(v, visited, on_stack):
return True
return False

def is_cycle_present_helper(v, visited, on_stack):


"""Return True if the DFS traversal starting at vertex v detects a
cycle. Uses set visited to keep track of nodes that have been visited. Uses
set on_stack to keep track of nodes that are 'on the stack' of the recursive
calls."""
if v in on_stack:
return True
on_stack.add(v)
for dest in v.get_neighbours():
if dest not in visited:
if is_cycle_present_helper(dest, visited, on_stack):
return True
on_stack.remove(v)
visited.add(v)
return False

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <vertex1> <vertex2>')
print('cycle')
print('display')
print('quit')

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':
v1 = int(do[2])
v2 = int(do[3])
if v1 not in g:
print('Vertex {} does not exist.'.format(v1))
elif v2 not in g:
print('Vertex {} does not exist.'.format(v2))
else:
if not g.does_edge_exist(v1, v2):
g.add_edge(v1, v2)
else:
print('Edge already exists.')

elif operation == 'cycle':


if is_cycle_present(g):
print('Cycle present.')
else:
print('Cycle not present.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To determine whether the graph contains a cycle, is_cycle_present is called on the
graph.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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? cycle
Cycle not present.
What would you like to do? add edge 1 2
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 2 3
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 1 3
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 4 5
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 3 4
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 4 1
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <vertex1> <vertex2>
cycle
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 edge 1 2
What would you like to do? add edge 3 2
What would you like to do? cycle
Cycle not present.
What would you like to do? add edge 2 3
What would you like to do? cycle
Cycle present.
What would you like to do? quit

Python Program to Print a Topological Sorting of a Directed


Acyclic Graph using DFS
This is a Python program to print a topological sorting of a DAG using DFS.

Problem Description
The program allows the user to print a topological sorting of a directed acyclic graph (DAG).

Problem Solution
1. The algorithm works by performing a DFS traversal of the entire graph. This means
performing DFS traversal starting at some node in the graph and after the traversal,
performing DFS on one of the unvisited nodes if some are still left. This is done until there
are no unvisited nodes. Then the finished times corresponding to each node sorted in
descending order gives a topological ordering of the DAG.
2. Create classes for Graph and Vertex.
3. Create a function get_topological_sorting_helper that takes a Vertex object v, a set
visited, a set on_stack and a list tlist as arguments.
4. It stores a topological sorting in tlist and returns False iff the graph is found to be not a
DAG.
5. The set on_stack keeps track of the nodes that are on the stack of the DFS traversal.
6. The functions begins by testing if v is in on_stack and if so, a cycle is present and and
False is returned.
7. Otherwise, it adds v to on_stack.
8. For each neighbour of v that is not in visited, get_topological_sorting_helper is called.
9. If the above call returns False, the graph is not a DAG and False is returned.
10. After the loop finishes, v is removed from on_stack and added to visited.
11. The key of v is prepended to tlist.
12. True is returned to indicate that no cycles were found.
13. Create a function get_topological_sorting that takes a graph object as argument.
14. The function returns a topological sorting in a list and returns None if the graph is not a
DAG.
15. The function begins by creating an empty list called tlist to store the topological sorting.
16. For each vertex in the graph that has not been visited, it calls
get_topological_sorting_helper with tlist.
17. If a call to the helper function returns False, None is returned.
18. If the loop finishes, tlist is returned.

Program/Source Code
Here is the source code of a Python program to print a topological sorting of a DAG. The
program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 get_topological_sorting(graph):
"""Return a topological sorting of the DAG. Return None if graph is not a DAG."""
tlist = []
visited = set()
on_stack = set()
for v in graph:
if v not in visited:
if not get_topological_sorting_helper(v, visited, on_stack, tlist):
return None
return tlist

def get_topological_sorting_helper(v, visited, on_stack, tlist):


"""Perform DFS traversal starting at vertex v and store a topological
sorting of the DAG in tlist. Return False if it is found that the graph is
not a DAG. Uses set visited to keep track of already visited nodes."""
if v in on_stack:
# graph has cycles and is therefore not a DAG.
return False

on_stack.add(v)
for dest in v.get_neighbours():
if dest not in visited:
if not get_topological_sorting_helper(dest, visited, on_stack, tlist):
return False
on_stack.remove(v)
visited.add(v)
tlist.insert(0, v.get_key()) # prepend node key to tlist
return True

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest>')
print('topological')
print('display')
print('quit')

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])
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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest)
else:
print('Edge already exists.')

elif operation == 'topological':


tlist = get_topological_sorting(g)
if tlist is not None:
print('Topological Sorting: ', end='')
print(tlist)
else:
print('Graph is not a DAG.')

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To print a topological sorting of the graph, get_topological_sorting is called.
4. If it returns None instead of a list, the graph is not a DAG.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest>
topological
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? topological
Topological Sorting: [3, 2, 1]
What would you like to do? add edge 1 2
What would you like to do? topological
Topological Sorting: [3, 1, 2]
What would you like to do? add edge 2 3
What would you like to do? topological
Topological Sorting: [1, 2, 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 vertex 7
What would you like to do? add edge 4 5
What would you like to do? topological
Topological Sorting: [7, 6, 4, 5, 1, 2, 3]
What would you like to do? add edge 4 6
What would you like to do? topological
Topological Sorting: [7, 4, 5, 6, 1, 2, 3]
What would you like to do? add edge 5 7
What would you like to do? topological
Topological Sorting: [4, 5, 7, 6, 1, 2, 3]
What would you like to do? add edge 3 4
What would you like to do? topological
Topological Sorting: [1, 2, 3, 4, 5, 7, 6]
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest>
topological
display
quit
What would you like to do? add vertex 1
What would you like to do? topological
Topological Sorting: [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 edge 1 2
What would you like to do? add edge 2 3
What would you like to do? topological
Topological Sorting: [1, 2, 3]
What would you like to do? add edge 3 2
What would you like to do? topological
Graph is not a DAG.
What would you like to do? quit
3. Python Programming examples on “Shortest Path”

3. Python Programming examples on “Shortest Path”

Python Program to Implement Dijkstra’s Shortest Path


Algorithm
This is a Python program to implement Dijkstra’s Shortest Path algorithm on a graph.

Problem Description
The problem is to find the shortest distance to all vertices from a source vertex in a
weighted graph.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function dijkstra that takes a Graph object and a source vertex as arguments.
3. The function begins by creating a set unvisited and adding all the vertices in the graph to
it.
4. A dictionary distance is created with keys as the vertices in the graph and their value all
set to infinity.
5. distance[source] is set to 0.
6. The algorithm proceeds by finding the vertex that has the minimum distance in the set
unvisited.
7. It then removes this vertex from the set unvisited.
8. Then all the neighbours of this vertex that have not been visited yet have their distances
updated.
9. The above steps repeat until the set unvisited becomes empty.
10. The dictionary distance is returned.
11. This algorithm works for both undirected and directed graphs.

Program/Source Code
Here is the source code of a Python program to implement Dijkstra’s Shortest Path
algorithm on a graph. The program output is shown below.
class Graph:
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_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])

def __iter__(self):
return iter(self.vertices.values())

class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}

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 dijkstra(g, source):


"""Return distance where distance[v] is min distance from source to v.

This will return a dictionary distance.


g is a Graph object.
source is a Vertex object in g.
"""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0

while unvisited != set():


# find vertex with minimum distance
closest = min(unvisited, key=lambda v: distance[v])

# mark as visited
unvisited.remove(closest)

# update distances
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance

return distance

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

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:
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 == 'shortest':


key = int(do[1])
source = g.get_vertex(key)
distance = dijkstra(g, source)
print('Distances from {}: '.format(key))
for v in distance:
print('Distance to {}: {}'.format(v.get_key(), distance[v]))
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all shortest distances from a source vertex, dijkstra is called on the graph and the
source vertex.

Runtime Test Cases


Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
shortest <source vertex key>
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 vertex 7
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 3 80
What would you like to do? add edge 3 4 70
What would you like to do? add edge 2 5 20
What would you like to do? add edge 2 3 6
What would you like to do? add edge 5 6 50
What would you like to do? add edge 5 7 10
What would you like to do? add edge 6 7 5
What would you like to do? shortest 1
Distances from 1:
Distance to 6: 45
Distance to 3: 16
Distance to 4: 86
Distance to 5: 30
Distance to 2: 10
Distance to 7: 40
Distance to 1: 0

What would you like to do? quit

Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
shortest <source vertex key>
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 edge 1 2 10
What would you like to do? add edge 2 3 20
What would you like to do? add edge 3 4 30
What would you like to do? add edge 1 4 100
What would you like to do? shortest 1
Distances from 1:
Distance to 2: 10
Distance to 4: 60
Distance to 3: 30
Distance to 1: 0

Python Program to Implement Bellman-Ford Algorithm


This is a Python program to implement the Bellman-Ford algorithm on a graph.

Problem Description
The problem is to find the shortest distance to all vertices from a source vertex in a
weighted directed graph that can have negative edge weights. For the problem to be well-
defined, there should be no cycles in the graph with a negative total weight.
Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function bellman-ford that takes a Graph object and a source vertex as
arguments.
3. A dictionary distance is created with keys as the vertices in the graph and their value all
set to infinity.
4. distance[source] is set to 0.
5. The algorithm proceeds by performing an update operation on each edge in the graph n
– 1 times. Here n is the number of vertices in the graph.
6. The update operation on an edge from vertex i to vertex j is distance[j] = min(distance[j],
distance[i] + weight(i, j)).
7. The dictionary distance is returned.

Program/Source Code
Here is the source code of a Python program to implement Bellman-Ford algorithm on a
graph. The program output is shown below.
class Graph:
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_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])

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 = {}

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 bellman_ford(g, source):


"""Return distance where distance[v] is min distance from source to v.

This will return a dictionary distance.

g is a Graph object which can have negative edge weights.


source is a Vertex object in g.
"""
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0

for _ in range(len(g) - 1):


for v in g:
for n in v.get_neighbours():
distance[n] = min(distance[n], distance[v] + v.get_weight(n))

return distance

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('bellman-ford <source vertex key>')
print('display')
print('quit')

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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')

elif operation == 'bellman-ford':


key = int(do[1])
source = g.get_vertex(key)
distance = bellman_ford(g, source)
print('Distances from {}: '.format(key))
for v in distance:
print('Distance to {}: {}'.format(v.get_key(), distance[v]))
print()

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find all shortest distances from a source vertex, bellman-ford is called on the graph
and the source vertex.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest> <weight>
bellman-ford <source vertex key>
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 vertex 7
What would you like to do? add vertex 8
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 8 8
What would you like to do? add edge 2 6 2
What would you like to do? add edge 3 2 1
What would you like to do? add edge 3 4 1
What would you like to do? add edge 4 5 3
What would you like to do? add edge 5 6 -1
What would you like to do? add edge 6 3 -2
What would you like to do? add edge 7 2 -4
What would you like to do? add edge 7 6 -1
What would you like to do? add edge 8 7 1
What would you like to do? bellman-ford 1
Distances from 1:
Distance to 5: 9
Distance to 6: 7
Distance to 7: 9
Distance to 2: 5
Distance to 1: 0
Distance to 8: 8
Distance to 3: 5
Distance to 4: 6

Case 2:
Menu
add vertex <key>
add edge <src> <dest> <weight>
bellman-ford <source vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? bellman-ford 1
Distances from 1:
Distance to 1: 0

What would you like to do? add vertex 2


What would you like to do? bellman-ford 1
Distances from 1:
Distance to 1: 0
Distance to 2: inf

What would you like to do? add edge 1 2 2


What would you like to do? add vertex 3
What would you like to do? add edge 1 3 -1
What would you like to do? bellman-ford 1
Distances from 1:
Distance to 1: 0
Distance to 3: -1
Distance to 2: 2

What would you like to do? add edge 3 2 2


What would you like to do? bellman-ford 1
Distances from 1:
Distance to 1: 0
Distance to 3: -1
Distance to 2: 1

What would you like to do? quit

Python Program to Implement Floyd-Warshall Algorithm


This is a Python program to implement the Floyd-Warshall algorithm on a directed graph to
find the shortest distance between all pairs of vertices.

Problem Description
The problem is to find the shortest distance between all pairs of vertices in a weighted
directed graph that can have negative edge weights. For the problem to be well-defined,
there should be no cycles in the graph with a negative total weight.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function floyd_warshall that takes a Graph object as argument.
3. A dictionary distance is created that can be indexed with two vertices and all the values
set to infinity.
4. Another dictionary next_v is created that can be indexed with two vertices and all the
values set to None.
5. The above is implemented by creating a dictionary with keys as the start vertices and
values as another inner dictionary. This inner dictionary contains keys as the destination
vertices and value as the the corresponding distance for each vertex pair.
6. distance[u][v] will contain the shortest distance from vertex u to v.
7. next_v[u][v] will be the next vertex after vertex v in the shortest path from u to v. It is
None if there is no path between them. next_v[w][w] will be None for all w.
8. For all edges from v to n, distance[v][n] = weight(edge(v, n)) and next_v[v][n] = n.
9. For all vertices v, distance[v][v] = 0 and next_v[v][v] = None.
10. The algorithm then performs distance[v][w] = min(distance[v][w], distance[v][p] +
distance[p][w]) for each possible pair v, w of vertices.
11. The above is repeated for each vertex p in the graph.
12. Whenever distance[v][w] is given a new minimum value, next_v[v][w] is updated to
next_v[v][p].
13. The dictionaries distance and next_v are returned.
14. The function print_path is created to print the shortest path from one vertex to another
vertex using the dictionary next_v.
15. Formally, the Floyd-Warshall algorithm defines W(k)[i][j] to refer to the shortest distance
from i to j using only the vertices 1, …, k where i and j are not necessarily included.
16. For all edges (i, j), W(0)[i][j] = weight(edge(i, j)).
17. To find W(k)[i][j], note that in the shortest path from i to j, we can either have k or not
have k included.
18. If k is not present, W(k)[i][j] = W(k – 1)[i][j].
19. If k is present, W(k)[i][j] = W(k – 1)[i][k] + W(k – 1)[k][j].
20. So we simply set W(k)[i][j] equal to the minimum of the above two values.
21. This program is an implementation of the Floyd-Warshall algorithm but uses only O(n^2)
space instead of O(n^3) space which a straightforward implementation of the algorithm
would take.

Program/Source Code
Here is the source code of a Python program to implement Floyd-Warshall algorithm on a
graph. The program output is shown below.
class Graph:
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_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])

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 = {}

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 floyd_warshall(g):
"""Return dictionaries distance and next_v.

distance[u][v] is the shortest distance from vertex u to v.


next_v[u][v] is the next vertex after vertex v in the shortest path from u
to v. It is None if there is no path between them. next_v[u][u] should be
None for all u.

g is a Graph object which can have negative edge weights.


"""
distance = {v:dict.fromkeys(g, float('inf')) for v in g}
next_v = {v:dict.fromkeys(g, None) for v in g}
for v in g:
for n in v.get_neighbours():
distance[v][n] = v.get_weight(n)
next_v[v][n] = n

for v in g:
distance[v][v] = 0
next_v[v][v] = None

for p in g:
for v in g:
for w in g:
if distance[v][w] > distance[v][p] + distance[p][w]:
distance[v][w] = distance[v][p] + distance[p][w]
next_v[v][w] = next_v[v][p]

return distance, next_v

def print_path(next_v, u, v):


"""Print shortest path from vertex u to v.

next_v is a dictionary where next_v[u][v] is the next vertex after vertex u


in the shortest path from u to v. It is None if there is no path between
them. next_v[u][u] should be None for all u.

u and v are Vertex objects.


"""
p = u
while (next_v[p][v]):
print('{} -> '.format(p.get_key()), end='')
p = next_v[p][v]
print('{} '.format(v.get_key()), end='')

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('floyd-warshall')
print('display')
print('quit')

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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')

elif operation == 'floyd-warshall':


distance, next_v = floyd_warshall(g)
print('Shortest distances:')
for start in g:
for end in g:
if next_v[start][end]:
print('From {} to {}: '.format(start.get_key(),
end.get_key()),
end = '')
print_path(next_v, start, end)
print('(distance {})'.format(distance[start][end]))

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find shortest distances between all pairs, floyd_warshall is called to get the
dictionaries distance, next_v.
4. print_path is called on the dictionary next_v for each pair of vertices to print the paths and
the dictionary distance is used to print the distance between each pair.
Runtime Test Cases
Case 1:
Menu
add vertex <key>
add edge <src> <dest> <weight>
floyd-warshall
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 edge 1 2 3
What would you like to do? add edge 1 5 -4
What would you like to do? add edge 1 3 8
What would you like to do? add edge 2 5 7
What would you like to do? add edge 2 4 1
What would you like to do? add edge 3 2 4
What would you like to do? add edge 4 3 -5
What would you like to do? add edge 4 1 2
What would you like to do? add edge 5 4 6
What would you like to do? floyd-warshall
Shortest distances:
From 1 to 2: 1 -> 5 -> 4 -> 3 -> 2 (distance 1)
From 1 to 3: 1 -> 5 -> 4 -> 3 (distance -3)
From 1 to 4: 1 -> 5 -> 4 (distance 2)
From 1 to 5: 1 -> 5 (distance -4)
From 2 to 1: 2 -> 4 -> 1 (distance 3)
From 2 to 3: 2 -> 4 -> 3 (distance -4)
From 2 to 4: 2 -> 4 (distance 1)
From 2 to 5: 2 -> 4 -> 1 -> 5 (distance -1)
From 3 to 1: 3 -> 2 -> 4 -> 1 (distance 7)
From 3 to 2: 3 -> 2 (distance 4)
From 3 to 4: 3 -> 2 -> 4 (distance 5)
From 3 to 5: 3 -> 2 -> 4 -> 1 -> 5 (distance 3)
From 4 to 1: 4 -> 1 (distance 2)
From 4 to 2: 4 -> 3 -> 2 (distance -1)
From 4 to 3: 4 -> 3 (distance -5)
From 4 to 5: 4 -> 1 -> 5 (distance -2)
From 5 to 1: 5 -> 4 -> 1 (distance 8)
From 5 to 2: 5 -> 4 -> 3 -> 2 (distance 5)
From 5 to 3: 5 -> 4 -> 3 (distance 1)
From 5 to 4: 5 -> 4 (distance 6)
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest> <weight>
floyd-warshall
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 edge 1 2 10
What would you like to do? add edge 2 3 -7
What would you like to do? add edge 1 3 5
What would you like to do? floyd-warshall
Shortest distances:
From 1 to 2: 1 -> 2 (distance 10)
From 1 to 3: 1 -> 2 -> 3 (distance 3)
From 2 to 3: 2 -> 3 (distance -7)
What would you like to do? quit

Python Program to Implement Floyd-Warshall Algorithm


This is a Python program to implement the Floyd-Warshall algorithm on a directed graph to
find the shortest distance between all pairs of vertices.

Problem Description
The problem is to find the shortest distance between all pairs of vertices in a weighted
directed graph that can have negative edge weights. For the problem to be well-defined,
there should be no cycles in the graph with a negative total weight.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function floyd_warshall that takes a Graph object as argument.
3. A dictionary distance is created that can be indexed with two vertices and all the values
set to infinity.
4. Another dictionary next_v is created that can be indexed with two vertices and all the
values set to None.
5. The above is implemented by creating a dictionary with keys as the start vertices and
values as another inner dictionary. This inner dictionary contains keys as the destination
vertices and value as the the corresponding distance for each vertex pair.
6. distance[u][v] will contain the shortest distance from vertex u to v.
7. next_v[u][v] will be the next vertex after vertex v in the shortest path from u to v. It is
None if there is no path between them. next_v[w][w] will be None for all w.
8. For all edges from v to n, distance[v][n] = weight(edge(v, n)) and next_v[v][n] = n.
9. For all vertices v, distance[v][v] = 0 and next_v[v][v] = None.
10. The algorithm then performs distance[v][w] = min(distance[v][w], distance[v][p] +
distance[p][w]) for each possible pair v, w of vertices.
11. The above is repeated for each vertex p in the graph.
12. Whenever distance[v][w] is given a new minimum value, next_v[v][w] is updated to
next_v[v][p].
13. The dictionaries distance and next_v are returned.
14. The function print_path is created to print the shortest path from one vertex to another
vertex using the dictionary next_v.
15. Formally, the Floyd-Warshall algorithm defines W(k)[i][j] to refer to the shortest distance
from i to j using only the vertices 1, …, k where i and j are not necessarily included.
16. For all edges (i, j), W(0)[i][j] = weight(edge(i, j)).
17. To find W(k)[i][j], note that in the shortest path from i to j, we can either have k or not
have k included.
18. If k is not present, W(k)[i][j] = W(k – 1)[i][j].
19. If k is present, W(k)[i][j] = W(k – 1)[i][k] + W(k – 1)[k][j].
20. So we simply set W(k)[i][j] equal to the minimum of the above two values.
21. This program is an implementation of the Floyd-Warshall algorithm but uses only O(n^2)
space instead of O(n^3) space which a straightforward implementation of the algorithm
would take.

Program/Source Code
Here is the source code of a Python program to implement Floyd-Warshall algorithm on a
graph. The program output is shown below.
class Graph:
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_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])

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 = {}

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 floyd_warshall(g):
"""Return dictionaries distance and next_v.

distance[u][v] is the shortest distance from vertex u to v.


next_v[u][v] is the next vertex after vertex v in the shortest path from u
to v. It is None if there is no path between them. next_v[u][u] should be
None for all u.

g is a Graph object which can have negative edge weights.


"""
distance = {v:dict.fromkeys(g, float('inf')) for v in g}
next_v = {v:dict.fromkeys(g, None) for v in g}

for v in g:
for n in v.get_neighbours():
distance[v][n] = v.get_weight(n)
next_v[v][n] = n

for v in g:
distance[v][v] = 0
next_v[v][v] = None

for p in g:
for v in g:
for w in g:
if distance[v][w] > distance[v][p] + distance[p][w]:
distance[v][w] = distance[v][p] + distance[p][w]
next_v[v][w] = next_v[v][p]

return distance, next_v

def print_path(next_v, u, v):


"""Print shortest path from vertex u to v.

next_v is a dictionary where next_v[u][v] is the next vertex after vertex u


in the shortest path from u to v. It is None if there is no path between
them. next_v[u][u] should be None for all u.

u and v are Vertex objects.


"""
p = u
while (next_v[p][v]):
print('{} -> '.format(p.get_key()), end='')
p = next_v[p][v]
print('{} '.format(v.get_key()), end='')

g = Graph()
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('floyd-warshall')
print('display')
print('quit')

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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')

elif operation == 'floyd-warshall':


distance, next_v = floyd_warshall(g)
print('Shortest distances:')
for start in g:
for end in g:
if next_v[start][end]:
print('From {} to {}: '.format(start.get_key(),
end.get_key()),
end = '')
print_path(next_v, start, end)
print('(distance {})'.format(distance[start][end]))

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find shortest distances between all pairs, floyd_warshall is called to get the
dictionaries distance, next_v.
4. print_path is called on the dictionary next_v for each pair of vertices to print the paths and
the dictionary distance is used to print the distance between each pair.

Runtime Test Cases


Case 1:
Menu
add vertex <key>
add edge <src> <dest> <weight>
floyd-warshall
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 edge 1 2 3
What would you like to do? add edge 1 5 -4
What would you like to do? add edge 1 3 8
What would you like to do? add edge 2 5 7
What would you like to do? add edge 2 4 1
What would you like to do? add edge 3 2 4
What would you like to do? add edge 4 3 -5
What would you like to do? add edge 4 1 2
What would you like to do? add edge 5 4 6
What would you like to do? floyd-warshall
Shortest distances:
From 1 to 2: 1 -> 5 -> 4 -> 3 -> 2 (distance 1)
From 1 to 3: 1 -> 5 -> 4 -> 3 (distance -3)
From 1 to 4: 1 -> 5 -> 4 (distance 2)
From 1 to 5: 1 -> 5 (distance -4)
From 2 to 1: 2 -> 4 -> 1 (distance 3)
From 2 to 3: 2 -> 4 -> 3 (distance -4)
From 2 to 4: 2 -> 4 (distance 1)
From 2 to 5: 2 -> 4 -> 1 -> 5 (distance -1)
From 3 to 1: 3 -> 2 -> 4 -> 1 (distance 7)
From 3 to 2: 3 -> 2 (distance 4)
From 3 to 4: 3 -> 2 -> 4 (distance 5)
From 3 to 5: 3 -> 2 -> 4 -> 1 -> 5 (distance 3)
From 4 to 1: 4 -> 1 (distance 2)
From 4 to 2: 4 -> 3 -> 2 (distance -1)
From 4 to 3: 4 -> 3 (distance -5)
From 4 to 5: 4 -> 1 -> 5 (distance -2)
From 5 to 1: 5 -> 4 -> 1 (distance 8)
From 5 to 2: 5 -> 4 -> 3 -> 2 (distance 5)
From 5 to 3: 5 -> 4 -> 3 (distance 1)
From 5 to 4: 5 -> 4 (distance 6)
What would you like to do? quit

Case 2:
Menu
add vertex <key>
add edge <src> <dest> <weight>
floyd-warshall
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 edge 1 2 10
What would you like to do? add edge 2 3 -7
What would you like to do? add edge 1 3 5
What would you like to do? floyd-warshall
Shortest distances:
From 1 to 2: 1 -> 2 (distance 10)
From 1 to 3: 1 -> 2 -> 3 (distance 3)
From 2 to 3: 2 -> 3 (distance -7)
What would you like to do? quit
Python Program to Find Minimum Spanning Tree using Prim’s
Algorithm
This is a Python program to find a minimum spanning tree of an undirected weighted graph
using Prim’s algorithm.

Problem Description
A spanning tree of a graph can be defined as a graph with minimal set of edges that
connect all vertices. A minimum spanning tree of a graph is a spanning tree of the graph
with least weight (where the weight is computed by adding the weights of all the edges in
the spanning tree). In general, a graph can have multiple minimum 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_prim 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 selecting any one vertex from g and adding it to mst.
6. The vertex which is outside mst but has a neighbour in mst with the smallest distance is
added to mst. (If there are multiple such vertices then add any one.)
7. The corresponding edge is also added.
8. The above two steps are repeated until all vertices have been added to the graph.
9. Two dictionaries are used in the above algorithm.
10. The nearest neighbour in mst of a vertex outside mst is kept track of using a dictionary
nearest_neighbour.
11. The corresponding smallest distance is stored in a dictionary called smallest_distance.

Program/Source Code
Here is the source code of a Python program to find the minimum spanning tree of an
undirected weighted graph using Prim’s algorithm. The program output is shown below.
class Graph:
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_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])

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 = {}

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_prim(g):
"""Return a minimum cost spanning tree of the connected graph g."""
mst = Graph() # create new Graph object to hold the MST

# if graph is empty
if not g:
return mst

# nearest_neighbour[v] is the nearest neighbour of v that is in the MST


# (v is a vertex outside the MST and has at least one neighbour in the MST)
nearest_neighbour = {}
# smallest_distance[v] is the distance of v to its nearest neighbour in the MST
# (v is a vertex outside the MST and has at least one neighbour in the MST)
smallest_distance = {}
# v is in unvisited iff v has not been added to the MST
unvisited = set(g)

u = next(iter(g)) # select any one vertex from g


mst.add_vertex(u.get_key()) # add a copy of it to the MST
unvisited.remove(u)

# for each neighbour of vertex u


for n in u.get_neighbours():
if n is u:
# avoid self-loops
continue
# update dictionaries
nearest_neighbour[n] = mst.get_vertex(u.get_key())
smallest_distance[n] = u.get_weight(n)

# loop until smallest_distance becomes empty


while (smallest_distance):
# get nearest vertex outside the MST
outside_mst = min(smallest_distance, key=smallest_distance.get)
# get the nearest neighbour inside the MST
inside_mst = nearest_neighbour[outside_mst]

# add a copy of the outside vertex to the MST


mst.add_vertex(outside_mst.get_key())
# add the edge to the MST
mst.add_edge(outside_mst.get_key(), inside_mst.get_key(),
smallest_distance[outside_mst])
mst.add_edge(inside_mst.get_key(), outside_mst.get_key(),
smallest_distance[outside_mst])

# now that outside_mst has been added to the MST, remove it from our
# dictionaries and the set unvisited
unvisited.remove(outside_mst)
del smallest_distance[outside_mst]
del nearest_neighbour[outside_mst]

# update dictionaries
for n in outside_mst.get_neighbours():
if n in unvisited:
if n not in smallest_distance:
smallest_distance[n] = outside_mst.get_weight(n)
nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())
else:
if smallest_distance[n] > outside_mst.get_weight(n):
smallest_distance[n] = outside_mst.get_weight(n)
nearest_neighbour[n] = mst.get_vertex(outside_mst.get_key())

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')

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:
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_prim(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.
3. mst_prim is called to get a minimum spanning tree of the graph.
4. This is then displayed.

Runtime 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 vertex 7
What would you like to do? add edge 1 3 18
What would you like to do? add edge 1 2 10
What would you like to do? add edge 3 4 70
What would you like to do? add edge 3 2 6
What would you like to do? add edge 2 5 20
What would you like to do? add edge 5 6 10
What would you like to do? add edge 5 7 10
What would you like to do? add edge 6 7 5
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3 4 5 6 7
Edges:
(src=1, dest=2, weight=10)
(src=2, dest=5, weight=20)
(src=2, dest=1, weight=10)
(src=2, dest=3, weight=6)
(src=3, dest=2, weight=6)
(src=3, dest=4, weight=70)
(src=4, dest=3, weight=70)
(src=5, dest=6, weight=10)
(src=5, dest=2, weight=20)
(src=6, dest=5, weight=10)
(src=6, dest=7, weight=5)
(src=7, dest=6, weight=5)

What would you like to do? quit

Case 2:
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 edge 1 2 10
What would you like to do? add edge 2 3 100
What would you like to do? add edge 1 3 50
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3
Edges:
(src=1, dest=2, weight=10)
(src=1, dest=3, weight=50)
(src=2, dest=1, weight=10)
(src=3, dest=1, weight=50)

What would you like to do? quit

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 edges that connect all
vertices. A minimum spanning tree of a graph is a spanning tree of the graph with least weight
(where the weight is computed by adding the weights of all the edges in the spanning tree). In
general, a graph can have multiple minimum 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
Here is the source code of a Python program to find the minimum spanning tree of an undirected
weighted graph using Krusal’s algorithm. The program output is shown below.
class Graph:
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])

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 = {}

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."""
mst = Graph() # create new Graph object to hold the MST

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

# get all the edges in a list


edges = []
for v in g:
for n in v.get_neighbours():
# avoid adding two edges for each edge of the undirected graph
if v.get_key() < n.get_key():
edges.append((v, n))

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

# initially, each vertex is in its own component


component = {}
for i, v in enumerate(g):
component[v] = i

# next edge to try


edge_index = 0

# loop until mst has the same number of vertices as g


while len(mst) < len(g):
u, v = edges[edge_index]
edge_index += 1

# if adding edge (u, v) will not form a cycle


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

# add to mst
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))

# merge components of u and 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')

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:
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.
3. mst_krusal is called to get a minimum spanning tree of the graph.
4. This is then displayed.

Runtime 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
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)

What would you like to do? quit

Case 2:
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 edge 1 2 10
What would you like to do? add edge 1 3 20
What would you like to do? add edge 2 3 30
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3
Edges:
(src=1, dest=3, weight=20)
(src=1, dest=2, weight=10)
(src=2, dest=1, weight=10)
(src=3, dest=1, weight=20)

What would you like to do? quit

Python Program to Implement Johnson’s Algorithm


This is a Python program to implement Johnson’s algorithm on a directed graph to find the
shortest distance between all pairs of vertices.

Problem Description
The problem is to find the shortest distance between all pairs of vertices in a weighted
directed graph that can have negative edge weights. For the problem to be well-defined,
there should be no cycles in the graph with a negative total weight.

Problem Solution
1. Create classes for Graph and Vertex.
2. Create a function johnson that takes a Graph object g as argument.
3. It returns a dictionary distance where distance[u][v] is the minimum distance from vertex
u to v.
4. The algorithm works by first adding a new vertex q to the graph g.
5. This vertex q is made to point to all other vertices wit zero-weight edges.
6. The Bellman-Ford algorithm is run on the graph with source vertex q to find the shortest
distance from q to all other vertices. This is stored in bell_dist where bell_dist[v] is the
shortest distance from q to v.
7. Modify the graph’s weight function and set it to w(u, v) = w(u, v) + bell_dist(u) –
bell_dist(v).
8. Remove the vertex q from the graph.
9. Run Dijkstra’s algorithm on each source vertex in the graph to find the shortest distance
from each source vertex to all other vertices in this modified graph.
10. These shortest distances are stored in distance where distance[u][v] is the shortest
distance from u to v.
11. Add (bell_dist[v] – bell_dist[u]) to distance[u][v] for each pair of vertices u, v to get the
shortest distances for the original graph.
12. Correct the weights in the graph by adding (bell_dist[v] – bell_dist[u]) to weight(u, v) for
each edge (u, v) in the graph so that the graph is no longer modified.

Program/Source Code
Here is the source code of a Python program to implement Johnson’s algorithm on a
directed graph. The program output is shown below.
class Graph:
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_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])

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 = {}

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 set_weight(self, dest, weight):


"""Set weight of edge from this vertex to dest."""
self.points_to[dest] = weight

def does_it_point_to(self, dest):


"""Return True if this vertex points to dest."""
return dest in self.points_to
def johnson(g):
"""Return distance where distance[u][v] is the min distance from u to v.

distance[u][v] is the shortest distance from vertex u to v.

g is a Graph object which can have negative edge weights.


"""
# add new vertex q
g.add_vertex('q')
# let q point to all other vertices in g with zero-weight edges
for v in g:
g.add_edge('q', v.get_key(), 0)

# compute shortest distance from vertex q to all other vertices


bell_dist = bellman_ford(g, g.get_vertex('q'))

# set weight(u, v) = weight(u, v) + bell_dist(u) - bell_dist(v) for each


# edge (u, v)
for v in g:
for n in v.get_neighbours():
w = v.get_weight(n)
v.set_weight(n, w + bell_dist[v] - bell_dist[n])

# remove vertex q
# This implementation of the graph stores edge (u, v) in Vertex object u
# Since no other vertex points back to q, we do not need to worry about
# removing edges pointing to q from other vertices.
del g.vertices['q']

# distance[u][v] will hold smallest distance from vertex u to v


distance = {}
# run dijkstra's algorithm on each source vertex
for v in g:
distance[v] = dijkstra(g, v)

# correct distances
for v in g:
for w in g:
distance[v][w] += bell_dist[w] - bell_dist[v]

# correct weights in original graph


for v in g:
for n in v.get_neighbours():
w = v.get_weight(n)
v.set_weight(n, w + bell_dist[n] - bell_dist[v])

return distance

def bellman_ford(g, source):


"""Return distance where distance[v] is min distance from source to v.

This will return a dictionary distance.


g is a Graph object which can have negative edge weights.
source is a Vertex object in g.
"""
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0

for _ in range(len(g) - 1):


for v in g:
for n in v.get_neighbours():
distance[n] = min(distance[n], distance[v] + v.get_weight(n))

return distance

def dijkstra(g, source):


"""Return distance where distance[v] is min distance from source to v.

This will return a dictionary distance.

g is a Graph object.
source is a Vertex object in g.
"""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0

while unvisited != set():


# find vertex with minimum distance
closest = min(unvisited, key=lambda v: distance[v])

# mark as visited
unvisited.remove(closest)

# update distances
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance

return distance

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

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:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
else:
print('Edge already exists.')

elif operation == 'johnson':


distance = johnson(g)
print('Shortest distances:')
for start in g:
for end in g:
print('{} to {}'.format(start.get_key(), end.get_key()), end=' ')
print('distance {}'.format(distance[start][end]))

elif operation == 'display':


print('Vertices: ', end='')
for v in g:
print(v.get_key(), end=' ')
print()

print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
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.
3. To find shortest distances between all pairs, johnson is called to get the dictionary
distance.
4. The distances between each pair of vertices are then displayed.
Runtime Test Cases
Case 1:
Menu
add vertex <key>
add edge <src> <dest> <weight>
johnson
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 edge 1 2 3
What would you like to do? add edge 1 3 8
What would you like to do? add edge 1 5 -4
What would you like to do? add edge 2 5 7
What would you like to do? add edge 2 4 1
What would you like to do? add edge 3 2 4
What would you like to do? add edge 4 3 -5
What would you like to do? add edge 4 1 2
What would you like to do? add edge 5 4 6
What would you like to do? johnson
Shortest distances:
1 to 1 distance 0
1 to 2 distance 1
1 to 3 distance -3
1 to 4 distance 2
1 to 5 distance -4
2 to 1 distance 3
2 to 2 distance 0
2 to 3 distance -4
2 to 4 distance 1
2 to 5 distance -1
3 to 1 distance 7
3 to 2 distance 4
3 to 3 distance 0
3 to 4 distance 5
3 to 5 distance 3
4 to 1 distance 2
4 to 2 distance -1
4 to 3 distance -5
4 to 4 distance 0
4 to 5 distance -2
5 to 1 distance 8
5 to 2 distance 5
5 to 3 distance 1
5 to 4 distance 6
5 to 5 distance 0
What would you like to do? quit

Case 2:
python 226__graph_johnson.py
Menu
add vertex <key>
add edge <src> <dest> <weight>
johnson
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? johnson
Shortest distances:
1 to 1 distance 0
1 to 2 distance inf
2 to 1 distance inf
2 to 2 distance 0
What would you like to do? add edge 1 2 100
What would you like to do? add vertex 3
What would you like to do? add edge 2 3 -50
What would you like to do? add edge 1 3 60
What would you like to do? johnson
Shortest distances:
1 to 1 distance 0
1 to 2 distance 100
1 to 3 distance 50
2 to 1 distance inf
2 to 2 distance 0
2 to 3 distance -50
3 to 1 distance inf
3 to 2 distance inf
3 to 3 distance 0
What would you like to do? quit

You might also like