0% found this document useful (0 votes)
13 views20 pages

Assignment 1 All Answers

Uploaded by

ahmed.razi98989
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

Assignment 1 All Answers

Uploaded by

ahmed.razi98989
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Assignment_1_All_Answers

April 11, 2021

[8]: #Question 1

a = [100, 200]
b = a
b += [300, 400] #add b to a and assign the result to variable a
print(a) # prints out #[100, 200, 300, 400]
print(b) # a is also same because of above operator used with value [100, 200,␣
,→300, 400]

#Question 2

def fun1(Name, Age=28):


print(Name, Age) # Prints HARRY 25 (Default value for Age parameter is␣
,→overridden with value passed from the function)

fun1('HARRY', 25) # Call function with following parameters

#Question 3

def outerFun(a, b): # Parameter a is input as 25, b as 20


def innerFun(c, d):
return c + d # 45 is returned
return innerFun(a, b) # call inner function and pass c=25 , d =20, 45 is␣
,→returned

return a # Finally a is returned with value 45

fun_call = outerFun(25, 20)


print(fun_call) # Answer is 45

#Question 4

#Choose the correct function declaration of fun() so that we can execute the␣
,→following

#function call successfully.


#fun1(25, 75, 55)

1
#fun1(10, 20)
#a. def fun1(**kwargs)
#b. No, it is not possible in Python
#c. def fun1(args*)
#d. def fun1(*data)

# For variable length of Positional Arguments, we use *args

#Answer : d

#Question 5

def fun(**kwargs):
for i in kwargs:
print(i) # Print the positional arguments

fun(emp="John", salary=25000) # Call function with variable length of␣


,→positional arguments

#Answer is below:

# emp
# salary

#Question 6

a = 0
while (a < 20):
a += 2 # While a is less than 20, a is incremented by 2. When a becomes 20,␣
,→it comes out of while loop

print(a) # a is 20

#Answer is below:

# 20

#Question 7

for i in range(1, 16): # i starts from 1 till 16


for j in range(2, i): # j starts from 2 till value of i
if i % j == 1: # Check if remainder is 1 when i divided by j
print(i) # First scenario, for i =3, j in range(2,3) and 3 % 2 ==1,␣
,→hence print 3 and pick

break # next value of i which is 4

2
# Now, for j in range (2,4) and i =4.
# i % j comes out as 4 % 2 which is 0. Next j in range (2,4), so j becomes 3
# i % j comes out as 3 % 2 which is 1.
# So i =4 and it is printed and break makes it come out of loop. Next value of␣
,→i is 5 and this goes on

#Answer is below:

# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12
# 13
# 14
# 15

#Question 8

x = 0
a = 0
b = -5
if a > 0: # This loop is entered only when a > 0, we have a =0 - so if␣
,→statement is not executed and control goes to else

if b < 0:
x = x + 5
elif a > 5:
x = x + 4
else:
x = x + 3
else:
x = x + 2 # 2 is added to initial value of x which was 0, hence x = 2
print(x)

#Answer is below:

# 2

#Question 9

3
x = [10, 20, 30, 40, 50]
for i in range(1, 5):
x[i-1] = x[i] # x[0] = x[1], x[1] = x[2], ......., x[4] = x[5]
for i in range(0, 5):
print(x[i], end=" ") # print x[0] to x[5] which is 20 30 40 50 50

#Answer is below:

# 20 30 40 50 50

#Question 10

# Generate two 4x4 2D numpy array using arrange(), and then perform some basic
# operation and evaluate the results
# a. Transpose the array
# b. Multiply the arrays
# c. Stack the arrays Vertically and Horizontally
# d. Convert the 2D array into 1D array
# e. Reverse the column of the array
# f. Swap two rows of an array
# g. Swap two columns of an array
# h. Get the common elements between two arrays
# i. Get the position of if two array matches somewhere.
# j. Remove the elements of an array if it matches to another array.

# Generate two 4X4 2D numpy array using arange


import numpy as np

array_one = np.arange(2,18).reshape(4,4)
array_two = np.arange(2,34,2).reshape(4,4)
print("\n")
print("Question No. 10")
print("1st array : %s", array_one)
print("2nd array : %s", array_two)

# a) Transpose the array


def transpose_array(array_input):
print("Transpose of array : %s",np.transpose(array_input))

transpose_array(array_one)
transpose_array(array_two)

# b) Multiply the arrays


def multiply_array(array_a, array_b):
print("Multiplication result of arrays : %s",np.multiply(array_a,array_b))

4
multiply_array(array_one,array_two)

# c. Stack the arrays Vertically and Horizontally

def stack_arrays(array_a, array_b):


print("Vertical stacked array : %s", np.vstack((array_a,array_b)))
print("Horizontal stacked array : %s", np.hstack((array_a,array_b)))

stack_arrays(array_one,array_two)

# d. Convert the 2D array into 1D array

def convert_to_1d_array(array_input):
print("1 D of array : %s",array_input.flatten())

convert_to_1d_array(array_one)
convert_to_1d_array(array_two)

# e. Reverse the column of the array

def reverse_column_array(array_input):
print("Array after column reverse : %s",np.flip(array_input, axis=1))

reverse_column_array(array_one)
reverse_column_array(array_two)

# f. Swap two rows of an array

def swap_rows(array_input, start_index, last_index):


array_swapped = array_input
array_swapped[[start_index, last_index]] = array_swapped[[last_index,␣
,→start_index]]

print(" After Swapping rows :")


print(array_swapped)

swap_rows(array_one, 0, 3)
swap_rows(array_two, 0, 3)

# g. Swap two columns of an array

def swap_columns(array_input, start_index, last_index):


array_swapped = array_input
array_swapped[:, [start_index, last_index]] = array_swapped[:, [last_index,␣
,→start_index]]

print(" After Swapping columns :")


print(array_swapped)

5
swap_columns(array_one, 0, 3)
swap_columns(array_two, 0, 3)

# h. Get the common elements between two arrays

def common_elements_array(array_A, array_B):


print(" Common elements in 2 arrays are : ",np.intersect1d(array_A,␣
,→array_B))

common_elements_array(array_one, array_two)

# i. Get the position of if two array matches somewhere.


print(array_one)
print(array_two)

print(np.argwhere(array_one == array_two))

#Question 11

# Take an image of your choice. Performs basic operations using SciPy library:
# a. Read the image
# b. Plot the image with title.
# c. Rotate the image.
# d. Flip the image.
# e. Apply Sobel filter
# f. Apply Gaussian filter with the different values of sigma.
# g. Apply morphological dilation and erosion with the variation of size: tuple␣
,→of

# ints on the image.

from scipy import misc, ndimage


import matplotlib.pyplot as plt
import matplotlib.pyplot as mpimg
import numpy as np
import imageio

#Sample raccoon image using misc


image_raccoon_load = misc.face()

print("\n")
print("Question No. 11")

# save the image using Image module


imageio.imsave('raccoon.jpeg', image_raccoon_load)

# a. Read the image

6
image = mpimg.imread('raccoon.jpeg')

# b. Plot the image with title.


def show_image(image_input, title):
plt.imshow(image_input)
plt.title(title)
plt.show()

show_image(image, "Raccoon - Original")

# c. Rotate the image.


def rotate_image(image_input, angle):
return ndimage.rotate(image_input, angle)

rotated_image = rotate_image(image, 90)


show_image(rotated_image, "Raccoon - Rotated")

# d. Flip the image.


def flip_image(image_input):
return np.flipud(image_input)

flipped_image = flip_image(image)
show_image(flipped_image, "Raccoon - Flipped")

# e. Apply Sobel filter


def sobel_filter(image_input):
return ndimage.filters.sobel(image_input)

image_sobel_filter = sobel_filter(image)
show_image(image_sobel_filter, "Raccoon - Sobel Filter")

# f. Apply Gaussian filter with the different values of sigma.


def gaussian_filter(image_input, sigma_value):
return ndimage.filters.gaussian_filter(image_input, sigma = sigma_value)

gaussian_one = gaussian_filter(image, 1)
show_image(gaussian_one, "Raccoon - Gaussian Sigma 1")

gaussian_two = gaussian_filter(image, 2)
show_image(gaussian_two, "Raccoon - Gaussian Sigma 2")

gaussian_three = gaussian_filter(image, 3)
show_image(gaussian_three, "Raccoon - Gaussian Sigma 3")

gaussian_four = gaussian_filter(image, 4)
show_image(gaussian_four, "Raccoon - Gaussian Sigma 4")

7
# g. Apply morphological dilation and erosion with the variation of size: tuple␣
,→of

# ints on the image.


def dilation(image_input, tuple_size):
return ndimage.grey_dilation(image_input, tuple_size)

dilation_img = dilation(image, (1,2,3))


show_image(dilation_img, "Raccoon - Dilated")

def erosion(image_input, tuple_size):


return ndimage.grey_erosion(image_input, tuple_size)

erosion_img = erosion(image, (1,2,3))


show_image(erosion_img, "Raccoon - Erosion")

#Question 12

# Generate a python DataFrame of Students_Records by combining the different␣


,→python

# Series for the students’ details, i.e. Name, Enrollment_no., Age, Course,
# Marks(Hindi, Maths, Science, English), Address And perform the following
# operations and get the results.
# a. Save the DataFrame as Student_records.csv file
# b. Import the Student_records.csv
# c. Print the 1st 10 rows of the DataFrame.
# d. Describe the DataFrame.
# e. Show the Students’ Name and their Age.
# f. Add one more column to the DataFrame as the Total_Marks, by summing
# marks of all the subjects.
# g. Take mean of the Total Marks.
# h. Take the mean by groupby the DataFrame based on the Age.
# i. Update the Address of the 5th Student in DataFrame
# j. Drop the column of Total_Marks

import pandas as pd

# Generate a python DataFrame of Students_Records by combining the different␣


,→python

# Series for the students’ details, i.e. Name, Enrollment_no., Age, Course,
# Marks(Hindi, Maths, Science, English), Address

print("\n")
print("Question No. 12")

def create_student_details_series (name, series_data):


return (pd.Series( series_data, name = name))

8
student_names = create_student_details_series('Names', ['John', 'Ricky',␣
,→'Matthew', 'Kane', 'Steve', 'David', 'Martin', 'Joe', 'Tom', 'Harry',␣

,→'Lionel', 'Ronaldo'])

student_enrolment_number = create_student_details_series('Enrolment No',[1, 2,␣


,→3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

student_age = create_student_details_series('Age',[25, 20, 30, 24, 28, 31, 22,␣


,→30, 21, 23, 26, 28])

student_address = create_student_details_series('Address',["Street_A",␣
,→"Street_B", "Street_C", "Street_D",

"Street_E", "Street_F", "Street_G", "Street_H", "Street_I", "Street_J",␣


,→"Street_K", "Street_L"])

#Marks of different subject for all students


student_hindi_marks = create_student_details_series('Hindi',[25, 20, 30, 24,␣
,→28, 31, 67, 70, 80, 91, 75, 66])

student_english_marks = create_student_details_series('English',[25, 20, 30,␣


,→24, 28, 31, 64, 71, 83, 97, 79, 66])

student_maths_marks = create_student_details_series('Maths',[25, 20, 30, 24,␣


,→28, 31, 67, 74, 83, 94, 77, 67])

student_science_marks = create_student_details_series('Science',[25, 20, 30,␣


,→24, 28, 31, 68, 75, 87, 95, 75, 76])

#Concat series
data_frame = pd.concat([student_names,student_enrolment_number,student_age,␣
,→student_address,

student_hindi_marks, student_english_marks, student_maths_marks,␣


,→student_science_marks], axis=1)

# a. Save the DataFrame as Student_records.csv file


data_frame.to_csv('Student_records.csv', index=False)

# b. Import the Student_records.csv


df = pd.read_csv('Student_records.csv')

# c. Print the 1st 10 rows of the DataFrame.


print("First 10 rows of the DataFrame:")
print(df.head(10))

# d. Describe the DataFrame.


df.describe()

# e. Show the Students’ Name and their Age.

9
df1 = df[['Names', 'Age']]
print("Names and Age of the DataFrame:")
print(df1)

# f. Add one more column to the DataFrame as the Total_Marks, by summing


# marks of all the subjects.

col_list = list(df)

#Remove columns which we dont want to sum


col_list.remove('Names')
col_list.remove('Enrolment No')
col_list.remove('Age')
col_list.remove('Address')

df['Total_Marks'] = df[col_list].sum(axis=1)

print("Dataframe after Total marks column added:")


print(df)

# g. Take mean of the Total Marks.


total_marks_mean = df["Total_Marks"].mean()
print("\n")
print("Mean of Total marks is :")
print(total_marks_mean)

# h. Take the mean by groupby the DataFrame based on the Age.

groupby_age_mean = df.groupby(['Age']).mean()
print("\n")
print("Mean by groupby the DataFrame based on the Age:")
print(groupby_age_mean)

# i. Update the Address of the 5th Student in DataFrame


df.at[4,'Address']='Street_Updated'

print("Updated address Dataframe for 5th student :")


print(df)

# j. Drop the column of Total_Marks


column_dataframe_dropped = df.drop(columns=['Total_Marks'])

print("Dataframe after Total marks column dropped:")


print(column_dataframe_dropped)

[100, 200, 300, 400]

10
[100, 200, 300, 400]
HARRY 25
45
emp
salary
20
3
4
5
6
7
8
9
10
11
12
13
14
15
2
20 30 40 50 50

Question No. 10
1st array : %s [[ 2 3 4 5]
[ 6 7 8 9]
[10 11 12 13]
[14 15 16 17]]
2nd array : %s [[ 2 4 6 8]
[10 12 14 16]
[18 20 22 24]
[26 28 30 32]]
Transpose of array : %s [[ 2 6 10 14]
[ 3 7 11 15]
[ 4 8 12 16]
[ 5 9 13 17]]
Transpose of array : %s [[ 2 10 18 26]
[ 4 12 20 28]
[ 6 14 22 30]
[ 8 16 24 32]]
Multiplication result of arrays : %s [[ 4 12 24 40]
[ 60 84 112 144]
[180 220 264 312]
[364 420 480 544]]
Vertical stacked array : %s [[ 2 3 4 5]
[ 6 7 8 9]
[10 11 12 13]
[14 15 16 17]
[ 2 4 6 8]

11
[10 12 14 16]
[18 20 22 24]
[26 28 30 32]]
Horizontal stacked array : %s [[ 2 3 4 5 2 4 6 8]
[ 6 7 8 9 10 12 14 16]
[10 11 12 13 18 20 22 24]
[14 15 16 17 26 28 30 32]]
1 D of array : %s [ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17]
1 D of array : %s [ 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32]
Array after column reverse : %s [[ 5 4 3 2]
[ 9 8 7 6]
[13 12 11 10]
[17 16 15 14]]
Array after column reverse : %s [[ 8 6 4 2]
[16 14 12 10]
[24 22 20 18]
[32 30 28 26]]
After Swapping rows :
[[14 15 16 17]
[ 6 7 8 9]
[10 11 12 13]
[ 2 3 4 5]]
After Swapping rows :
[[26 28 30 32]
[10 12 14 16]
[18 20 22 24]
[ 2 4 6 8]]
After Swapping columns :
[[17 15 16 14]
[ 9 7 8 6]
[13 11 12 10]
[ 5 3 4 2]]
After Swapping columns :
[[32 28 30 26]
[16 12 14 10]
[24 20 22 18]
[ 8 4 6 2]]
Common elements in 2 arrays are : [ 2 4 6 8 10 12 14 16]
[[17 15 16 14]
[ 9 7 8 6]
[13 11 12 10]
[ 5 3 4 2]]
[[32 28 30 26]
[16 12 14 10]
[24 20 22 18]
[ 8 4 6 2]]
[[3 3]]

12
Question No. 11

13
14
15
16
17
Question No. 12
First 10 rows of the DataFrame:
Names Enrolment No Age Address Hindi English Maths Science
0 John 1 25 Street_A 25 25 25 25
1 Ricky 2 20 Street_B 20 20 20 20
2 Matthew 3 30 Street_C 30 30 30 30
3 Kane 4 24 Street_D 24 24 24 24
4 Steve 5 28 Street_E 28 28 28 28
5 David 6 31 Street_F 31 31 31 31
6 Martin 7 22 Street_G 67 64 67 68
7 Joe 8 30 Street_H 70 71 74 75
8 Tom 9 21 Street_I 80 83 83 87
9 Harry 10 23 Street_J 91 97 94 95
Names and Age of the DataFrame:
Names Age
0 John 25
1 Ricky 20
2 Matthew 30
3 Kane 24
4 Steve 28
5 David 31
6 Martin 22
7 Joe 30
8 Tom 21
9 Harry 23
10 Lionel 26
11 Ronaldo 28
Dataframe after Total marks column added:
Names Enrolment No Age Address Hindi English Maths Science \
0 John 1 25 Street_A 25 25 25 25
1 Ricky 2 20 Street_B 20 20 20 20
2 Matthew 3 30 Street_C 30 30 30 30
3 Kane 4 24 Street_D 24 24 24 24
4 Steve 5 28 Street_E 28 28 28 28
5 David 6 31 Street_F 31 31 31 31
6 Martin 7 22 Street_G 67 64 67 68
7 Joe 8 30 Street_H 70 71 74 75
8 Tom 9 21 Street_I 80 83 83 87
9 Harry 10 23 Street_J 91 97 94 95
10 Lionel 11 26 Street_K 75 79 77 75
11 Ronaldo 12 28 Street_L 66 66 67 76

Total_Marks
0 100
1 80
2 120
3 96
4 112

18
5 124
6 266
7 290
8 333
9 377
10 306
11 275
Mean of Total marks is :
206.58333333333334

Mean by groupby the DataFrame based on the Age:


Enrolment No Hindi English Maths Science Total_Marks
Age
20 2.0 20.0 20.0 20.0 20.0 80.0
21 9.0 80.0 83.0 83.0 87.0 333.0
22 7.0 67.0 64.0 67.0 68.0 266.0
23 10.0 91.0 97.0 94.0 95.0 377.0
24 4.0 24.0 24.0 24.0 24.0 96.0
25 1.0 25.0 25.0 25.0 25.0 100.0
26 11.0 75.0 79.0 77.0 75.0 306.0
28 8.5 47.0 47.0 47.5 52.0 193.5
30 5.5 50.0 50.5 52.0 52.5 205.0
31 6.0 31.0 31.0 31.0 31.0 124.0
Updated address Dataframe for 5th student :
Names Enrolment No Age Address Hindi English Maths \
0 John 1 25 Street_A 25 25 25
1 Ricky 2 20 Street_B 20 20 20
2 Matthew 3 30 Street_C 30 30 30
3 Kane 4 24 Street_D 24 24 24
4 Steve 5 28 Street_Updated 28 28 28
5 David 6 31 Street_F 31 31 31
6 Martin 7 22 Street_G 67 64 67
7 Joe 8 30 Street_H 70 71 74
8 Tom 9 21 Street_I 80 83 83
9 Harry 10 23 Street_J 91 97 94
10 Lionel 11 26 Street_K 75 79 77
11 Ronaldo 12 28 Street_L 66 66 67

Science Total_Marks
0 25 100
1 20 80
2 30 120
3 24 96
4 28 112
5 31 124
6 68 266
7 75 290

19
8 87 333
9 95 377
10 75 306
11 76 275
Dataframe after Total marks column dropped:
Names Enrolment No Age Address Hindi English Maths Science
0 John 1 25 Street_A 25 25 25 25
1 Ricky 2 20 Street_B 20 20 20 20
2 Matthew 3 30 Street_C 30 30 30 30
3 Kane 4 24 Street_D 24 24 24 24
4 Steve 5 28 Street_Updated 28 28 28 28
5 David 6 31 Street_F 31 31 31 31
6 Martin 7 22 Street_G 67 64 67 68
7 Joe 8 30 Street_H 70 71 74 75
8 Tom 9 21 Street_I 80 83 83 87
9 Harry 10 23 Street_J 91 97 94 95
10 Lionel 11 26 Street_K 75 79 77 75
11 Ronaldo 12 28 Street_L 66 66 67 76

[ ]:

20

You might also like