Illustrative Problems
Illustrative Problems
BEGIN READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF
END FOR
PRINT min
END
Flowchart: Find minimum in a list
2.Insert a card in a list of sorted cards
Algorithm: Insert a card in a list of sorted cards
Step 1: Start
Step 2: Read n Step 10: a[i+1]=a[i]
Step 3: Initialize i=0 Step 11: i=i-1 goto step 9
Step 4: If i<n, then goto step 5, Step 12: Compute a[i+1]=item
6 else goto step 7 Step 13: Compute n=n+1,i=0
Step 5: Read a[i] Step 14: If i<n, then goto step 15,
Step 6: i=i+1 goto step 4 16 else goto step 17
Step 7: Read item Step 15: Print a[i]
Step 8: Calculate i=n-1 Step 16: i=i+1 goto step 14
Step 9: If i>=0 and item<a[i], Step 17: Stop
then go to step 10, 11 else goto
step 12
Pseudocode: Insert a card in a list of sorted cards
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
Flowchart: Insert a card in a list of sorted cards
3.Guess an Integer in a Range
Algorithm - Guess an Integer in a Range
Pseudocode - Guess an Integer in a Range
Flowchart - Guess an Integer in a Range
4.Towers of Hanoi
Towers of Hanoi
• Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more
• Tower of Hanoi is one of the best example for recursive problem solving.
.
Towers of Hanoi - Conditions
Pre-condition:
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
Post-condition:
All the disk should be moved to the last pole and placed only in ascending order as shown
below.
Towers of Hanoi - Rules
• Only one disk can be moved among the towers at any given time.
• Tower of Hanoi puzzle with n disks can be solved in minimum 2^n−1 steps. This presentation
• If we have only one disk, then it can easily be moved from source to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
Towers of Hanoi - Steps
Step 1: Start
Step 8: Stop
Towers of Hanoi - Flowchart
Towers of Hanoi - Pseudocode
BEGIN
READ n
n=n-1
END FOR
END
Towers of Hanoi - Recursive Algorithm
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call Hanoi(n,Beg,Aux,End)
Step 5: Stop
Algorithm :
Output:
Enter the value of a: 10
Enter the value of b: 15
The values before swapping 10, 15
The values after swapping 15, 10
Python Program to Exchange the values of two Variable
within Function
def swap(a,b):
temp=a
a=b
b=temp
print("The values a and b after swapping:", a, b)
n1=int(input("Enter the value of n1:"))
n2=int(input("Enter the value of n2:"))
print ("The values of n1 and n2 before swapping:", n1, n2)
swap(n1,n2)
Output:
Enter the value of n1: 10
Enter the value of n2: 15
The values of n1 and n2 before swapping: 10, 15
Output:
Enter the value of a: 10
Enter the value of b: 15
The values before swapping: 10, 15
The values after swapping: 15, 10
2. Circulate the Values of n Variable
Circulate the Values of n Variable
Algorithm :
Step 5: Using range function and Pop Function to circulate the Variables
Algorithm :
Step 3: Calculate the Distance Using the formula sqrt (((x2-x1)**2) + ((y2-y1)**2))
# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = math.sqrt(( (x2-x1)**2) + ((y2-y1)**2 ))
Python Program to Calculate Distance Between Two Points
( Co-ordinates)
import math
def distance(x1,y1,x2,y2):
dx=x2-x1
dy=y2-y1
f=dx**2 + dy**2
result=math.sqrt(f)
return result
a=int(input("Enter the value of x- coordinate of point 1:"))
b=int(input("Enter the value of y- coordinate of point 1:"))
c=int(input("Enter the value of x- coordinate of point 2:"))
d=int(input("Enter the value of y- coordinate of point 2:"))
r=distance(a,b,c,d)
print("The distance between (",a,",",b,“ )and (",c,",",d,") is",r)
Python Program to Calculate Distance Between Two Points
( Co-ordinates)
Output:
UNIT 3
Quadratic Equation
Quadratic Equation
Quadratic Equation
Quadratic Equation
import math
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
# calculate the D
d = (b**2) - (4*a*c)
Algorithm:
Step 1: Start the Program
Step 2: Initialize the Array with values
Step 3: Initialize Sum =0
Step 4: for i in range(len(arr))
Step 4.1: Caluculate Sum= sum +arr[i]
Step 5: Print Sum
Step 6: Stop the program
Sum an array of Integers – ( Using Iteration)
Sum an array of Integers – ( Using Iteration)
Sum = 0
for i in range(len(arr)):
print (Sum)
Sum an array of Integers – ( Using in-built Function)
Using in-built function sum(arr), we can get the sum of the elements
of the array passed to it.
Sum an array of Integers – Runtime Input
Exponentiation
Exponentiation– ( Using Exponential Operator)
Algorithm:
Step1: Start the program
Step 2: Get the base Number
Step 3: Get the Exponential Value / Power Value
Step 4: Calculate base ** Power
Step 5: Print the result
Step 6: Stop the Program
Exponentiation– ( Using Exponential Operator)
result=num**exp
print("Result is:",result)
Exponentiation– ( Using Built in Method)
import math
num=int(input("Enter number: "))
exp=int(input("Enter exponential value: "))
result=math.pow(num,exp)
print("Result is:",result)
Greatest Common Divisor ( GCD)
Greatest Common Divisor ( GCD)
Algorithm:
Initialize GCD = 1
Note down the highest number that divides both num1 & num2
• The math.gcd() method returns the greatest common divisor of the two integers int1
and int2.
• GCD is the largest common divisor that divides the numbers without a remainder.
• GCD is also known as the highest common factor (HCF).
Syntax:
math.gcd(int1, int2)
Parameter Values
Greatest Common Divisor ( GCD) Using Built In Functions
sequential manner.
It compares each and every element with the value that we are searching for. If both
are matched, the element is found, and the algorithm returns the key's index position.
Linear Search - Concept
Linear Search – Python Script
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Binary Search
Binary Search
• If the element is present in the list, then the process is called successful, and the
• Binary search is the search technique that works efficiently on sorted lists.
• Binary search follows the divide and conquer approach in which the list is divided
into two halves, and the item is compared with the middle element of the list.
• If the match is found then, the location of the middle element is returned.
• Otherwise, we search into either of the halves depending upon the result produced
array = [3, 4, 5, 6, 7, 8, 9]
x=4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
UNIT 4
Simple Sorting
Simple Sorting
#List of Integers
Numbers=[1,3,4,2]
#sorting list of integers
Numbers.sort()
Print(numbers)
#list of decimal numbers
Decimalnumber=[2.01.2.00,3.67,3.28,1.68]
Decimalnumber.sort()
Print(decimalnumbers)
Output:
#list of strings
1, 2, 3, 4
words=[‘welcome’, ‘all] 1.68, 2.0, 2.01, 3.28, 3.67
Words.sort() all , welcome
Print(words)
SELECTION SORT
It start with the second element and put it in its correct place, so
that the first and second elements of the list are in order. This
process continues until all the elements have been sorted
For pass p=1 through n-1, insertion sort ensures that the elements
in position 0 through p are in sorted order.
• Merge sort uses divide and conquer method. The problem is divided into smaller
problem and solved recursively. Finally it merges two sorted list.
• Basic algorithm:
i. Divide the given array of elements into two half.
ii. Recursively sort the first half and second half of array elements.
iii. Take two input arrays A and B, an output array C
iv. The first element of A array and B array are compared, then the smaller
element is sorted in the output array C, the corresponding pointer is incremented.
v. This step is repeated until all the elements are compared.
MERGE SORT
MERGE SORT
def mergesort(a):
if len(a) < 2:
return a
middle = int(len(a)/2)
left = mergesort(a[:middle])
right = mergesort(a[middle:])
return merge(left, right)
a=[30,50,10,40,20]
print("Before sorting ...")
print(a)
print("After sorting ...")
print(mergesort(a))
QUICK SORT
• Basic algorithm:
i. If the number of elements in S is 0 or 1, then return
ii. Pick any element v in S. this is called the pivot
iii. Partition S-{v} (the remaining elements in S) into two
disjoint groups: return {quicksort(S1) followed by v
followed by v followed by quicksort(s2)}
QUICK SORT
QUICK SORT
• Just like the movement of air bubbles in the water that rise up
to the surface, each element of the array move to the end in
each iteration. Therefore, it is called a bubble sort.
BUBBLE SORT
BUBBLE SORT
def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Histograms
HISTOGRAM
Definition of Histogram : Histogram is visual representation of the distribution of quantitative variable. It is
appeared as vertical bar graph. It represents the distribution of variable being studied.
Parts of Histogram:
Title : The title gives a brief description of what the information is represented by the histogram.
Horizontal or X-Axis : The horizontal or X-axis shows you the range or the values of gaps in between variables. They
are commonly called class intervals which represent or summarize large data sets.
Vertical or Y-Axis : The vertical or Y-axis represents the range values of frequencies or the number of times that the
class intervals occurred.
Bars : The bars represent the object, item, event, or person from where the variables arise. Their height denotes their
respective frequencies, while the bar placement along the X-axis indicates their respective interval values. The width,
however, is the same for all bars.
Bin : Histograms use bins to display data-where a bin represents a given range of values. It is very simple to plot the
Histogram in Python, but for that we need to install few libraries – namely numpy, scipy and mathplotlib.
HISTOGRAM
Histogram
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.
Student Mark Statement
#Enter five subject Marks
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: "))
#Calculate Average
avg=(sub1+sub2+sub3+sub4+sub4)/5
print(“First Subject Mark”,sub1)
print(“Second Subject Mark”,sub2)
print(“Third Subject Mark”,sub3)
print(“Fourth Subject Mark”,sub4)
print(“Fifth Subject Mark”,sub5)
Print(“Average”,avg)
Student Mark Statement
#Find Grade and print
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")
Student Mark Statement
Output:
Enter the First Subject Mark: 85
Enter the Second Subject Mark: 95
Enter the Third Subject Mark: 99
Enter the Fourth Subject Mark: 93
Enter the Fifth Subject Mark : 98
Average: 93
Grade : A
Retail Bill Preparation
Retail Bill Preparation
#simple retail bill preparation
a=0
b=0
sum=0
While true:
item=input(‘Item’)
unit=input(‘Enter the unit’)
a=int(unit)
price=input(‘Enter the price’)
b=int(price)
sum+=a*b
next_item=input(‘Is There another item?’)
if(next_item!=‘yes’):
print(‘Please Choose between yes or no’)
if(next_item==‘no’):
break
Print(‘Total Amount for Items Purchased:’, sum)
Retail Bill Preparation
Output
Item : Milk
Enter the Unit: 10
Enter the Price : 50
Is there another Item? Yes
Item: Bread
Enter the Unit: 5
Enter the Price : 30
Is there another Item? No
Program:
file = open("C:\data.txt", "r")
data = file.read()
words = data.split()
Input : data.txt
Welcome to www.pythonexamples.org. Here, you will Output
find python programs for all general use cases.
Number of words in text file : 21
This is another line with some words.
Copy File
Copy File (Method 1)
Program:
Output
with open("test.txt") as f:
for line in f:
f1.write(line)
Copy File (Method 2)
Voters Age Validation
Voters Age Validation ( Method 1)
#this program check voting eligibility
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18: Output 1:
print("Eligible to vote") Enter your age 24
else: Eligible to vote
print("Not eligible to vote")
except ValueError: Output 2:
print("age must be a valid number") Enter your age 6T
except IOError: Enter correct value
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
Voters Age Validation ( Method 2)
import datetime
Year_of_birth=int(input(“In which year you took birth:”))
Current_year=datetime.datetime.now().year
Current _age=current year-year of birth
Print(“your current age is:”,Current_age)
if (Current age>=18):
Output 1:
print(“You are eligible to vote”)
else: In which year you took birth:2000
your current age is:22
print(“you are not eligible to vote”) You are eligible to vote
Mark Range Validation ( 0 – 100 )
Mark Range Validation ( 0 – 100 )
Name=input(“Enter the student name:”)
Regno=input(“Enter the student Register Number:”)
try:
mark1=int(input(“Enter the Mark1:”))
mark2=int(input(“Enter the Mark2:”))
if(0<=mark1<=100)and(0<=mark2<=100):
print(“Marks are in the range”)
else:
raise ValueError(“Marks are not in the range”)
Except ValueError as err:
Print(err)
finally:
#code to be excecuted when there is no exception
print(“Thankyou,you have successfully checked”)
Mark Range Validation ( 0 – 100 )
Output 1:
Enter the student name: ABC