It Workshop
It Workshop
in
Computer Science and Engineering
Lab Manual
For
18CS5SP08L
IT Workshop (Python)
1
CONTENTS
3. PEOs 4
2
Institute Vision and Mission
Vision:
To be a leading technical institution that offers a transformative education to create leaders and
innovators with ethical values to contribute for the sustainable development and economic growth of our
nation.
Mission:
M1: To impart high standard of engineering education through innovative teaching and research to meet
the changing needs of the modern society.
M2: To provide outcome-based education that transforms the students to understand and solve the
societal, industrial problems through engineering and technology.
M3: To collaborate with other leading technical institutions and organization to develop globally
competitive technocrats and entrepreneurs.
Vision:
To emerge as a model center for education and research in the area of Computer Science and
Engineering through Knowledge acquisition, dissemination and generation to meet societal demands.
Mission:
M1: To impart the quality education in cutting edge technologies, teaching & learning ambience in
Computer Science and Engineering.
M2: To establish a center of excellence in collaboration with industries, research laboratories and other
agencies to meet the changing needs of society.
M3: To provide an environment conducive to develop innovation, team-spirit and Entrepreneurship.
M4: To practice and promote high standards of professional ethics and transparency.
3
Program Educational Objectives (PEOs)
Program Outcomes
4
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
4. research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
5. modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to
6. assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
7. engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
8.
and norms of the engineering practice.
Individual and teamwork: Function effectively as an individual, and as a member or
9.
leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
10.
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
11.
member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
12. engage in independent and life-long learning in the broadest context of technological
change.
5
Course Outcome Statements and CO-PO Mapping
CO – PO Mapping
CO/PO: Mapping
(H/M/L indicates strength of correlation) 3-High, 2-Medium, 1-Low
Course Programme Outcome (POs)
Outcome PO-9 PSO-2
PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-10 PO-11 PO-12 PSO-1
(COs)
CO-1 3 2 2 1 1 1 1
CO-2 3 2 2 1 1 1 1
CO-3 3 2 2 1 1 2 2
CO-4 3 2 2 2 1 1 2 2
CO-5 3 2 3 2 1 1 2 2
CO-6 3 2 3 2 1 1 2 2
Avg : 18 12 14 9 3 6 10 10
6
List of Experiment with CO Mapping
8
2. Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners
with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) Kindle Edition
( by LCF Publishing (Author), Jamie Chan (Author) Format: Kindle Edition)
JUPYTER NOTEBOOK
Jupyter Notebook is an open-source web application that allows you to create and share documents
that contain live code, equations, visualizations, and narrative text. Uses include data cleaning and
transformation, numerical simulation, statistical modeling, data visualization, machine learning,
and much more.
Jupyter has support for over 40 different programming languages and Python is one of them.
Python is a requirement (Python 3.3 or greater, or Python 2.7) for installing the Jupyter Notebook
itself.
Jupyter Notebook can be installed by using either of the two ways described below:
Using Anaconda:
Install Python and Jupyter using the Anaconda Distribution, which includes Python, the Jupyter
Notebook, and other commonly used packages for scientific computing and data science. To install
Anaconda, go through How to install Anaconda on windows? and follow the instructions provided.
Using PIP:
Install Jupyter using the PIP package manager used to install and manage software
packages/libraries written in Python. To install pip, go through How to install PIP on Windows?
and follow the instructions provided.
9
Click on the Install Jupyter Notebook Button
10
Beginning the Installation:
Launching Jupyter:
11
Installing Jupyter Notebook using pip:
PIP is a package management system used to install and manage software packages/libraries
written in Python. These files are stored in a large “on-line repository” termed as Python Package
Index (PyPI).
pip uses PyPI as the default source for packages and their dependencies.
To install Jupyter using pip, we need to first check if pip is updated in our system. Use the
following command to update pip:
python -m pip install --upgrade pip
After updating the pip version, follow the instructions provided below to install Jupyter:
Command to install Jupyter:
python -m pip install jupyter
Beginning Installation:
12
Experiment -1
Write programs to implement the following operations:
A. To elaborate variables and their data types such as int, float, boolean, string, list, set, Dictionary and
tuples; swap two numbers.
Description:
Data types are the classification or categorization of data items. Data types represent a kind of
value which determines what operations can be performed on that data. Numeric, non-numeric and
Boolean (true/false) data are the most used data types. However, each programming language has
its own classification largely reflecting its programming philosophy.
Program:
Int, Float:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Boolean:
print(type(True))
print(type(False))
Output:
String:
# Creating a String
# with single Quotes
String1 = 'Welcome to Jain University'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
13
# with double Quotes
String1 = "I'm souvik"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm souvik.I study in Jain University'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Jain
University'''
print("\nCreating a multiline String: ")
print(String1)
Output:
List:
# Creating a List
List = []
print("Intial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['JainUniversity']
print("\nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Jain", "University"]
print("\nList containing multiple values: ")
print(List[0])
print(List[1])
Output:
14
Set:
# Creating a Set
set1 = set()
print("Intial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set("Jain University")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["Jain", "University", "souvik"])
print("\nSet with the use of List: ")
print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Jain', 4, 'University', 6])
print("\nSet with the use of Mixed Values")
print(set1)
Output:
Dictionary:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
15
# with Integer Keys
Dict = {1: 'Jain', 2: 'University', 3: 'Souvik'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Jain', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Jain', 2: 'University', 3: 'Souvik'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Jain'), (2, 'University')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Tuple:
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple with
# the use of Strings
Tuple1 = ('Jain', 'Univeraity')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Jain')
16
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Jain', 'University')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Output:
Experiment -1
b. To perform mathematical operations such as addition, subtraction, multiplication, division, modulo, and
power; also explore the operator precedence.
Program:
a,b=[int(x) for x in input('Enter two Numbers (give coma in between
them):').split(',')]
17
print("Sum of",a,"and",b,"=",a+b)
print("subtraction from",a,"to",b,"=",a-b)
print("Multiplication of",a,"and",b,"=",a*b)
print("Division of",a,"by",b,"=",a/b)
print("Reminder after dividing",a,"by",b,"=",a%b)
print(a,"powerof",b,"=",a**b)
Output:
18
Experiment -2
Write programs to implement conditional operations on following:
a. Python program to find the sum and average of natural numbers up to n where n is provided by user.
Description :
Allows a user to enter the number (n) he wishes to calculate the sum and average. The program
accepts user input using the input function.
Next, run loop till the entered number using the for loop and range() function.
Next, calculate the sum using a sum = sum + current number formula.
At last, after the loop ends, calculate the average using average = sum / n. n is a number entered by
the user.
Program :
n=int (input("Enter upto which number you want sum and average"))
sum=0
avg=0
for i in range(0,n+1,1):
sum=sum+i
avg=sum/n
print("Total of first {} numbers is {}".format(n,sum))
print("Average of first {a} numbers is {b}".format(a=n,b=avg))
Output:
19
Experiment -2
B. Python program to find factorial, and Fibonacci of a number, received by user, with iterative as well
as recursive process.
Description: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8,
13, 21, 34, 55, 89, 144, ……. A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.... The first
two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This means to say the
nth term is the sum of (n-1)th and (n-2)th term. In mathematical terms, the sequence Fn of Fibonacci numbers
is defined by the recurrence relation
Program:
# Factorial of a number using
Iterative:
n=int(input("Enter number to get factorial"))
result=1
if n<0:
print("Factorial is not possible for negative number")
elif n==0:
print("Factorial of {} is {}".format(0,1))
else:
for i in range(n,0,-1):
result=result*i
print("Factorial of {} is {}".format(n,result))
Output:
Output:
Factorial of a number:
Recursive:
Def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
Output:
Output:
21
Recursive:
deffib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
nterms = int(input("How many terms? "))
ifnterms<= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fib(i))
Output:
22
Experiment -3
23
Experiment -3
b. To find largest among three numbers, input by user.
Program:
Ans:
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
n3 = int(input("Enter third number: "))
Output:
24
Experiment -3
25
Experiment -4
If x doesn’t match with any of elements in arr[] , return -1 or element not found.
Program:
search.
Linear Search:
deflinearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
Output:
Description: In a nutshell, this search algorithm takes advantage of a collection of elements that is already
sorted by ignoring half of the elements after just one comparison.
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray after the
mid element. Then we apply the algorithm again for the right half.
4. Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the left
half.
Program:
defbinary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid
elifarr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
26
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 10
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element",x,"is present at index", str(result))
else:
print("Element is not present in array")
Output:
27
Experiment -4
b) Implement a python script to arrange the elements in sorted order using Bubble, Selection, Insertion
and Merge sorting techniques.
Description: Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of a list are
checked and swapped if they are in wrong order and this process is repeated until we get a sorted list. The
steps of performing a bubble sort are:
Compare the first and the second element of the list and swap them if they are in wrong order.
Compare the second and the third element of the list and swap them if they are in wrong order.
Proceed till the last element of the list in a similar fashion.
Repeat all of the above steps until the list is sorted.
Program :
Bubble Sort:
a = [16, 19, 11, 15, 10, 12, 14]
for j in range(len(a)):
swapped = False
i = 0
while i<len(a)-1:
if a[i]>a[i+1]:
a[i],a[i+1] = a[i+1],a[i]
swapped = True
i = i+1
if swapped == False:
break
print('The sorted order is:')
print (a)
Output:
Selection Sort:
Description: The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains
two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted
subarray is picked and moved to the sorted subarray.
28
a = [16, 19, 11, 15, 10, 12, 14]
i = 0
while i<len(a):
smallest = min(a[i:])
index_of_smallest = a.index(smallest)
a[i],a[index_of_smallest] = a[index_of_smallest],a[i]
i=i+1
print('The sorted list is:')
print (a)
Output:
Insertion Sort:
definsertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key <arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [16,19,11,15,10,12,14]
insertionSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i])
Output:
Merge Sort:
defmergeSort(arr):
if len(arr) >1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i <len(L) and j <len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
29
arr[k] = R[j]
j += 1
k += 1
while i <len(L):
arr[k] = L[i]
i += 1
k += 1
while j <len(R):
arr[k] = R[j]
j += 1
k += 1
defprintList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
if __name__ == '__main__':
arr = [16,19,10,15,14,11,12]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
Output:
30
Experiment -5
Write Python program
a. Implement python script to show the usage of various operators available in python language.
Program:
Arithmetic Operation:
x = 15
y = 4
print('x=',x,'y=',y)
print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison Operator:
x = 10
y = 12
print('x=',x,'y=',y)
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Output:
Logical Operator:
x = True
y = False
print('x=',x,'y=',y)
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
31
Experiment -5
b. Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs.12.00 per
hour for every hour worked above 40 hours. Assume that employee do not work for fractional part of an
hour.
Program:
overtime_pay = 0
for i in range(10) :
print("Enter the time employee worked in hr ")
time_worked = int(input())
if (time_worked>40):
over_time = time_worked - 40
overtime_pay = overtime_pay + (12 * over_time)
print("\nTotal Overtime Pay Of 10 Employees Is ", overtime_pay)
Output:
32
Experiment -6
Description:Pandas is one of the most widely used python libraries in data science. It provides high-
performance, easy to use structures and data analysis tools. Unlike NumPy library which provides objects for
multi-dimensional arrays, Pandas provides in-memory 2d table object called Dataframe. It is like a
spreadsheet with column names and row labels.
Hence, with 2d tables, pandas is capable of providing many additional functionalities like creating pivot
tables, computing columns based on other columns and plotting graphs. Pandas can be imported into Python
using:
Pandasdataframe object represents a spreadsheet with cell values, column names, and row index labels.
Dataframe can be visualized as dictionaries of Series. Dataframe rows and columns are simple and intuitive
to access. Pandas also provide SQL-like functionality to filter, sort rows based on conditions.
Program:
import pandas as pd
importnumpy as np
df = pd.DataFrame(exam_data , index=labels)
print(df)
Output:
33
Experiment -6
Program:
import numpy
firstArray = numpy.empty([4,2], dtype= numpy.uint16)
print("Printing Array")
print(firstArray)
print("Printing numpy array Attributes")
print("1> Array Shape is: ", firstArray.shape)
print("2>. Array dimensions are ", firstArray.ndim)
print("3>. Length of each element of array in bytes is ", firstArray.itemsize)
Output:
Experiment -6
c. For the given numpy array return array of odd rows and even columns.
Program :
import numpy
sampleArray = numpy.array([[3 ,6, 9, 12], [15 ,18, 21, 24],
[27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
print("Printing Input Array")
print(sampleArray)
print("\n Printing array of odd rows and even columns")
newArray = sampleArray[::2, 1::2]
print(newArray)
34
Output:
Experiment -6
d. To add the two NumPy arrays and modify a result array by calculating the square root ofeach element.
Program :
import numpy
arrayOne = numpy.array([[5, 6, 9], [21 ,18, 27]])
arrayTwo = numpy.array([[15 ,33, 24], [4 ,7, 1]])
resultArray = arrayOne + arrayTwo
print("addition of two arrays is \n")
print(resultArray)
for numin numpy.nditer(resultArray, op_flags= ['readwrite']):
num[...] = num*num
print("\nResult array after calculating the square root of all elements\n")
print(resultArray)
Output:
35
Experiment -7
Write python program to show following plots using Matplotlib library.[ General case study]
a. To read total profit of all months and show it using a line plot where x axis should be month number
and y axis should be named as total profit.
Description:Matplotlib is a 2d plotting library which produces publication quality figures in a variety of
hardcopy formats and interactive environments. Matplotlib can be used in Python scripts, Python and IPython
shell, Jupyter Notebook, web application servers and GUI toolkits.
matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB. Majority of plotting
commands in pyplot have MATLAB analogs with similar arguments.
Program :
import pandas as pd
importmatplotlib.pyplot as plt
df = pd.read_csv("D:\\Python\\Articles\\matplotlib\\sales_data.csv")
profitList = df ['total_profit'].tolist()
monthList =df ['month_number'].tolist()
plt.plot(monthList, profitList, label = 'Month-wise Profit data of last year')
plt.xlabel('Month number')
plt.ylabel('Profit in dollar')
plt.xticks(monthList)
plt.title('Company profit per month')
plt.yticks([100000, 200000, 300000, 400000, 500000])
plt.show()
Output:
36
Experiment -7
b. To get total profit of all months and show line plot with the following style properties
Line Style dotted and Line-color should be red
Show legend at the lower right location.
X label name = Month Number
Y label name = Sold units number
Add a circle marker.
Line marker color as read
Line width should be 3.
Program :
import pandas as pd
import matplotlib.pyplotas plt
df = pd.read_csv("D:\\Python\\Articles\\matplotlib\\sales_data.csv")
monthList = df ['month_number'].tolist()
faceCremSalesData = df ['facecream'].tolist()
faceWashSalesData = df ['facewash'].tolist()
toothPasteSalesData = df ['toothpaste'].tolist()
bathingsoapSalesData = df ['bathingsoap'].tolist()
shampooSalesData = df ['shampoo'].tolist()
moisturizerSalesData = df ['moisturizer'].tolist()
plt.plot(monthList, faceCremSalesData, label = 'Face cream Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, faceWashSalesData, label = 'Face Wash Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, toothPasteSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, bathingsoapSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, shampooSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.plot(monthList, moisturizerSalesData, label = 'ToothPaste Sales Data', marker='o',
linewidth=3)
plt.xlabel('Month Number')
plt.ylabel('Sales units in number')
plt.legend(loc='upper left')
plt.xticks(monthList)
plt.yticks([1000, 2000, 4000, 6000, 8000, 10000, 12000, 15000, 18000])
plt.title('Sales data')
plt.show()
Output:
37
Experiment -8
a) Draw the target symbol (a set of concentric squares, alternating red and white) in a graphics window, that is, 200
pixels wide by 200 pixels high. (Hint: Draw the target square first in red, followed by next smaller square in
white, then draw the next smaller square in red).
Program:
import matplotlib.pyplot as plt
plt.axes
rectangle=plt.Rectangle((0,0),200,200,fc='red')
plt.gca().add_patch(rectangle)
rectangle=plt.Rectangle((50,50),100,100,fc='white')
plt.gca().add_patch(rectangle)
rectangle=plt.Rectangle((75,75),50,50,fc='red')
plt.gca().add_patch(rectangle)
plt.axis("scaled")
plt.show()
output:
38
Experiment -8
Create a 5x5 rectangle whose top left corner is at (row*5, col*5). If the sum of the rows and columns’ number is even, set the
fill color of the rectangle to white, otherwise set it to the black. Then draw the rectangle.
Program:
from matplotlib import pyplot as plot
plt.figure()
plt.axis([0,25,25,0])
currentAxis=plt.gca()
for i in range(0,5):
for j in range(0,5):
if((i+j)%2==0):
currentAxis.add_patch(plt.Rectangle((i*5,j*5),5,5,color='white'))
else:
currentAxis.add_patch(plt.Rectangle((i*5,j*5),5,5,color='black'))
plt.show()
output:
39
Experiment -9
Cryptography algorithms with python programming – I
Caesar Cipher Technique is the simple and easy method of encryption technique.
It is simple type of substitution cipher.
Each letter of plain text is replaced by a letter with some fixed number of positions down with
alphabet.
The following diagram depicts the working of Caesar cipher algorithm implementation −
Program:
def encrypt(text,s):
result = " "
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
41
B. Write a python program to decrypt a message encrypted using Caesar cipher method.
The cipher text can be hacked with various possibilities. One of such possibility is Brute Force
Technique, which involves trying every possible decryption key. This technique does not demand
much effort and is relatively simple for a hacker.
The program implementation for hacking Caesar cipher algorithm is as follows −
Program
Output
42
C. Write a python program to hack Caesar cipher symmetric encryption method using brute force
technique.
Encryption code:
OUTPUT
43
Decryption
OUTPUT
D. Write a python program to implement XOR algorithm for encryption and decryption of an input
message.
Description
XOR algorithm of encryption and decryption converts the plain text in the format ASCII bytes and uses XOR
procedure to convert it to a specified byte. It offers the following advantages to its users −
Fast computation
No difference marked in left and right side
Easy to understand and analyze
44
Output
45
Experiment - 10
Cryptography algorithms with python programming– II
Transposition Cipher is a cryptographic algorithm where the order of alphabets in the plaintext is rearranged
to form a cipher text. In this process, the actual plain text alphabets are not included.
Example - A simple example for a transposition cipher is columnar transposition cipher where each
character in the plain text is written horizontally with specified alphabet width. The cipher is written
vertically, which creates an entirely different cipher text.
Consider the plain text hello world, and let us apply the simple columnar transposition technique as shown
below
The plain text characters are placed horizontally and the cipher text is created with vertical format as :
holewdlo lr. Now, the receiver has to use the same table to decrypt the cipher text to plain text.
Program
import math
def encrypt(key, message):
# Simulates columns in the matrix by using string array.
ciphertext = [''] * key
# Iterates through each column in the ciphertext.
for column in range(key):
index = column
# Iterates until the plaintext end.
while index < len(message):
# Places the character at the end of the column:
ciphertext[column] += message[index]
# Moves the index to the next symbol.
index += key
46
def decrypt(key, message):
# Calculates the matrix dimensions: how many rows and columns
# - we need this for position tracking.
nrows = key
ncols = math.ceil(len(message) / key)
47
message = 'Here is our first message!'
key = 6
ciphertext = encrypt(key, message)
# Delimits the ciphertext for displaying purposes, i.e. to show
# a <space> symbol if there is one at the end.
print(f'Ciphertext: {ciphertext}<end>')
# Prints the plaintext for algorithm validity checking.
plaintext = decrypt(key, ciphertext)
print(f'Plaintext: {plaintext}')
OUTPUT
B. Write a python program to decrypt a message encrypted using transposition cipher method.
Program:
Output:
Program:
# Transposition Cipher Decryption
import math, pyperclip
48
def main():
myMessage = 'Cenoonommstmme oo snnio. s s c'
myKey = 8
plaintext = decryptMessage(myKey, myMessage)
print(plaintext + '|')
pyperclip.copy(plaintext)
def decryptMessage(key, message):
# The transposition decrypt function will simulate the "columns" and
# "rows" of the grid that the plaintext is written on by using a list
# of strings. First, we need to calculate a few values.
# The number of "columns" in our transposition grid:
numOfColumns = math.ceil(len(message) / key)
# The number of "rows" in our grid will need:
numOfRows = key
# The number of "shaded boxes" in the last "column" of the grid:
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
# Each string in plaintext represents a column in the grid.
plaintext = [''] * numOfColumns
# The col and row variables point to where in the grid the next
# character in the encrypted message will go.
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1 # point to next column
# If there are no more columns OR we're at a shaded box, go back to
# the first column and the next row.
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows -
numOfShadedBoxes):
col = 0
row += 1
return ''.join(plaintext)
# If transpositionDecrypt.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
49
Output:
50
51