Question Bank With Solution1
Question Bank With Solution1
Solution:-
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))
Output: 20
Solution:-
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('1234abcd'))
Output: dcba4321
Page 1
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print("The number is outside the given range.")
test_range(5)
4. Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.
String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12
Solution:-
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])
string_test('The quick Brown Fox')
Output:
Original String : The quick Brow Fox
No. of Upper case characters : 3
No. of Lower case Characters : 13
5. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
Page 2
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution:-
def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,3,3,3,3,4,5]))
Output: [1, 2, 3, 4, 5]
6. Write a Python function that takes a number as a parameter and check the
number is prime or not.
Note: A prime number (or a prime) is a natural number greater than 1 and
that has no positive divisors other than 1 and itself.
Solution:-
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))
Output: False
7. Write a Python program to print the even numbers from a given list.
List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
Solution:-
def is_even_num(l):
enum = []
for n in l:
Page 3
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
Output: [2, 4, 6, 8]
Solution:-
def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(6))
Output: True
Solution:-
def isPalindrome(string):
left_pos = 0
right_pos = len(string) - 1
while right_pos >= left_pos:
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
print(isPalindrome('aza'))
Output: True
Page 4
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
10. Write a Python function that prints out the first n rows of Pascal's triangle.
Note: Pascal's triangle is an arithmetic and geometric figure first imagined by
Blaise Pascal.
Pascal's triangle:
Solution:-
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(n):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
Output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
print ( ispangram('The quick brown fox jumps over the lazy dog'))
Output: True
Solution:-
items=[n for n in input().split('-')]
items.sort()
print('-'.join(items))
Output:
green-red-black-white
black-green-red-white
13. Write a Python function to create and print a list where the values are square of
numbers between 1 and 30 (both included).
Solution:-
def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l)
printValues()
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
Page 6
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
14. Write a Python program to make a chain of function decorators (bold, italic,
underline etc.) in Python.
Solution:-
def make_bold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def make_italic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
def make_underline(fn):
def wrapped():
return "<u>" + fn() + "</u>"
return wrapped
@make_bold
@make_italic
@make_underline
def hello():
return "hello world"
print(hello()) ## returns "<b><i><u>hello world</u></i></b>"
Solution:-
mycode = 'print("hello world")'
code = """
def mutiply(x,y):
return x*y
print('Multiply of 2 and 3 is: ',mutiply(2,3))
"""
exec(mycode)
exec(code)
Output:
hello world
Page 7
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
16. Write a Python program to access a function inside a function.
Solution:-
def test(a):
def add(b):
nonlocal a
a += 1
return a+b
return add
func= test(4)
print(func(4))
Output: 9
17. Write a Python program to detect the number of local variables declared in a
function
Solution:-
def abc():
x=1
y=2
str1= "w3resource"
print("Python Exercises")
print(abc.__code__.co_nlocals)
Output: 3
Page 8
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Recursive Functions
1. Write a Python program to calculate the sum of a list of numbers.
Solution:-
def list_sum(num_List):
if len(num_List) == 1:
return num_List[0]
else:
return num_List[0] + list_sum(num_List[1:])
print(list_sum([2, 4, 5, 6, 7]))
Output: 24
Solution:-
def to_string(n,base):
conver_tString = "0123456789ABCDEF"
if n < base:
return conver_tString[n]
else:
return to_string(n//base,base) + conver_tString[n % base]
print(to_string(2835,16))
Output: B13
Solution:
def recursive_list_sum(data_list):
total = 0
for element in data_list:
if type(element) == type([]):
total = total + recursive_list_sum(element)
else:
total = total + element
Page 9
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
return total
print( recursive_list_sum([1, 2, [3,4],[5,6]]))
Output: 21
Solution:
def factorial(n):
if n <= 1:
return 1
else:
return n * (factorial(n - 1))
print(factorial(5))
Output: 120
Solution:
def fibonacci(n):
if n == 1 or n == 2:
return 1
else:
return (fibonacci(n - 1) + (fibonacci(n - 2)))
n=int(input("Enter the no of terms"))
for i in range (1,n):
print(fibonacci(7))
Output: 13
Solution:
def sumDigits(n):
if n == 0:
return 0
Page 10
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
else:
return n % 10 + sumDigits(int(n / 10))
print(sumDigits(345))
print(sumDigits(45))
Output:
12
9
7. Write a Python program to calculate the sum of the positive integers of n+(n-
2)+(n-4)... (until n-x =< 0).
Solution:
def sum_series(n):
if n < 1:
return 0
else:
return n + sum_series(n - 2)
print(sum_series(6))
print(sum_series(10))
Output:
12
30
Example:
Solution:-
def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))
Page 11
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print(harmonic_sum(7))
print(harmonic_sum(4))
Output:
2.5928571428571425
2.083333333333333
Example :
Solution:-
def geometric_sum(n):
if n < 0:
return 0
else:
return 1 / (pow(2, n)) + geometric_sum(n - 1)
print(geometric_sum(7))
print(geometric_sum(4))
Output:
1.9921875
1.9375
10. Write a Python program to calculate the value of 'a' to the power 'b'.
Solution:-
def power(a,b):
if b==0:
return 1
elif a==0:
return 0
Page 12
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
elif b==1:
return a
else:
return a*power(a,b-1)
print(power(3,4))
Output: 81
11. Write a Python program to find the greatest common divisor (gcd) of two
integers.
Solution:-
def Recurgcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return Recurgcd(low, high%low)
print(Recurgcd(12,14))
Output: 2
Page 13
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
File Handling
1. Write a Python program to read first n lines of a file.
Solution:
def file_read_from_head(fname, nlines):
from itertools import islice
with open(fname) as f:
for line in islice(f, nlines):
print(line)
file_read_from_head('test.txt',2)
file_read('test.txt')
3. Write a Python program to append text to a file and display the text.
Solution:-
def file_read(fname):
from itertools import islice
with open(fname, "w") as myfile:
myfile.write("Python Exercises\n")
myfile.write("Java Exercises")
txt = open(fname)
print(txt.read())
file_read('abc.txt')
Page 14
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
iter = 0
with open(fname) as f:
if bufsize > fsize:
bufsize = fsize-1
data = []
while True:
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
if len(data) >= lines or f.tell() == 0:
print(''.join(data[-lines:]))
break
file_read_from_tail('test.txt',2)
5. Write a Python program to read a file line by line and store it into a list.
Solution:-
def file_read(fname):
with open(fname) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
print(content_list)
file_read(\'test.txt\')
6. Write a Python program to read a file line by line store it into a variable.
Solution:-
def file_read(fname):
with open (fname, "r") as myfile:
data=myfile.readlines()
print(data)
file_read('test.txt')
Page 15
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print(longest_word('test.txt'))
8. Write a Python program to read a file line by line store it into an array.
Solution:-
def file_read(fname):
content_array = []
with open(fname) as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
print(content_array)
file_read('test.txt')
11. Write a Python program to combine each line from first file with the
corresponding line in second file.
Solution:-
with open('abc.txt') as fh1, open('test.txt') as fh2:
for line1, line2 in zip(fh1, fh2):
# line1 from abc.txt, line2 from test.txtg
print(line1+line2)
Page 16
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
12. Write a Python program to get the file size of a plain file.
Solution:-
def file_size(fname):
import os
statinfo = os.stat(fname)
return statinfo.st_size
content = open('abc.txt')
print(content.read())
Page 17
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
17. Write a Python program to remove newline characters from a file.
Solution:
def remove_newlines(fname):
flist = open(fname).readlines()
return [s.rstrip('\n') for s in flist]
print(remove_newlines("test.txt"))
18. Write a Python program that takes a text file as input and returns the number of
words of a given text file.
Note: Some words can be separated by a comma with no space.
Solution:
def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt"))
19. Write a Python program to extract characters from various text files and puts
them into a list.
Solution:
import glob
char_list = []
files_list = glob.glob("*.txt")
for file_elem in files_list:
with open(file_elem, "r") as f:
char_list.append(f.read())
print(char_list)
20. Write a Python program to generate 26 text files named A.txt, B.txt, and so on up
to Z.txt.
Solution:
import string, os
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_uppercase:
with open(letter + ".txt", "w") as f:
f.writelines(letter)
Page 18
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
21. Write a Python program to create a file where all letters of English alphabet are
listed by specified number of letters on each line.
Solution:
import string
def letters_file_line(n):
with open("words1.txt", "w") as f:
alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet), n)]
f.writelines(letters)
letters_file_line(3)
Page 19
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Arrays and Data Structures
1. Write a Python program to create an array of 5 integers and display the array
items. Access individual element through indexes.
Solution:
from array import *
array_num = array('i', [1,3,5,7,9])
for i in array_num:
print(i)
print("Access first three items individually")
print(array_num[0])
print(array_num[1])
print(array_num[2])
2. Write a Python program to append a new item to the end of the array.
Solution:
from array import *
array_num = array('i', [1, 3, 5, 7, 9])
print("Original array: "+str(array_num))
print("Append 11 at the end of the array:")
array_num.append(11)
print("New array: "+str(array_num))
Output:
Original array: array('i', [1, 3, 5, 7, 9])
Append 11 at the end of the array:
New array: array('i', [1, 3, 5, 7, 9, 11])
3. Write a Python program which takes two digits m (row) and n (column) as input
and generates a two-dimensional array. The element value in the i-th row and j-th
column of the array should be i*j.
Note :
i = 0,1.., m-1
j = 0,1, n-1.
Page 20
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution:
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
print(multi_list)
Output:
Input number of rows: 3
Input number of columns: 4
[[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6]]
Approach #1: Find the length of the list and simply swap the first element with
(n-1)th element.
# Python3 program to swap first
# and last element of a list
# Swap function
def swapList(newList):
size = len(newList)
# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp
return newList
# Driver code
newList = [12, 35, 9, 56, 24]
print(swapList(newList))
Page 21
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
5. Write a Python program to remove Nth occurrence of the given word
Given a list of words in Python, the task is to remove the Nth occurrence of the given
word in that list.
Examples:
Input: list - ["geeks", "for", "geeks"]
word = geeks, N = 2
Output: list - ["geeks", "for"]
Input: list - ["can", "you", "can", "a", "can" "?"]
word = can, N = 1
Output: list - ["you", "can", "a", "can" "?"]
Make a new list, say newList. Iterate the elements in the list and check if the word to
be removed matches the element and the occurrence number, otherwise, append
the element to newList.
Page 22
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# Driver code
list = ["geeks", "for", "geeks"]
word = "geeks"
N=2
RemoveIthWord(list, word, N)
Output :
Updated list is: ['geeks', 'for']
Page 23
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
li_= li1[:]
return li_
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Page 24
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
def Cloning(li1):
li_= list(li1)
return li_
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Page 25
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
return li_
# Driver Code
li1 = [4, 8, 2, 10, 15, 18]
li2 = Cloning(li1)
print("Original List:", li1)
print("After Cloning:", li2)
Output:
Original List: [4, 8, 2, 10, 15, 18]
After Cloning: [4, 8, 2, 10, 15, 18]
Page 27
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# driver program
x=3
d = Counter(l)
print('{} has occurred {} times'.format(x, d[x]))
Output:
3 has occurred 2 times
Examples :
Input : [4, 5, 1, 2, 9]
N=2
Output : [9, 5]
A simple solution traverse the given list N times. In every traversal, find the
maximum, add it to result, and remove it from the list. Below is the
implementation:
list1.remove(max1);
Page 28
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
final_list.append(max1)
print(final_list)
# Driver code
list1 = [2, 6, 41, 85, 0, 3, 7, 6, 10]
N=2
# Calling the function
Nmaxelements(list1, N)
Output: [85, 41]
Example:
Input: list1 = [12, -7, 5, 64, -14]
Output: 12, 5, 64
Example #1: Print all positive numbers from given list using for loop
Iterate each element in the list using for loop and check if number is greater than or
equal to 0. If the condition satisfies, then only print the number.
# Python program to print positive Numbers in a List
# list of numbers
list1 = [11, -21, 0, 45, 66, -93]
Page 29
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Example #2: Using while loop
# Python program to print positive Numbers in a List
# list of numbers
list1 = [-10, 21, -4, -45, -66, 93]
num = 0
# using while loop
while(num < len(list1)):
# checking condition
if list1[num] >= 0:
print(list1[num], end = " ")
# increment num
num += 1
Output: 21, 93
Example:
Input: list1 = [12, -7, 5, 64, -14]
Output: -7, -14
Input: list2 = [12, 14, -95, 3]
Output: -95
Example #1: Print all negative numbers from given list using for loop
Iterate each element in the list using for loop and check if number is less than 0. If
the condition satisfies, then only print the number.
# Python program to print negative Numbers in a List
# list of numbers
list1 = [11, -21, 0, 45, 66, -93]
# iterating each number in list
for num in list1:
# checking condition
if num < 0:
print(num, end = " ")
Output: -21, -93
Page 30
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Example #2: Using while loop
# Python program to print negative Numbers in a List
# list of numbers
list1 = [-10, 21, -4, -45, -66, 93]
num = 0
# using while loop
while(num < len(list1)):
# checking condition
if list1[num] < 0:
print(list1[num], end = " ")
# increment num
num += 1
Example:
Input: list1 = [2, -7, 5, -64, -14]
Output: pos = 2, neg = 3
Input: list2 = [-12, 14, 95, 3]
Output: pos = 3, neg = 1
Example #1: Count positive and negative numbers from given list using for loop
Iterate each element in the list using for loop and check if num >= 0, the condition
to check positive numbers. If the condition satisfies, then increase pos_count else
# Python program to count positive and negative numbers in a List
# list of numbers
list1 = [10, -21, 4, -45, 66, -93, 1]
pos_count, neg_count = 0, 0
# iterating each number in list
for num in list1:
# checking condition
if num >= 0:
pos_count += 1
Page 31
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
else:
neg_count += 1
print("Positive numbers in the list: ", pos_count)
print("Negative numbers in the list: ", neg_count)
Output:
Positive numbers in the list: 4
Negative numbers in the list: 3
13. Write a program in Python to Remove multiple elements from a list in Python
Given a list of numbers, write a Python program to remove multiple elements from
a list based on the given condition.
Example:
Input: [12, 15, 3, 10]
Output: Remove = [12, 3], New_List = [15, 10]
Input: [11, 5, 17, 18, 23, 50]
Output: Remove = [1:5], New_list = [11, 50]
Page 32
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Multiple elements can be deleted from a list in Python, based on the knowledge we
have about the data. Like, we just know the values to be deleted or also know the
indexes of those values. Let’s see different examples based on different scenario.
Example #1: Let’s say we want to delete each element in the list which is divisible
by 2 or all the even numbers.
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# Iterate each element in list
# and add them in variale total
for ele in list1:
if ele % 2 == 0:
list1.remove(ele)
# printing modified list
print("New list after removing all even numbers: ", list1)
Output:
New list after removing all even numbers: [11, 5, 17, 23]
Page 33
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# removes elements from index 1 to 4
# i.e. 5, 17, 18, 23 will be deleted
del list1[1:5]
print(*list1)
Output:
11 50
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
50, -20, 60, 60, -20, -20]
print (Repeat(list1))
Page 34
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# This code is contributed
# by Sandeep_anand
Output: [20, 30, -20, 60]
15. Write a program in Python to Break a list into chunks of size N in Python
Using yield
The yield keyword enables a function to comeback where it left off when it is called
again. This is the critical difference from a regular function. A regular function
cannot comes back where it left off. The yield keyword helps a function to
remember its state. The yield enables a function to suspend and resume while it
turns in a value at the time of the suspension of the execution.
my_list =['geeks', 'for', 'geeks', 'like', 'geeky','nerdy', 'geek', 'love', 'questions','words' ,'life']
Approach:
An array is monotonic if and only if it is monotone increasing, or monotone
decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent
elements to determine if the array is monotone increasing (or decreasing), respectively.
We can check each of these properties in one pass.
To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i
indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i]
>= A[i+1] for all i indexing from 0 to len(A)-2.
Note: Array with single element can be considered to be both monotonic increasing or
decreasing, hence returns “True“.
Below is the implementation of above approach:
# Python program to find sum in Nth group
# Check if given array is Monotonic
def isMonotonic(A):
return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or
all(A[i] >= A[i + 1] for i in range(len(A) - 1)))
# Driver program
A = [6, 5, 4, 4]
# Print required result
print(isMonotonic(A))
# This code is written by
# Sanjit_Prasad
Output: True
17. Write a Python Program to Split the array and add the first part to the end.
There is a given an array and split it from a specified position, and move the first
part of array add to the end.
Examples:
Input : arr[] = {12, 10, 5, 6, 52, 36}
k=2
Output : arr[] = {5, 6, 52, 36, 12, 10}
Page 36
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Explanation : Split from index 2 and first
part {12, 10} add to the end .
Input : arr[] = {3, 1, 2}
k=1
Output : arr[] = {1, 2, 3}
Explanation : Split from index 1 and first part add to the end.
# Python program to split array and move first
# part to end.
def splitArr(arr, n, k):
for i in range(0, k):
x = arr[0]
for j in range(0, n-1):
arr[j] = arr[j + 1]
arr[n-1] = x
# main
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 2
splitArr(arr, n, position)
for i in range(0, n):
print(arr[i], end = ' ')
Output: 5, 6, 52, 36, 12, 10
Another Solution:
# Python program to split array and move first
# part to end.
Page 37
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print(arr[i], end = ' ')
Output:
5 6 52 36 12 10
18. Write a program to create and input the elements of M*N matrix and print it in
proper format.
Solution:-
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
print("The matrix you have entered:")
print()
for i in range(r):
for j in range(c):
print(a[i][j],end=" ")
print()
19. Write a program to create and input 2-D matrix of size M*N and perform the
following operations on the matrix.
a) To print the sum and average of the elements exist in matrix.
b) To print the elements which are above than average?
c) To print the total no. of elements which are above than average?
d) To print the largest element in the matrix.
e) To print the smallest element in the matrix.
f) To print the second largest element in the matrix.
g) To print the second smallest element in the matrix.
h) To print the even elements exist in matrix.
i) To print the odd elements exist in matrix.
j) To print the total no. of even elements exist in matrix.
k) To print the total no. of odd elements exist in matrix.
Page 38
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
l) To print the elements which are divisible by both 5 and 7 in the matrix?
m) To print the total no. of elements which are divisible by both 5 and 7 in the
matrix?
Solution:-
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
s=0
t=0
for i in range(len(a)):
for j in range(len(a[i])):
s=s+a[i][j]
avg=s/(r*c)
print()
print("The sum of elements:",s)
print("The Average of elements:",avg)
print()
print("Elements which are above than average are:")
for i in range(len(a)):
for j in range(len(a[i])):
if a[i][j]>avg:
t=t+1
print(a[i][j],end=",")
print()
print("Total Elements which are above than average are:")
print(t)
max=0
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]>max):
max=a[i][j]
Page 39
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print("\nThe largest element:",max)
min=100000
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]<min):
min=a[i][j]
print("\nThe smallest element:",min)
smax=1
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]>smax and a[i][j]!=max):
smax=a[i][j]
print("\nThe second largest element:",smax)
smin=9999
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]<smin and a[i][j]!=min):
smin=a[i][j]
print("\nThe second smallest element:",smin)
t1=0
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]%2==0):
t1=t1+1
print("\nEven Elements:",a[i][j],end=",")
print("\nTotal Even Elements:",t1)
t2=0
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]%2!=0):
t2=t2+1
print("\nOdd elements:",a[i][j],end=",")
print("\nTotal Odd Elements:",t2)
for i in range(len(a)):
for j in range(len(a[i])):
if(a[i][j]%5==0 or a[i][j]%7==0):
print("\nThe elements divisible by 5 or 7 are:",a[i][j],end=",")
Page 40
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
20. Write a user defined function in Python which takes two M*N matrix and its size
as argument and print the print the addition of them.
Solution:-
def Add_Mat(a,b,r,c):
import numpy as np
c=np.zeros((r,c))
for i in range(len(a)):
for j in range(len(a[i])):
c[i][j]=a[i][j]+b[i][j]
for i in range(len(a)):
for j in range(len(a[i])):
print(c[i][j],end=" ")
print()
def Sub_Mat(a,b,r,c):
import numpy as np
c=np.zeros((r,c))
for i in range(len(a)):
for j in range(len(a[i])):
c[i][j]=a[i][j]-b[i][j]
for i in range(len(a)):
for j in range(len(a[i])):
print(c[i][j],end=" ")
print()
a=[[]]
b=[[]]
c=[[]]
print("Enter the details for first matrix")
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
print("Enter the details for second matrix")
r=int(input("Enter Rows:"))
Page 41
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
c=int(input("Enter Columns:"))
for i in range(r):
b.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
b[i].append(num)
print("\nAddition of Matrix:")
Add_Mat(a,b,r,c)
print("\nSubtraction of Matrix:")
Sub_Mat(a,b,r,c)
21. Write a user defined function Lower_half() which takes a two dimensional array
A with size N rows and N columns as argument and print the lower half of the
array
2 3 1 5 0 2
7 1 5 3 0 7 1
2 5 7 8 1 2 5 7
0 1 5 0 1 0 1 5 0
3 4 9 1 5 3 4 9 1 5
Solution:-
def Lower_Half(a):
for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j],end=" ")
if j>=i:
break
print()
#Driver Code
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
Page 42
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
print("The matrix you have entered:")
print()
for i in range(r):
for j in range(c):
print(a[i][j],end=" ")
print()
print("Lower half of the given array\n")
Lower_Half(a)
22. Write a function in Python to find and display the sum of each row and each
column of a 2-D array of type float. Use the array and its size as parameters with
float as its return type.
Solution:-
def RowCol_Sum(a):
for i in range(len(a)):
rsum=0
for j in range(len(a[i])):
rsum=rsum+a[i][j]
print("Sum of",i+1,"row:",rsum)
print()
for i in range(len(a)):
csum=0
for j in range(len(a[i])):
csum=csum+a[j][i]
print("Sum of",i+1,"column:",csum)
print()
#Driver Code
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
Page 43
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
RowCol_Sum(a)
23. Write a function in Python to find the sum of diagonal elements from a 2-D array
of type float. Use the array and its size as parameters with float as return type.
Solution:-
def Diagonal_Sum(a,r,c):
s1=0
s2=0
for i in range(0,r):
for j in range(0,c):
if(i==j):
s1=s1+a[i][j]
if((i+j)==(c-1)):
s2=s2+a[i][j]
print("Sum of first diagonal:",s1)
print("Sum of second diagonal:",s2)
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
Diagonal_Sum(a,r,c)
Or
def Diagonal_Sum(a,n):
s1=0
s2=0
Page 44
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
for i in range(0,n):
s1=s1+a[i][i]
s2=s2+a[i][n-1-i]
print("Sum of first diagonal:",s1)
print("Sum of second diagonal:",s2)
a=[[]]
n=int(input("Enter Rows and columns:"))
for i in range(n):
a.append([])
for i in range(n):
print("Enter the elements for row",i+1)
for j in range(n):
num=int(input("Enter elements"))
a[i].append(num)
print("The matrix you have entered:")
print()
for i in range(n):
for j in range(n):
print(a[i][j],end=" ")
print()
Diagonal_Sum(a,n)
24. Write a function in Python, which accepts a 2-D array of integers and its size as
its arguments and display the elements of the middle row and the elements of
middle column.
Solution:-
def MiddleRowCol_Elem(a,r,c):
print("Elements of Middle Row:")
for i in range(r):
print(a[r//2][i],end=" ")
print()
print("Elements of Middle Column:")
for i in range(r):
print(a[i][r//2],end=" ")
#Driver Code
a=[[]]
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
Page 45
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
MiddleRowCol_Elem(a,r,c)
-5 -15 -7 -8 3 1 3 7 -7 3
Solution:-
def swap(A,N):
for i in range(N):
if(A[i]<0):
temp=A[i]
j=i-1
while(A[j]>=0 and j>=0):
A[j+1]=A[j]
j=j-1
A[j+1]=temp
#Driver program starts here
A=[]
N=int(input("Enter the size of array"))
print("Enter elements")
for i in range(N):
val=int(input())
A.append(val)
swap(A,N)
print("Resultant Array:\n")
for i in range(N):
print(A[i], end=",")
Page 46
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
26. Suppose A, B, C are arrays of integers of size M, N and M+N respectively. The
numbers in array A appear in ascending order while the numbers in array B
appear in descending order. Write a user defined function in Python to produce
third array C by merging array A and B in ascending order. Use A, B and C as
arguments in the function.
Solution:-
def MergeSort(A,B,C,m,n):
a=0
b=0
c=0
while(a<m and b<n):
if(A[a]<=B[b]):
C.append(A[a])
a=a+1
else:
C.append(B[b])
b=b+1
while(a<m):
C.append(A[a])
a=a+1
while(b<n):
C.append(B[b])
b=b+1
#Driver Code
A=[]
B=[]
C=[]
m=int(input("Enter the size of first array:"))
print("Enter elements:")
for i in range(m):
v1=int(input())
A.append(v1)
n=int(input("Enter the size of second array:"))
print("Enter elements:")
for j in range(n):
v2=int(input())
Page 47
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
B.append(v2)
A.sort()
B.sort()
MergeSort(A,B,C,m,n)
print("Merged Array:\n")
for k in range(m+n):
print(C[k],end=",")
27. Suppose X, Y, Z are arrays of integers of size M, N and M+N respectively. The
numbers in array X and Y appear in descending order. Write a user defined
function in Python to produce third array Z by merging array X and Y in
ascending order. Use X, Y and Z as arguments in the function.
Solution:-
Step1:- Define the Merge Sort Function.
Step2:- In the driver program, declare three arrays.
Step3:- Input the size of first, second array.
Step4:- Inter the elements of first array and second array.
Step5:- Sort both the arrays in descending order by using any sorting technique.
Step6:- Call the Merge Sort Function.
Step7:- Print the final (Resultant) array.
28. Define a function Reversearray (int [ ], int) that would accept a 1-D integer array
NUMBERS and its size N. the function should reverse the contexts of the array
neither without using any second array nor using the built-in method.
Solution:-
def ReverseArray(A,N):
beg=0
end=N-1
while(beg<end):
temp=A[beg]
Page 48
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
A[beg]=A[end]
A[end]=temp
beg=beg+1
end=end-1
#Driver Program
A=[]
N=int(input("Enter the size of array"))
print("Enter elements")
for i in range(N):
val=int(input())
A.append(val)
ReverseArray(A,N)
print("Resultant Array:\n")
for i in range(N):
print(A[i], end=",")
29. Define a function Swapearray (int [ ], int) that would accept a 1-D integer array
NUMBERS and its size N. the function should rearrange the array in such a way
that the value of alternate location of the array are exchange (assume the size of
array to be even).
Exp: if the array initially contains
[2, 5, 9, 14, 17, 8, 9, 16]
Then after rearranging the array should contains:
[5, 2, 14, 9, 8, 17, 16, 9]
Solution:-
def swap(A,N):
i=0
while(i<N-1):
temp=A[i]
A[i]=A[i+1]
A[i+1]=temp
i=i+2
#Driver Program
A=[]
N=int(input("Enter the size of array"))
print("Enter elements")
for i in range(N):
val=int(input())
Page 49
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
A.append(val)
swap(A,N)
print("Resultant Array:\n")
for i in range(N):
print(A[i], end=",")
30. Write a function Findsort(), to find whether the given integer array arr[10] is
stored in ascending order or descending order or is not in order. The function
should return A for ascending, D for descending and N for no order.
Solution:-
def FindSort(A,N):
order="N"
for i in range(N-1):
if(A[i]<A[i+1]):
order="A"
else:
order="N"
break
if(order=="A"):
return order
for i in range(N-1):
if(A[i]>A[i+1]):
order="D"
else:
order="N"
break
return order
#Driver Code
a=[]
n=int(input("Enter the size of list:"))
print("Enter elements:")
for i in range(n):
num=int(input())
a.append(num)
Insertion_Sort(a,n)
print("Sorted Array:\n")
for i in range(n):
print(a[i],end=",")
Solution:-
def Bubble_Sort(a,size):
for i in range(size-1):
for j in range(size-1-i):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
Page 51
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
#Driver Code
a=[]
n=int(input("Enter the size of list:"))
print("Enter elements:")
for i in range(n):
num=int(input())
a.append(num)
Bubble_Sort(a,n)
for i in range(n):
print(a[i],end=",")
33. Write a sorting function in Python that takes any array containing N names. Sort
the array using bubble sort.
Solution: - Same as question no. 14
Solution (i):
def Binary_Search(a,n,key):
beg=0
end=n-1
mid=(beg+end//2)
while(beg<end and a[mid]!=key):
if(key<a[mid]):
end=mid-1
else:
beg=mid+1
mid=(beg+end//2)
if(beg>end):
return -1
else:
return mid
#Driver Code
a=[]
n=int(input("Enter the size of list:"))
print("Enter elements:")
for i in range(n):
num=int(input())
a.append(num)
key=int(input("Enter the search item"))
index=Binary_Search(a,n,key)
if(index==-1):
print("Sorry element not found in the list")
else:
print("Element found on index",index)
Page 53
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution (ii):
def Linear_Search(a,n,key):
for i in range(n):
if(a[i]==key):
return i
return -1
a=[]
n=int(input("Enter the size of list:"))
print("Enter elements:")
for i in range(n):
num=int(input())
a.append(num)
key=int(input("Enter the search item"))
index=Linear_Search(a,n,key)
if(index==-1):
print("Sorry element not found in the list")
else:
print("Element found on index",index)
36. Write a Function to print the addition and subtraction of two M*N matrix. The
matrixes and their size should be passed as argument in the function. Also write the
driver program and call the function.
Solution:-
def Add_Mat(a,b,r,c):
import numpy as np
c=np.zeros((r,c))
for i in range(len(a)):
for j in range(len(a[i])):
c[i][j]=a[i][j]+b[i][j]
for i in range(len(a)):
for j in range(len(a[i])):
print(c[i][j],end=" ")
print()
def Sub_Mat(a,b,r,c):
import numpy as np
c=np.zeros((r,c))
for i in range(len(a)):
for j in range(len(a[i])):
Page 54
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
c[i][j]=a[i][j]-b[i][j]
for i in range(len(a)):
for j in range(len(a[i])):
print(c[i][j],end=" ")
print()
a=[[]]
b=[[]]
c=[[]]
print("Enter the details for first matrix")
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
print("Enter the details for second matrix")
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
b.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
b[i].append(num)
print("\nAddition of Matrix:")
Add_Mat(a,b,r,c)
print("\nSubtraction of Matrix:")
Sub_Mat(a,b,r,c)
37. Write a Function to print the product/Multiplication of two M*N matrix. The
matrixes and their size should be passed as argument in the function. Also write the
driver program and call the function.
Page 55
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution:-
def Prod_Mat(a,b,r,c):
p=[[]]
import numpy as np
p=np.zeros((r,c))
for i in range(len(a)):
for j in range(len(a[i])):
for k in range(len(a[i])):
p[i][j]=p[i][j]+a[i][k]*b[k][j]
print("Product of Matrix:")
for i in range(len(p)):
for j in range(len(p[i])):
print(p[i][j],end=" ")
print()
#Driver Code
a=[[]]
b=[[]]
p=[[]]
print("Enter the details for first matrix")
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
a.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
a[i].append(num)
print("Enter the details for second matrix")
r=int(input("Enter Rows:"))
c=int(input("Enter Columns:"))
for i in range(r):
b.append([])
for i in range(r):
print("Enter the elements for row",i+1)
for j in range(c):
num=int(input("Enter elements"))
b[i].append(num)
print("The matrix you have entered:")
Page 56
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
print()
for i in range(r):
for j in range(c):
print(a[i][j],end=" ")
print()
print()
for i in range(r):
for j in range(c):
print(b[i][j],end=" ")
print()
Prod_Mat(a,b,r,c)
38. Write a function in Python to push and pop an element in stack, stores
character data. (Using array implementation)
Solution:-
def IsEmpty():
global Top
if(Top==-1):
stackempty=True
else:
stackempty=False
return stackempty
def IsFull():
global Top
if(Top==Max-1):
stackfull=True
else:
stackfull=False
return stackfull
def Push():
global Top
if(IsFull()==True):
print("Overflow")
else:
item=int(input("Enter item:"))
Stack.append(item)
Page 57
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Top=Top+1
Stack[Top]=item
def Pop():
item=0
global Top
if IsEmpty()==True:
print("Underflow")
else:
item=Top
Top=Top-1
def Traverse():
global Top
if (IsEmpty()==True):
print("Stack is Underflow")
else:
print("Stack Elements are:")
i=Top
while(i>=0):
print(Stack[i])
i=i-1
Max=10
Stack=[Max]
global Top
Top=-1
while True:
print("Stack Operations")
print("Menu Selection")
print("Press 1 for Push")
print("Press 2 for Pop")
print("Press 3 for Display")
print("Press 4 for Exit")
ch=int(input("Enter your choice"))
if ch==1:
Push()
elif ch==2:
Page 58
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Pop()
elif ch==3:
Traverse()
elif ch==4:
break
else:
print("Invalid Choice")
39. Declare a queue using array that contains int type numbers and define insert,
delete, and display function using Python syntax.
Solution:-
def IsEmpty(Q):
global Front
global Rear
if Front==Rear==-1:
return True
else:
return False
def IsFull(Q):
global Front
global Rear
if(Front==0 and Rear==Capacity-1):
return True
else:
return False
def Enqueue(Q,item):
global Front
global Rear
if IsFull(Q)==True:
print("Queue is full")
else:
Rear=Rear+1
Q[Rear]=item
if Rear>Capacity-1:
raise Exception("Cannot be enqued")
Page 59
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
def Dequeue(Q):
item=0
global Front
global Rear
if IsEmpty(Q)==True:
print("Queue is empty")
else:
item=Q[Front]
Q.pop(Front)
Front=Front+1
if Front>Rear:
raise Exception("Nothing to delete")
return item
def Traverse(Q):
global Front
global Rear
if IsEmpty(Q)==True:
print("Queue is empty")
else:
Front=0
Rear=len(Q)-1
print("Queue Elements front-->rear are:")
for i in range(Front,Rear):
print(Q[i],end="-->")
#Driver Code
Capacity=5
Queue=[Capacity]
global Front
global Rear
Front=Rear=-1
while True:
print("\nQueue Operations")
print("Menu Selection")
print("Press 1 for Enqueue")
print("Press 2 for Dequeue")
print("Press 3 for Display")
print("Press 4 for Exit")
Page 60
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
ch=int(input("Enter your choice"))
if ch==1:
item=int(input("Enter item to insert:"))
Queue.append(item)
Enqueue(Queue,item)
elif ch==2:
Dequeue(Queue)
elif ch==3:
Traverse(Queue)
elif ch==4:
break
else:
print("Invalid Choice")
Page 61
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Data Visualization
Introduction to Matplotlib
1. Write a program in Python to create a plot by using functional approach.
Solution:-
#Creating Plot by using Functional Approach
#Importing Matplotlib Library
import matplotlib.pyplot as plt
#Importing Numpy Library for Numpy Array
import numpy as np
#Giving Data Points usint linspace() Method
x=np.linspace(0, 10, 20)
#Generating Array y from square of x
y=x**2
#Establishing Our Plot
plt.plot(x, y)
#Showing Our Plot
plt.show()
#Giving the Title of Plot using title() Method
plt.title("My First Plot")
#Giving name of the x-axis and y-axis
plt.xlabel("X Label")
plt.ylabel("Y Label")
#Showing our Plot
plt.show()
#Creating Sub-Plots using subplot() method
#by giving Number of Rows,number of columns
# and the Plot Number
plt.subplot(1, 2, 1)
#Setting the Color Attribute to Sub-Plots
plt.plot(x, y, "red")
plt.subplot(1, 2, 2)
plt.plot(y, x, "green")
#Showing our Plot
Page 62
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.show()
Page 63
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.show()
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
fig=plt.figure()
ax.plot(x,y,"purple")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("This is my first chart using Object Oriented Approach")
plt.show()
#To put in two sets of figures on one canvas:
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
Page 64
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
ax=fig.add_axes([.1,.2,.8,.9])
fig=plt.figure()
ax.plot(x,y,"purple")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("This is my first chart using Object Oriented Approach")
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
# To Create a 3 by 3 Subplots
fig, axes=plt.subplots(nrows=3, ncols=3)
plt.show()
# Using .tight_layout() method
# to avoid overlapping in subplots
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
# Empty Canvas of 3*3 Subplots
plt.tight_layout()
5. Write a program in Python to create to create a plot and set its figure
size, aspect, ratio and DPI.
Solution:-
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,20)
Page 65
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
y=(x**2)
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
plt.show()
fig=plt.figure()
ax=fig.add_axes([0.1,0.2,0.8,0.9])
fig=plt.figure()
ax.plot(x,y,"purple")
plt.show()
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
fig=plt.figure()
ax.plot(x,y,"purple")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("This is my first chart using Object Oriented Approach")
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
fig, axes=plt.subplots(nrows=3, ncols=3)
plt.show()
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
plt.tight_layout()
# Specifying the figure size,
Page 66
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# aspect ratio, and DPI
fig=plt.figure(figsize=(8,2),dpi=100)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
# Empty Canvas of 3*3 Subplots
plt.tight_layout()
#We can do the same thing with subplots() like:
fig, ax=plt.subplots(nrows=2, ncols=1,figsize=(8,4),dpi=100)
ax[0].plot(x,y)
ax[1].plot(y,x)
plt.tight_layout()
Page 67
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
fig, axes=plt.subplots(nrows=3, ncols=3)
plt.show()
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
plt.tight_layout()
# Empty Canvas of 3*3 Subplots
fig=plt.figure(figsize=(8,2),dpi=100)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
plt.tight_layout()
#We can do the same thing with subplots() like:
fig, ax=plt.subplots(nrows=2, ncols=1,figsize=(8,4),dpi=100)
ax[0].plot(x,y)
ax[1].plot(y,x)
plt.tight_layout()
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,x**2,label="X Square Plot")
ax.plot(x,x**3,"red",label="X Cube Plot")
ax.legend()
plt.show()
#To save our plot as an image
fig.savefig("my_figure.png")
#To open the saved imange
Page 68
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
'''import matplotlib.image as mpimg
plt.imshow(mpimg.imread("my_figure.png"))'''
Page 69
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.show()
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
plt.tight_layout()
# Empty Canvas of 3*3 Subplots
fig=plt.figure(figsize=(8,2),dpi=100)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
plt.tight_layout()
#We can do the same thing with subplots() like:
fig, ax=plt.subplots(nrows=2, ncols=1,figsize=(8,4),dpi=100)
ax[0].plot(x,y)
ax[1].plot(y,x)
plt.tight_layout()
#Adding the Legends
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,x**2,label="X Square Plot")
ax.plot(x,x**3,"red",label="X Cube Plot")
ax.legend()
plt.show()
Page 70
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
ax=fig.add_axes([0.1,0.2,0.8,0.9])
fig=plt.figure()
ax.plot(x,y,"purple")
plt.show()
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
fig=plt.figure()
ax.plot(x,y,"purple")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("This is my first chart using Object Oriented Approach")
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
fig, axes=plt.subplots(nrows=3, ncols=3)
plt.show()
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
plt.tight_layout()
# Empty Canvas of 3*3 Subplots
fig=plt.figure(figsize=(8,2),dpi=100)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
plt.tight_layout()
#We can do the same thing with subplots() like:
Page 71
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
fig, ax=plt.subplots(nrows=2, ncols=1,figsize=(8,4),dpi=100)
ax[0].plot(x,y)
ax[1].plot(y,x)
plt.tight_layout()
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,x**2,label="X Square Plot")
ax.plot(x,x**3,"red",label="X Cube Plot")
ax.legend()
plt.show()
#CHANGING THE PLOT APPEARANCE
#Change the Color
#Change the Line Thikness
#Line Style to Dashes
#Mark out the datapoints
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color="purple",linewidth=3,linestyle="--
",marker="o",markersize=8)
plt.show()
9. Write a program in Python to create a plot and set the range for x axis
and y axis.
Solution:-
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,20)
y=(x**2)
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
plt.show()
fig=plt.figure()
ax=fig.add_axes([0.1,0.2,0.8,0.9])
fig=plt.figure()
ax.plot(x,y,"purple")
plt.show()
Page 72
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
fig=plt.figure()
ax=fig.add_axes([.1,.2,.8,.9])
fig=plt.figure()
ax.plot(x,y,"purple")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_title("This is my first chart using Object Oriented Approach")
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
plt.show()
fig=plt.figure()
axes1=fig.add_axes([0.1,0.1,0.8,0.8])
axes2=fig.add_axes([0.2,0.5,0.4,0.3])
axes1.plot(x,y)
axes2.plot(y,x)
plt.show()
fig, axes=plt.subplots(nrows=3, ncols=3)
plt.show()
fig, ax=plt.subplots(nrows=3, ncols=3)
plt.tight_layout()
fig, ax=plt.subplots(nrows=3, ncols=3)
ax[0,1].plot(x,y)
ax[1,2].plot(y,x)
plt.tight_layout()
# Empty Canvas of 3*3 Subplots
fig=plt.figure(figsize=(8,2),dpi=100)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y)
plt.tight_layout()
#We can do the same thing with subplots() like:
fig, ax=plt.subplots(nrows=2, ncols=1,figsize=(8,4),dpi=100)
ax[0].plot(x,y)
ax[1].plot(y,x)
plt.tight_layout()
Page 73
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,x**2,label="X Square Plot")
ax.plot(x,x**3,"red",label="X Cube Plot")
ax.legend()
plt.show()
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color="purple",linewidth=3,linestyle="--
",marker="o",markersize=8)
plt.show()
#PLOT RANGE
#To Show Only Plot Between
#0 to 1 for the X Axis and
#0 to 5 for the Y Axis
fig=plt.figure(figsize=(8,6),dpi=60)
ax=fig.add_axes([0,0,1,1])
ax.plot(x,y,color="purple",lw=3,ls="--")
ax.set_xlim([0,1])
#[0,1]signifies the lower bound and upper bound of x axis
ax.set_ylim([0,5])
#[0,5]signifies the lower bound and upper bound of y axis
plt.show()
Page 74
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.ylabel("Numbers")
plt.title("First Plot")
plt.legend()
plt.show()
Page 75
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
13. Write a program in Python to create a plot by using alpha and
annotation.
Solution:-
#Using Alpha and Annotation
import matplotlib.pyplot as plt
from matplotlib import style
web_customers=[123,645,950,1290,1630,1450,1034,1295,465,205,80]
time_hrs=[7,8,9,10,11,12,13,14,15,16,17]
style.use("ggplot")
plt.plot(time_hrs,web_customers,alpha=.4)
plt.axis([6.5,17.5,50,2000])
plt.title("Web Site Traffic")
plt.annotate("Max",ha="center",va="bottom",xytext=(8,1500),xy=(11,1630
),arrowprops={"facecolor":"green"})
plt.xlabel("Hrs")
plt.ylabel("Number of Users")
plt.show()
Page 76
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.ylabel("Number of Users")
plt.legend()
plt.show()
15. Write a program in Python to create two subplots that shows two
different comparisons on different variables.
Solution:-
import matplotlib.pyplot as plt
temperature=[2,21,14,24,27]
time_hrs=[5,7,9,11,12]
wind=[23,26,15,21,24]
plt.subplot(1,2,1)
plt.plot(time_hrs,temperature,"r")
plt.title("Time Vs Temprature")
plt.xlabel("Time")
plt.ylabel("Temprature")
plt.subplot(1,2,2)
plt.plot(time_hrs,wind,"g")
plt.title("Wind Vs Time")
plt.xlabel("Time")
plt.ylabel("Wind")
plt.tight_layout()
Page 77
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
y=np.random.randint(100,size=x.shape)
plt.plot(x,y)
plt.tight_layout()
Page 78
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Basic Exercise on Chart
1. Write a Python program to draw a line with suitable label in the x axis, y
axis and a title.
Solution:
import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 3 for value in X]
print("Values of X:")
print(*range(1,50))
print("Values of Y (thrice of X):")
print(Y)
# Plot lines and/or markers to the Axes.
plt.plot(X, Y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Draw a line.')
# Display the figure.
plt.show()
Page 79
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
2. Write a Python program to draw a line using given axis values with
suitable label in the x axis , y axis and a title.
Solution:
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# y axis values
y = [2,4,1]
# Plot lines and/or markers to the Axes.
plt.plot(x, y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('graph!')
# Display a figure.
plt.show()
Output:
Page 80
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
3. Write a Python program to draw a line using given axis values with
suitable label in the x axis , y axis and a title.
test.txt
12
24
31
Solution:
import matplotlib.pyplot as plt
with open("test.txt") as f:
data = f.read()
data = data.split('\n')
x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]
plt.plot(x, y)
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('graph!')
# Display a figure.
plt.show()
Page 81
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
4. Write a Python program to draw line charts of the financial data of
Alphabet Inc. between October 3, 2016 to October 7, 2016.
Financial data (fdata.csv):
Date,Open,High,Low,Close
10-03-16,774.25,776.065002,769.5,772.559998
10-04-16,776.030029,778.710022,772.890015,776.429993
10-05-16,779.309998,782.070007,775.650024,776.469971
10-06-16,779,780.47998,775.539978,776.859985
10-07-16,779.659973,779.659973,770.75,775.080017
Solution:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('fdata.csv', sep=',', parse_dates=True, index_col=0)
df.plot()
plt.show()
Output:
Page 82
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
5. Write a Python program to plot two or more lines on same plot with
suitable legends of each line.
Solution:
import matplotlib.pyplot as plt
# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Display a figure.
plt.show()
Page 83
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
6. Write a Python program to plot two or more lines with legends, different
widths and colors.
Solution:
import matplotlib.pyplot as plt
# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Two or more lines with different widths and colors with suitable
legends ')
# Display the figure.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-width-3')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-width-5')
# show a legend on the plot
plt.legend()
plt.show()
Page 84
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
7. Write a Python program to plot two or more lines with different styles.
Solution:
import matplotlib.pyplot as plt
# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Plot lines and/or markers to the Axes.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-
dotted',linestyle='dotted')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-dashed',
linestyle='dashed')
# Set a title
plt.title("Plot with two or more lines with different styles")
# show a legend on the plot
plt.legend()
# function to show the plot
plt.show()
Page 85
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
8. Write a Python program to plot two or more lines and set the line
markers.
Solution:
import matplotlib.pyplot as plt
# x axis values
x = [1,4,5,6,7]
# y axis values
y = [2,6,3,6,3]
# plotting the points
plt.plot(x, y, color='red', linestyle='dashdot', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)
#Set the y-limits of the current axes.
plt.ylim(1,8)
#Set the x-limits of the current axes.
plt.xlim(1,8)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Display marker')
# function to show the plot
plt.show()
Page 86
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
9. Write a Python program to display the current axis limits values and set
new axis values.
Solution:
import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 3 for value in X]
plt.plot(X, Y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Draw a line.')
# shows the current axis limits values
print(plt.axis())
# set new axes limits
# Limit of x axis 0 to 100
# Limit of y axis 0 to 200
plt.axis([0, 100, 0, 200])
# Display the figure.
plt.show()
Page 87
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
10. Write a Python program to plot quantities which have an x and y
position.
Solution:
import numpy as np
import pylab as pl
# Make an array of x values
x1 = [2, 3, 5, 6, 8]
# Make an array of y values for each x value
y1 = [1, 5, 10, 18, 20]
# Make an array of x values
x2 = [3, 4, 6, 7, 9]
# Make an array of y values for each x value
y2 = [2, 6, 11, 20, 22]
# set new axes limits
pl.axis([0, 10, 0, 30])
# use pylab to plot x and y as red circles
pl.plot(x1, y1,'b*', x2, y2, 'ro')
# show the plot on the screen
pl.show()
Page 88
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
11. Write a Python program to plot several lines with different format
styles in one command using arrays.
Solution:
import numpy as np
import matplotlib.pyplot as plt
Page 89
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
12. Write a Python program to create multiple types of charts (a simple
curve and plot some quantities) on a single set of axes.
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
data = [(DT.datetime.strptime('2016-10-03', "%Y-%m-%d"), 772.559998),
(DT.datetime.strptime('2016-10-04', "%Y-%m-%d"), 776.429993),
(DT.datetime.strptime('2016-10-05', "%Y-%m-%d"), 776.469971),
(DT.datetime.strptime('2016-10-06', "%Y-%m-%d"), 776.859985),
(DT.datetime.strptime('2016-10-07', "%Y-%m-%d"), 775.080017 )]
x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]
fig = plt.figure()
graph = fig.add_subplot(111)
# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')
# Set the xtick locations
graph.set_xticks(x)
# Set the xtick labels
graph.set_xticklabels([date.strftime("%Y-%m-%d") for (date, value) in data])
plt.show()
Page 90
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
13. Write a Python program to display grid and draw line charts of the
closing value of Alphabet Inc. between October 3, 2016 to October 7,
2016. Customized the grid lines with linestyle -, width .5. and color blue.
Date,Close
03-10-16,772.559998
04-10-16,776.429993
05-10-16,776.469971
06-10-16,776.859985
07-10-16,775.080017
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
fig = plt.figure()
graph = fig.add_subplot(111)
Page 91
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
graph.set_xticklabels(
[date.strftime("%Y-%m-%d") for (date, value) in data]
)
# giving a title
plt.title('Closing stock value of Alphabet Inc.')
Page 92
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
14. Write a Python program to display the grid and draw line charts of the
closing value of Alphabet Inc. between October 3, 2016 to October 7,
2016. Customized the grid lines with rendering with a larger grid (major
grid) and a smaller grid (minor grid).Turn on the grid but turn off ticks..
Date,Close
03-10-16,772.559998
04-10-16,776.429993
05-10-16,776.469971
06-10-16,776.859985
07-10-16,775.080017
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
fig = plt.figure()
graph = fig.add_subplot(111)
Page 93
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# naming the x axis
plt.xlabel('Date')
# naming the y axis
plt.ylabel('Closing Value')
# giving a title
plt.title('Closing stock value of Alphabet Inc.')
# Turn on the minor TICKS, which are required for the minor GRID
plt.minorticks_on()
Page 94
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
15. Write a Python program to create multiple plots
Solution:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.subplots_adjust(bottom=0.020, left=0.020, top = 0.900, right=0.800)
plt.subplot(2, 1, 1)
plt.xticks(()), plt.yticks(())
plt.subplot(2, 3, 4)
plt.xticks(())
plt.yticks(())
plt.subplot(2, 3, 5)
plt.xticks(())
plt.yticks(())
plt.subplot(2, 3, 6)
plt.xticks(())
plt.yticks(())
plt.show()
Page 95
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
16. Write a Python program to create multiple types of charts (a simple
curve and plot some quantities) on a single set of axes.
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
Page 96
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
17. Write a Python program to plot several lines with different format
styles in one command using arrays.
Solution:
import numpy as np
import matplotlib.pyplot as plt
# d time at 200ms intervals
t = np.arange(0., 5., 0.2)
# green dashes, blue squares and red triangles
plt.plot(t, t, 'g--', t, t**2, 'bs', t, t**3, 'r^')
plt.show()
19. Write a Python program to display the current axis limits values and
set new axis values.
Solution:
import matplotlib.pyplot as plt
X = range(1, 50)
Y = [value * 3 for value in X]
plt.plot(X, Y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('Draw a line.')
# shows the current axis limits values
print(plt.axis())
# set new axes limits
Page 98
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# Limit of x axis 0 to 100
# Limit of y axis 0 to 200
plt.axis([0, 100, 0, 200])
# Display the figure.
plt.show()
20. Write a Python program to plot two or more lines and set the line
markers.
Solution:
import matplotlib.pyplot as plt
# x axis values
x = [1,4,5,6,7]
# y axis values
y = [2,6,3,6,3]
# plotting the points
plt.plot(x, y, color='red', linestyle='dashdot', linewidth = 3,
marker='o', markerfacecolor='blue', markersize=12)
#Set the y-limits of the current axes.
plt.ylim(1,8)
#Set the x-limits of the current axes.
Page 99
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.xlim(1,8)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Display marker')
# function to show the plot
plt.show()
21. Write a Python program to plot two or more lines with different
styles.
Solution:
import matplotlib.pyplot as plt
# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
Page 100
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Plot lines and/or markers to the Axes.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-
dotted',linestyle='dotted')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-dashed',
linestyle='dashed')
# Set a title
plt.title("Plot with two or more lines with different styles")
# show a legend on the plot
plt.legend()
# function to show the plot
plt.show()
22. Write a Python program to plot two or more lines with legends,
different widths and colors.
Solution:
import matplotlib.pyplot as plt
# line 1 points
Page 101
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
x1 = [10,20,30]
y1 = [20,40,10]
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# Set the x axis label of the current axis.
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title
plt.title('Two or more lines with different widths and colors with suitable
legends ')
# Display the figure.
plt.plot(x1,y1, color='blue', linewidth = 3, label = 'line1-width-3')
plt.plot(x2,y2, color='red', linewidth = 5, label = 'line2-width-5')
# show a legend on the plot
plt.legend()
plt.show()
Page 102
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
23. Write a Python program to plot two or more lines on same plot with
suitable legends of each line.
Solution:
import matplotlib.pyplot as plt
# line 1 points
x1 = [10,20,30]
y1 = [20,40,10]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# line 2 points
x2 = [10,20,30]
y2 = [40,10,30]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
plt.xlabel('x - axis')
# Set the y axis label of the current axis.
plt.ylabel('y - axis')
# Set a title of the current axes.
plt.title('Two or more lines on same plot with suitable legends ')
# show a legend on the plot
plt.legend()
# Display a figure.
plt.show()
Page 103
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
24. Write a Python program to draw line charts of the financial data of
Alphabet Inc. between October 3, 2016 to October 7, 2016.
Financial data (fdata.csv):
Date,Open,High,Low,Close
10-03-16,774.25,776.065002,769.5,772.559998
10-04-16,776.030029,778.710022,772.890015,776.429993
10-05-16,779.309998,782.070007,775.650024,776.469971
10-06-16,779,780.47998,775.539978,776.859985
10-07-16,779.659973,779.659973,770.75,775.080017
Solution:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('fdata.csv', sep=',', parse_dates=True, index_col=0)
df.plot()
plt.show()
25. Write a Python program to display grid and draw line charts of the
closing value of Alphabet Inc. between October 3, 2016 to October 7,
2016. Customized the grid lines with linestyle -, width .5. and color blue.
Page 104
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Date,Close
03-10-16,772.559998
04-10-16,776.429993
05-10-16,776.469971
06-10-16,776.859985
07-10-16,775.080017
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
fig = plt.figure()
graph = fig.add_subplot(111)
Page 105
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.ylabel('Closing Value')
# giving a title
plt.title('Closing stock value of Alphabet Inc.')
# Customize the grid
plt.grid(linestyle='-', linewidth='0.5', color='blue')
plt.show()
26. Write a Python program to display the grid and draw line charts of the
closing value of Alphabet Inc. between October 3, 2016 to October 7,
2016. Customized the grid lines with rendering with a larger grid (major
grid) and a smaller grid (minor grid).Turn on the grid but turn off ticks..
Date,Close
03-10-16,772.559998
04-10-16,776.429993
05-10-16,776.469971
06-10-16,776.859985
07-10-16,775.080017
Page 106
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
fig = plt.figure()
graph = fig.add_subplot(111)
Page 107
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# Customize the major grid
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
Page 108
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.xticks(())
plt.yticks(())
plt.subplot(2, 3, 5)
plt.xticks(())
plt.yticks(())
plt.subplot(2, 3, 6)
plt.xticks(())
plt.yticks(())
plt.show()
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, popularity, color='blue')
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
Page 109
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JS', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.barh(x_pos, popularity, color='green')
plt.xlabel("Popularity")
plt.ylabel("Languages")
Page 110
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.yticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
Page 111
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, popularity, color=(0.4, 0.6, 0.8, 1.0))
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Page 113
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
32. Write a Python programming to display a bar chart of the popularity
of programming Languages, based on following data. Attach a text label
above each bar displaying its popularity (float value).
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
fig, ax = plt.subplots()
rects1 = ax.bar(x_pos, popularity, color='b')
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.xticks(x_pos, x)
plt.show()
Page 114
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
33. Write a Python programming to display a bar chart of the popularity
of programming Languages, based on following data. Make blue border
to each bar.
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.xlabel("Languages")
Page 115
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.xticks(x_pos, x)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
Output:
Page 116
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
34. Write a Python programming to display a bar chart of the popularity
of programming Languages. Specify the position of each bar plot.
data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.xticks(x_pos, x)
# Select the position of each barplots on the x-axis (space=1,3,3,2,1)
y_pos = [0,1,4,7,9,10]
# Create bars
plt.bar(y_pos, popularity)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='red')
# Customize the minor grid
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Page 117
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
35. Write a Python programming to display a bar chart of the popularity
of programming Languages, based on following data. Select the width of
each bar and their positions.
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
plt.xticks(x_pos, x)
Page 118
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
# Select the width of each bar and their positions
width = [0.1,0.2,0.5,1.1,0.2,0.3]
y_pos = [0,.8,1.5,3,5,6]
# Create bars
plt.bar(y_pos, popularity, width=width)
plt.xticks(y_pos, x)
Page 119
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
36. Write a Python programming to display a bar chart of the popularity
of programming Languages. Increase bottom margin.
data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
Solution:
import matplotlib.pyplot as plt
x = ['Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++']
popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, popularity, color=(0.4, 0.6, 0.8, 1.0))
plt.xlabel("Languages")
plt.ylabel("Popularity")
plt.title("PopularitY of Programming Language\n" + "Worldwide, Oct 2017
compared to a year ago")
Output:
Page 120
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
37. Write a Python program to create bar plot of scores by group and
gender. Use multiple X values on the same chart for men and women.
Data:
Means (men) = (22, 30, 35, 35, 26)
Means (women) = (25, 32, 30, 35, 29)
Solution:
import numpy as np
import matplotlib.pyplot as plt
# data to plot
n_groups = 5
men_means = (22, 30, 33, 30, 26)
women_means = (25, 32, 30, 35, 29)
# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8
Page 121
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
rects1 = plt.bar(index, men_means, bar_width,
alpha=opacity,
color='g',
label='Men')
plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.legend()
plt.tight_layout()
plt.show()
Page 122
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
38. Write a Python program to create bar plot from a DataFrame.
Data Frame:
abcde
2 4,8,5,7,6
4 2,3,4,2,6
6 4,7,4,7,8
8 2,6,4,8,6
10 2,4,3,3,2
Solution:
from pandas import DataFrame
import matplotlib.pyplot as plt
import numpy as np
a=np.array([[4,8,5,7,6],[2,3,4,2,6],[4,7,4,7,8],[2,6,4,8,6],[2,4,3,3,2]])
df=DataFrame(a, columns=['a','b','c','d','e'], index=[2,4,6,8,10])
df.plot(kind='bar')
Page 123
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
39. Write a Python program to create bar plots with errorbars on the same
figure.
Mean velocity: 0.2474, 0.1235, 0.1737, 0.1824
Standard deviation of velocity: 0.3314, 0.2278, 0.2836, 0.2645
Solution:
import numpy as np
import matplotlib.pyplot as plt
N=5
menMeans = (54.74, 42.35, 67.37, 58.24, 30.25)
menStd = (4, 3, 4, 1, 5)
# the x locations for the groups
ind = np.arange(N)
# the width of the bars
width = 0.35
plt.bar(ind, menMeans, width, yerr=menStd, color='red')
plt.ylabel('Scores')
plt.xlabel('Velocity')
plt.title('Scores by Velocity')
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Page 124
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
40. Write a Python program to create bar plots with errorbars on the same
figure.
Data:
Mean velocity: 0.2474, 0.1235, 0.1737, 0.1824
Standard deviation of velocity: 0.3314, 0.2278, 0.2836, 0.2645
Solution:
import numpy as np
import matplotlib.pyplot as plt
N=5
menMeans = (54.74, 42.35, 67.37, 58.24, 30.25)
menStd = (4, 3, 4, 1, 5)
Output:
Page 125
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
41. Write a Python program to create a stacked bar plot with error bars.
Note: Use bottom to stack the women’s bars on top of the men’s bars.
Data:
Means (men) = (22, 30, 35, 35, 26)
Means (women) = (25, 32, 30, 35, 29)
Men Standard deviation = (4, 3, 4, 1, 5)
Women Standard deviation = (3, 5, 2, 3, 3)
Solution:
import numpy as np
import matplotlib.pyplot as plt
N=5
menMeans = (22, 30, 35, 35, 26)
womenMeans = (25, 32, 30, 35, 29)
menStd = (4, 3, 4, 1, 5)
Page 126
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
womenStd = (3, 5, 2, 3, 3)
# the x locations for the groups
ind = np.arange(N)
# the width of the bars
width = 0.35
plt.ylabel('Scores')
plt.xlabel('Groups')
plt.title('Scores by group\n' + 'and gender')
plt.xticks(ind, ('Group1', 'Group2', 'Group3', 'Group4', 'Group5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
Page 127
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
42. Write a Python program to create a horizontal bar chart with differently
ordered colors.
Note: Use bottom to stack the women’s bars on top of the men’s bars.
Data Set:
languages = [['Language','Science','Math'],
['Science','Math','Language'],
['Math','Language','Science']]
numbers = [{'Language':75, 'Science':88, 'Math':96},
{'Language':71, 'Science':95, 'Math':92},
{'Language':75, 'Science':90, 'Math':89}]
Solution:
import numpy as np
from matplotlib import pyplot as plt
lan_guage = [['Language','Science','Math'],
['Science','Math','Language'],
['Math','Language','Science']]
colors = ["r","g","b"]
names = sorted(num_set[0].keys())
values = np.array([[data[name] for name in order] for data,order in
zip(num_set, lan_guage)])
lefts = np.insert(np.cumsum(values, axis=1),0,0, axis=1)[:, :-1]
orders = np.array(lan_guage)
bottoms = np.arange(len(lan_guage))
Page 128
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
plt.yticks(bottoms+0.4, ["Student-%d" % (t+1) for t in bottoms])
plt.legend(loc="best", bbox_to_anchor=(1.0, 1.00))
plt.subplots_adjust(right=0.75)
# Turn on the grid
plt.minorticks_on()
plt.grid(which='major', linestyle='-', linewidth='0.5', color='green')
plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black')
plt.show()
Output:
43. Write a Python program to create stack bar plot and add label to each
section.
data:
people = ('G1','G2','G3','G4','G5','G6','G7','G8')
segments = 4
# multi-dimensional data
Page 129
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
data = [[ 3.40022085, 7.70632498, 6.4097905, 10.51648577, 7.5330039,
7.1123587, 12.77792868, 3.44773477],
[ 11.24811149, 5.03778215, 6.65808464, 12.32220677, 7.45964195,
6.79685302, 7.24578743, 3.69371847],
[ 3.94253354, 4.74763549, 11.73529246, 4.6465543, 12.9952182,
4.63832778, 11.16849999, 8.56883433],
[ 4.24409799, 12.71746612, 11.3772169, 9.00514257, 10.47084185,
10.97567589, 3.98287652, 8.80552122]]
Solution:
import numpy as np
import matplotlib.pyplot as plt
people = ('G1','G2','G3','G4','G5','G6','G7','G8')
segments = 4
# multi-dimensional data
data = [[ 3.40022085, 7.70632498, 6.4097905, 10.51648577, 7.5330039,
7.1123587, 12.77792868, 3.44773477],
[ 11.24811149, 5.03778215, 6.65808464, 12.32220677, 7.45964195,
6.79685302, 7.24578743, 3.69371847],
[ 3.94253354, 4.74763549, 11.73529246, 4.6465543, 12.9952182,
4.63832778, 11.16849999, 8.56883433],
[ 4.24409799, 12.71746612, 11.3772169, 9.00514257, 10.47084185,
10.97567589, 3.98287652, 8.80552122]]
percentages = (np.random.randint(5,20, (len(people), segments)))
y_pos = np.arange(len(people))
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)
colors ='rgwm'
patch_handles = []
# left alignment of data starts at zero
left = np.zeros(len(people))
for i, d in enumerate(data):
Page 130
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
patch_handles.append(ax.barh(y_pos, d,
color=colors[i%len(colors)], align='center',
left=left))
left += d
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.set_xlabel('Scores')
plt.show()
Page 131
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
44. Write a Python program to add textures (black and white) to bars and
wedges.
Solution:
import matplotlib.pyplot as plt
fig = plt.figure()
patterns = [ "|" , "\\" , "/" , "+" , "-", ".", "*","x", "o", "O" ]
ax = fig.add_subplot(111)
for i in range(len(patterns)):
ax.bar(i, 3, color='white', edgecolor='black', hatch=patterns[i])
plt.show()
Page 132
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Solution:
import matplotlib.pyplot as plt
# Data to plot
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0,0,0)
# Plot
plt.pie(popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()
Page 133
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
data:
medal.csv
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17
Solution:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)
plt.pie(medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in
2016 Summer Olympics")
plt.show()
Page 134
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
47. Write a Python program to draw a scatter graph taking a random
distribution in X and Y and plotted against each other.
Solution:
import matplotlib.pyplot as plt
from pylab import randn
X = randn(200)
Y = randn(200)
plt.scatter(X,Y, color='r')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Output
Page 135
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
48. Write a Python program to draw a scatter plot with empty circles
taking a random distribution in X and Y and plotted against each other.
Solution:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(50)
y = np.random.randn(50)
plt.scatter(x, y, s=70, facecolors='none', edgecolors='g')
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Output:
Page 136
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
49. Write a Python program to draw a scatter plot using random
distributions to generate balls of different sizes.
Solution:
import math
import random
import matplotlib.pyplot as plt
# create random data
no_of_balls = 25
x = [random.triangular() for i in range(no_of_balls)]
y = [random.gauss(0.5, 0.25) for i in range(no_of_balls)]
colors = [random.randint(1, 4) for i in range(no_of_balls)]
areas = [math.pi * random.randint(5, 15)**2 for i in range(no_of_balls)]
# draw the plot
plt.figure()
plt.scatter(x, y, s=areas, c=colors, alpha=0.85)
plt.axis([0.0, 1.0, 0.0, 1.0])
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Page 137
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
50. Write a Python program to draw a scatter plot comparing two subject
marks of Mathematics and Science. Use marks of 10 students.
Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Solution:
import matplotlib.pyplot as plt
import pandas as pd
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks', color='g')
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()
Page 138
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
51. Write a Python program to draw a scatter plot for three different
groups camparing weights and heights.
Solution:
import matplotlib.pyplot as plt
import numpy as np
weight1=[67,57.2,59.6,59.64,55.8,61.2,60.45,61,56.23,56]
height1=[101.7,197.6,98.3,125.1,113.7,157.7,136,148.9,125.3,114.9]
weight2=[61.9,64,62.1,64.2,62.3,65.4,62.4,61.4,62.5,63.6]
height2=[152.8,155.3,135.1,125.2,151.3,135,182.2,195.9,165.1,125.1]
weight3=[68.2,67.2,68.4,68.7,71,71.3,70.8,70,71.1,71.7]
height3=[165.8,170.9,192.8,135.4,161.4,136.1,167.1,235.1,181.1,177.3]
weight=np.concatenate((weight1,weight2,weight3))
height=np.concatenate((height1,height2,height3))
plt.scatter(weight, height, marker='*', color=['red','green','blue'])
plt.xlabel('weight', fontsize=16)
plt.ylabel('height', fontsize=16)
plt.title('Group wise Weight vs Height scatter plot',fontsize=20)
plt.show()
Page 139
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
52. Write a Python program to draw a scatter plot to find sea level rise in
past 100 years. We have collected the data from here
[https://github.com/datasets/sea-level-rise].
This data contains "cumulative changes in sea level for the world’s oceans since 1880, based on
a combination of long-term tide gauge measurements and recent satellite measurements. It shows
average absolute sea level change, which refers to the height of the ocean surface, regardless of
whether nearby land is rising or falling. Satellite data are based solely on measured sea level,
while the long-term tide gauge data include a small correction factor because the size and shape
of the oceans are changing slowly over time. (On average, the ocean floor has been gradually
sinking since the last Ice Age peak, 20,000 years ago.)"
Data:
data.csv
Solution:
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('data.csv')
year = data['year']
sea_levels = data['CSIRO_sea_level']
plt.scatter(year, sea_levels, edgecolors='g')
plt.xlabel('Year')
plt.ylabel('Sea Level (inches)')
plt.title('Rise in Sealevel')
plt.show()
Page 140
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Computer Network
1. Give two examples of PAN and LAN type of network.
2. Name any two type of protocols used in network. What does it stands for?
3. What kinds of security are available to Internet users?
4. Write any two advantages and disadvantages of Bus Topoloty?
5. Differentiate between Message Switching and Packet Switching
Techniques.
6. Write two difference between XML and HTML.
7. What was the role are ARPANET in the Computer Network?
8. What term we use for a software/hardware which is used to block
unauthorized access while permitting authorized communication?
9. What is the difference between Virus and Worms in the computers?
10. Explain various situations which comes under Cyber Crime.
11. Write three language names of Client Side and Server Side scripts.
12. Give one suitable example of each URL and Domain Name.
13. What is the difference between Domain Name and IP Address?
14. Write two advantages of using an Optical Fibre Cable over and Ethernet
cable to connect two service stations, which are 190 m away from each
other.
15. Which protocol will you use to have an audio-visual chat with an expert
sitting in a far-away place to fix-up a technical issue?
16. Differentiate between http and ftp.
17. Write one advantage of Bus Topology. Also illustrate how 4 computers
can be connected with each other using Star Topoloty?
18. Write two characterstics of Wi-Fi.
19. What is the difference between E-Mail and Chat?
20. Illustrate the layout for connecting five computers in a Bus and Star
Topoloty of network.
21. Which type of network is formed, when you connect two mobiles using
Bluetooth to transter a video?
22. What is a spam mail?
23. Which is the fastest wired and wireless medium of communication?
24. What do you mean by a backbone network?
25. What is E-Mail? What are its advantages?
26. What is the difference between LAN and MAN?
27. What is the difference between LAN and Internet?
Page 141
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
28. What is the purpose of using FTP?
29. What is the purpose of using routers?
30. What is the importance of URL in networking?
31. How does firewall protect our Network?
32. What are cookies?
33. Briefly explain the following in the instance of networm.
a) VoIP b) WEB 2.0
34. What do you mean by IP Address? How is it usful in Computer Security?
35. How is Coaxial cable different from Optical Fibre?
36. What is the significance of Cyber Law? Also write two applications of
Cyber Law?
37. Differencitate between Internet and Intranet.
38. Differentiate between Telnet and FTP.
39. Write one advantages and disadvantages of Optical Fibre cables.
40. Name two Switching Techniques and explain any one.
41. What is the purpose of using MODEM?
42. Which protocol is used for transfer of hypertext documents on the
Internet?
43. Briefly describe the difference between LAN, MAN, and WAN in the
context of their geographical scope.
44. What is a Communication Channel? What choices do you have while
choosing a communication channel for network?
45. What is meant by network topoloty? What are the most popular
topologies?
46. Explain in brief of networking needs and goals.
47. Differentiate between Repeaters and Routers.
48. Write the advantages and disadvantages of Star, Ring and Bus topoloty
in computer network.
49. What are bridges? How do they differ from repeaters?
50. What are Protocols? What is the significance of protocols in networks?
51. What are the functions of a MODEM?
52. What are the functions provided by the SERVER in a Network
environment?
53. Give the advantages of E-Mail and World Wide Web service provided by
Internet.
54. What is WWW and what are its advantages?
55. Write a short note on Cyber Law.
Page 142
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
56. What do you mean by Spam Mails? How can you protect your mailbox
from Spams?
57. What is the difference between Hub, Switch and Router?
58. What is NIC?
59. What are major types of networks? Explain.
60. What are the enabling technologies of IoT system?
61. What are the security concerns related to IoT?
62. Briefly discuss the role of following devices in the context of networking.
a) Router b) Bridge c) Gatewary
63. What are Hubs? How are active hubs different from passive hubs?
64. In which network there is no Server?
65. What is Cloud? What is Cloud Computing?
66. What are different cloud deployment models?
67. How is a Public Cloud different from a Private Cloud?
68. What is modulation?
69. Differentiate between carrier wave and modulated wave.
70. What is Aplitude Modulation?
71. What is dmodulation? How it is different from modulation?
72. Which characterstics of the modulated signals carries the actual
message/information?
73. What is Collision in a network? How does it impact the performance of a
network?
74. What measures do wireless networks employ to avoid collisions?
75. Explain the two types of Duplex communication.
76. The wireless networks employstrategies to avoid collisions. Why can’t
they detect collisions?
77. What is CSMA/CA? How does it works?
78. What are the basic methods of checking or detecting errors in the data
transmission over network?
79. What type of errors that may occur in the data transmitted over a
network?
80. What do you understand by the Parrity Checking?
81. Give an example of how 1 two-dimensional parity check detects error in
the received data.
82. What are checksums? What are the stpes sollowed in checksum
generator?
83. What is ACK(Acklologement) signal?
Page 143
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
84. What is routing? Explain briefly.
85. What is routing table? What type of information is stored in a routing
table?
86. What is network congestion? What are the symptoms of network
congestion?
87. Write a brief note on TCP/IP suite.
88. Write a short note on IPo4 addressing. Also discuss how IPo4 is different
from IPo6?
89. Write a short note on IPo4 addressing.
90. What is Ping network tool?
91. What is a tracert or traceroute command?
92. What is the use of Whois command?
93. What is Domain Name System? What is DNS lookup?
94. What is URL? What are the components of a URL?
95. How is Domain Name System different from URL?
96. What is the role/importance of TCP/IP on Internet communication?
97. Discuss the network tllos ipconfig and nslookup briefly.
98. Discuss the following network protocols briefly.
a) HTTP d) SSH g) SMTP
b) FTP e) POP h) VoIP
c) SCP f) IMAP i) NFC
99. Discuss the basic working model of HTTP.
100. What are MX records?
101. What is encryption? Why is considered so important?
102. What is HTTPS? How does it work?
103. What is SSL? How does it impact the communication over Internet?
104. What is remote desktop?
105. Expand the following abbriviations.
a) OSI j) WLL s) NFS
b) FTP k) TCP/IP t) DTR
c) WAN l) PPP u) SLIP
d) WWW m) XML v) SMTP
e) GSM n) HTML w) POP3
f) CDMA o) URL x) IMAP
g) HTTP p) SMS y) GPRS
h) ARPANET q) MAN z) VoI
i) MODEM r) DHTML
Page 144
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj
Page 145
Compiled By: Riteash Kumar Tiwari (9935973245)
V.B.P.S., Prayagraj