Python Assignment
Python Assignment
Python Assignment
“Python”
4 May – 8 May 2020
th th
Assignment-1
1. Find out the commands starting with ab.
In [2]: abs
abs()
absolute
absolute_import
Assignment-2
1. Look-up the documentation of round and see how to use it.
In [2]: round?
Signature: round(number, ndigits=None)
Docstring:
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
Type: builtin_function_or_method
Assignment-3
1. Check the output of
a)round(2.48)
b)round(2.48, 1)
c)round(2.484)
d)round(2.484, 2)
In [3]: round(2.48)
Out[3]: 2
Out[4]: 2.5
Out[5]: 2
Assignment-4
1. Type round(2.484 without closing the paranthesis and press Enter.
In [7]: round(2.484
...:
2. Then cancel the command using Ctrl + C.
In [7]:
3. Type the command, round(2.484, 2).
In [7]: round(2.484,2)
Out[7]: 2.48
Assignment-5
1. IPython is a programming language similar to Python.
False
2. Which key combination quits IPython?
Ctrl + C
Ctrl + D
Alt + C
Alt + D
Ans:Ctrl + D
3. Which character is used at the end of a command, in IPython to display the
documentation?
under score (_)
question mark (?)
exclamation mark (!)
ampersand (&)
ANS:question mark (?)
Assignment-1
Plot (sin(x)*sin(x))/x.
In [8]: x=linspace(-2,2,100)
In [9]: plot(x,sin(x)*sin(x)/x)
Out[9]: [<matplotlib.lines.Line2D at 0xaf2bc70>]
1. Save the plot as sinsquarebyx.pdf
In [12]: savefig('c:/users/admin/desktop/sine.pdf')
In [12]: t=linspace(-pi,pi,100)
In [13]: len(t)
Out[13]: 100
In [14]:plot(x,cos(x),'r--',linewidth=3)
output:
Assignment-2
In [24]: annotate("root",xy=(-4,0))
Out[24]: Text(-4, 0, 'root')
2. What happens to the first annotation?
Assignment-3
1. Draw a plot of cosine graph between -2pi to 2pi with line thickness 4.
In [34]: x=linspace(-2*pi,2*pi)
In [35]: plot(x,cos(x),linewidth=4)
2. Read the documentation and find out, is there a way to modify the alignment of text in the
NO
Saving plots- Assignments
Assignment-1
Assignment-2
Assignment-3
➢ saveplot()
➢ savefig()
➢ savefigure()
➢ saveplt()
➢ The root directory “/” (on GNU/Linux, Unix based systems), “C:” (on windows).
In [60]: x=linspace(-5,5,100)
In [61]: plot(x,2*x+3)
Out[61]: [<matplotlib.lines.Line2D at 0xb0c6250>]
In [62]: plot(x,4*x*x)
Out[62]: [<matplotlib.lines.Line2D at 0xcf8e0e8>]
In [66]: legend([r'$y=4(x^2)$',r'$y=2x+3$'])
Assignment-2
1. Draw a line of the form y = x as one figure and another line of the form
y = 2x + 3.
In [40]: figure(1)
In [41]: plot(x,x)
In [42]: figure(2)
Out[42]: <Figure size 640x480 with 1 Axes>
In [43]: plot(x,2*x+3)
In [44]: figure(1)
In [45]: savefig('plot1.png')
In [46]: figure(2)
In [47]: savefig('plot2.png')
Assignment-3
Subplots – Assignments
Assignment-1
Pressure, Volume and Temperatures are held by the equation PV = nRT where nR is a
constant.
Assume nR =0.01 Joules/Kelvin and T = 200K. V can be in the range from 21cc to 100cc.
In [28]: subplot(2,1,1)
Out[28]: <matplotlib.axes._subplots.AxesSubplot at 0x115fc70>
In [29]: clf()
In [30]: v=linspace(21,100,500)
In [31]: subplot(2,1,1)
Out[31]: <matplotlib.axes._subplots.AxesSubplot at 0xc4f8328>
In [32]: plot(v,2.0/v)
Out[32]: [<matplotlib.lines.Line2D at 0x9948028>]
In [33]: subplot(2,1,2)
Out[33]: <matplotlib.axes._subplots.AxesSubplot at 0x128fec8>
In [34]: t=linspace(200,200,500)
In [35]: plot(t,2.0/v)
Out[35]: [<matplotlib.lines.Line2D at 0x445b3e8>]
Assignment-2
1. Which of the following is correct?
1. subplot (numRows, numCols, plotNum)
2. subplot (numRows, numCols)
3. subplot (numCols, numRows)
Assignment-1
1. Find out how to list the recent commands between 5 and 10.
In [49]: %history -n 5-10
5: plot(y,y*y)
6: clf()
7: subplot(2,1,1)
8: clf()
9: subplot(2,1,2)
10: subplot(2,2,2)
. Assignment-2
1. Use %history and %save to create a script that has the function show() in it.
Use the history command to see at which line show is present using the command
%history –n
2. Run the script to produce the plot and display the same.
Assignment-3
L,T=loadtxt("pendulum_semicolon.txt",unpack=True,del
...: imiter=":")
In [77]: print(l)
[0.1 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18 0.19]
In [78]: print(t)
[0.69004 0.69497 0.74252 0.7536 0.83568 0.86789 0.84182 0.85379 0.85762
0.8839 ]
Assignment-2
1. loadtxt() can read data only from a file with one column. Is it True or False?
False
2. Given a file “data.txt” with three columns of data separated by spaces. Read it into 3
separate simple sequences.
In [76]: l =loadtxt(data.txt",unpack=True)
3. Given a file “data.txt” with three columns of data separated by “:”. Read it into 3 separate
simple sequences.
In [77]: l =loadtxt(data.txt",unpack=True,delimiter=”:”)
Day-2 Date 5th May 2020
In [4]: tsuuare=square(t)
In [11]: dl=[0.08,
...:
...: 0.09,
...: 0.07,
...: 0.05,
...: 0.06,
...: 0.00,
...: 0.06,
...: 0.06,
...: 0.01,
...: ]
In [12]: du=[0.04,
...: 0.08,
...: 0.03,
...: 0.05,
...: 0.03,
...: 0.03,
...: 0.04,
...: 0.07,
...: 0.08]
Assignment-2
1. Plot the given experimental data with small dots. Also include the error in your plot
S n ∂S ∂n
0.19 10.74 0.006 0.61
0.38 14.01 0.006 0.69
0.57 18.52 0.005 0.53
0.77 20.23 0.003 0.38
0.96 22.88 0.004 0.46
1.15 24.59 0.007 0.37
1.34 27.55 0.004 0.46
1.54 28.48 0.004 0.46
1.73 30.20 0.007 0.37
In [22]: s=[0.19,0.38,0.57,0.77,0.96,1.15,1.34,1.54,1.73]
In [23]: n=[10.74,14.01,18.52,20.23,22.88,24.59,27.55,28.48,30.20]
In [24]: delta_s=[0.006,0.006,0.005,0.003,0.004,0.007,0.004,0.004,0.007]
In [25]: delta_n=[0.61,0.69,0.53,0.38,0.46,0.37,0.46,0.46,0.37)
in [31]: clf()
In [32]: plot(s,n,'o')
Out[32]: [<matplotlib.lines.Line2D at 0xa72a838>]
Assignment-3
1. Square the following sequence.
➢ distance_values = [2.1,4.6,8.72,9.03]
In [37]: distance_v=[2.1,4.6,8.72,9.03]
In [38]: square_v=square(distance_v)
Assignment-1
1. Plot a scatter plot showing the percentage profit of a Company A from the year 2000-2010.
Note: The data for the same is available in the file “company-a-data.txt”. This file is
available in the code file link of this tutorial. Please download and use it.
In [53]: year,profit=loadtxt('company-a-data.txt',unpack=True)
In [54]: scatter(year,profit)
Assignment-2
1. Read the documentation of scatter.
2. Plot a scatter plot of the same data in company-a-data.txt with red diamond markers
In [63]: scatter(year,profit,color='r',marker='d')
Assignment-3
1. Plot a log-log chart of y = 5x3 for x from 1-20.
In [68]: x=linspace(1,20)
In [69]: y=5*x**3
In [70]: loglog(x,y)
Out[70]: [<matplotlib.lines.Line2D at 0x10d7b688>]
In [71]: clf()
In [72]: loglog(x,y)
Assignment-4
1. scatter(x, y, color=’blue’, marker=’d’) and plot(x, y, color=’b’, marker=’d’) does exactly the same?
➢ True
False
Plotting Charts -Assignments
Assignment-1
1. Plot a pie chart representing the profit percentage of company A. 2. Use the data from file
company-a-data.txt available in the code file link of this tutorial.
In [53]: year,profit=loadtxt('company-a-data.txt',unpack=True)
In [81]: pie(profit,labels=year)
Assignment-2
1. Plot a pie chart with the same data with the following colors for each wedges.
➢ white, red, black, magenta,
➢ yellow, blue, green, cyan,
➢ yellow, magenta and blue.
Hint: In your ipython interpreter, try typing pie?
In [88]: bar(year,profit)
Out[88]: <BarContainer object of 11 artists>
Assignment-4
1. Plot a bar chart as shown in the video.
2. Hint: Bar chart is not filled and which is hatched with 45o slanting lines.
In [91]: bar(year,profit,fill=False,hatch='/')
Assignment-5
1.What
statement can
be issued to
generate a bar
chart with
vertical line
hatching?
➢ bar(x, y,
color='w',
hatch='/')
➢ bar(x, y,
fill=False,
hatch='//')
➢ bar(x, y, fill=False, hatch='|')
➢ bar(x, y, color='w', hatch='\')
Assignment-1
Assignment-2
1. What is the command to get the element 'and' in the list doublelist?
In [138]: doublelist[2]
Out[138]: 'and'
3. How would you get element 'd' from the list doublelist?
In [141]: doublelist[1][2]
Out[141]: 'd'
Assignment-3
In [131]: doublelist.remove(doublelist[3])
In [132]: doublelist
Out[132]: ['a', ['b', 'c', 'd'], 'and', 6, 7, 8]
In [134]: doublelist.remove('and')
In [135]: doublelist
Out[135]: ['a', ['b', 'c', 'd'], 6, 7, 8]
Assignment-4
Assignment-1
In [10]: numbers=[4,9,16,25,36]
In [11]: for num in numbers:
...: print("sqrt of ",num,"is",num**0.5)// press two enter keys
...:
sqrt of 4 is 2.0
sqrt of 9 is 3.0
sqrt of 16 is 4.0
sqrt of 25 is 5.0
sqrt of 36 is 6.0
Assignment-2
1. Find out the cube of all the numbers from 1 to 10
2. Execute this in the Python interpreter.
In [1]: for num in range(1,11):
...: print(num ,"cube","is",num**3)
...:
1 cube is 1
2 cube is 8
3 cube is 27
4 cube is 64
5 cube is 125
6 cube is 216
7 cube is 343
8 cube is 512
9 cube is 729
10 cube is 1000
Assignment-3
Assignment-4
Assignment-2
s = “Hello World”
what is the output of
s[-5]// 'w'
s[-10] //'e'
s[-15]// string index out of range
s[15]// string index out of range
Assignment-3
1. Write code to assign the string ‘ is called the apostrophe, to a variable s.
s='is called the aphostrophe'
2. How will you change s = ‘hello’ to s= ‘Hello’?
Strings cannot be manipulated once a value is assigned to it
3. The variables s and t are strings and r is integer. s = “Hello” t = ”World” r = 2
What is the output of s * r + t * r ?
'hellohelloworldworld'
1. Re-open the file pendulum.txt (available in the code files link of this tutorial) with f as the
file object
Assignment-2
• string
• list
• file object
• function
c=x.split(' ')
In [71]: c
out[71]: ['08-26-2009;08-27-2009;08-29-2009']
Out[71]: ['08-26-2009;08-27-2009;08-29-2009']
NO
In [73]: str1.split()
Out[74]: ['welcome', 'to', '', '', '', '', '', '', 'python', 'tutorial']
Assignment-2
Assignment-3
➢ 20
➢ 20.0
➢ Error
➢ “20
DAY-3
Date 6th May 2020
Statistics- Assignments
Assignment-1
Refer to the file football.txt, that is available in the code files link of this tutorial.
In [24]: np.std(l,0)
Out[24]: array([20.72572208, 15.57776193 ])
Assignment-2
Assignment-1
1. Find out the shape of the arrays a1 and ar which we have created earlier in this tutorial.
In [30]: a1=np.array([1,2,3,4])
In [31]: a1
In [48]: a1.shape
Out[48]: (4,)
In [36]: ar=np.arange(1,9)
In [37]: ar
Out[37]: array([1, 2, 3, 4, 5, 6, 7, 8])
In [49]: ar.shape
Out[49]: (2, 4)
Assignment-2
1. x = np.array ([1, 2, 3], [5, 6, 7]) is a valid statement?
➢ True
➢ False
The correct way of writing is x = np.array ([[1, 2, 3], [5, 6, 7]])
Assignment-2
Assignment-3
In [122]: c[::3,1::3]
Out[122]:
array([[ 2, 5],
[17, 20]])
In [123]: c[::4,1:4]
Out[123]:
array([[2, 3, 4],
[2, 2, 2]])
Assignment-4
1. A = array([12, 15, 18, 21]) How do we access the element 18 from the given array A?
A[2]
How do we obtain the elements [[21, 22], [31, 32]] from the given array B?
B[1:3,1:3]
Assignment-1
1. Use the image Squares.png available in the code file link of this tutorial and obtain the square in
the center of the image with size 150 by 150.
In [16]: plt.imshow(img[75:225,75:225])
Out[16]: <matplotlib.image.AxesImage at 0x9c8d100>
In [17]: plt.show()
Assignment-2
1. The shape of the variable img is (600, 600, 4).
What will be the shape of img1 if img1 = img[::2,::4]
➢ (300, 300, 4)
➢ (150, 300, 4)
➢ (300, 150, 4)
➢ (150, 150, 4)
Assignment-1
1. Create a two dimensional matrix m3 of shape 2 by 4 with the elements 5, 6, 7, 8, 9, 10, 11,
12. Hint: Use arange() and reshape() methods and asmatrix() function.
In [42]: m3_array=asmatrix(arange(5,13).reshape(2,4))
In [44]: m3_array
Out[44]:
matrix([[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
Assignment-2
1. Find out the determinant of the following 3 by 3 matrix. [[ 2, -3, 1], [ 2, 0, -1], [ 1, 4, 5]]
In [55]: from numpy.linalg import det
In [56]: m5=matrix([[2,-3,1],[2,0,-1],[1,4,5]])
In [57]: det(m5)
Out[57]: 49.000000000000014
Assignment-3
1. A and B are two matrix objects of appropriate sizes. Matrix multiplication is done by
➢A*B
➢ multiply(A, B)
➢ mul(A, B)
➢ element_multiply(A,B)
2. eig(A) [1] and eigvals(A) are the same.
➢ True
➢ False
Advanced Matrix Operations – Assignments
Assignment-1
1. Find out the Frobenius norm of the inverse 4x4 matrix
m= [[ 1, 0, 3, 4],
[ 5, 6, 7, 0],
[ 9, 10, 11, 12],
[13, 14, 15, 16]]
In [76]: m=asmatrix(arange(1,17).reshape(4,4))
In [77]: m
Out[77]:
matrix([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
In [78]: m[0,1]=0
In [79]: m[1,3]=0
In [80]: m
Out[80]:
matrix([[ 1, 0, 3, 4],
[ 5, 6, 7, 0],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
In [83]: im=inv(m)
In [84]: norm(im)
Out[84]: 3.7059917700933944
Assignment-2
Assignment-3
1. norm(A,ord='fro') is the same as norm (A) ?
➢ True
➢ False
Assignment-1
1. What does ones_like([1, 2, 3]) produce?
➢ array([1, 1, 1])
➢ [1, 1, 1]
➢ [1.0, 1.0, 1.0]
➢ Error
Basic datatypes and operators – Assignments
Assignment-1
Assignment-2
1. Will you get the same value for the below expressions?
➢ 3**1/2
➢ 3**0.5
NO
Assignment-3
1. What are the three built-in data types in Python to represent numbers?
int, float, complex
2. Which operator is used to find exponent?
**
Day4 Date 7th May 2020
Assignment-2
1. Convert the string "Elizabeth is queen of England" to "Elizabeth is queen".
Assignment-3
1. What is the major difference between tuple and list?
a. Tuple is used to store the data related to item whereas list is used to store the data
of similar type.
b. Tuple cannot change the value at particular index but list can able to change the
value at particular index.
2. Split the below string on whitespaces
s = “Split this string on whitespaces”
Input-output – Assignments
Assignment-1
1. What happens when you execute the following?
print ('x is %d, y is %f' %(x, y))
Ans:
It converts the value of x in integer type value and value of y in floating type value. As we
have used format specifiers ‘%d’ and ‘%f’ which reads and display the integer and float value
respectively
Assignment-2
1. Enter the number 5.6 as input and store it in a variable c.
Assignment-3
1. Execute the statement: d = input()
As seen above it ask user to enter the value. After entering value 10. It will assign value
10 to variable d.
2. What happens when you do not enter anything and hit Enter?
And if We do not enter anything and hit Enter button then it will assign null value to d.
Assignment-4
1. a = input( ) and user enters 2.5. What is the type of a?
➢str
➢int
➢ float
➢ char
Assignment-2
1. Given a number, n as input.
2. Write an ternary operator to print n, if it is divisible by 10, else print 10 * n.
Assignment-3
1. Given a variable t.
Print Good Morning if it is less than 12, otherwise print Hello.Use if else statement.
Assignment-2
1. Write a “for” loop to print the squares of all the even numbers below 10.
Assignment-3
1. Given range(1,4), write a code to print only the number 1.
Assignment-2
1. num = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Obtain all the multiples of 3 from the list num.
Assignment-3
1. Given below is the list of marks of a student in an examination
marks = [99, 67, 47, 100, 50, 75, 62]
Obtain a list with marks in descending order.
Or
Assignment-4
1. primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
How do you obtain the last 4 primes?
Assignment-2
1. week_name = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]
Check if each element in the list ["SATURDAY","python","Sunday"] is present in the list
week_name.
Assignment-3
1. Replace the [dot] with '.' symbol in email “info@fossee[dot]in”.
Assignment-4
1. email_str = "info@fossee.in, enquiries@fossee.in, help@fossee.in".
From the email_str, change the separator to semicolon instead of comma.
Assignment-5
1. Given a string s = "this was a string", how will you change it to "this wasn't a list"?
Or
Assignment-2
1. Define a tuple containing two values as given below.
The first value is integer 4 and the second value is float 2.5.
2. If we type, a = 5,
then what is the datatype of a?
➢int
➢float
➢tuple
➢string
3. If we type,a = (2,3)
a[0], a[1] = (3,4)
what is the output ?
Dictionaries - Assignments
Assignment-1
1. student = 'name':'raj', 'age':16, 'gender':'male', 'class':10
Print the keys and values of the dictionary student one by one.
Assignment-2
1. Given d = {1:'a', 2:'b'} How do you retrieve the value 'b'?
2. Delete the value 'b' from the dictionary d.
Day5 Date 8th May 2020
Sets in Python
Assignment-1
1. Given a list of marks, marks = [20, 23, 22, 23, 20, 21, 23] List all the duplicate marks.
Assignment-2
1. If a = [1, 1, 2, 3, 3, 5, 5, 8], what is set(a) ?
➢ {1, 1, 2, 3, 3, 5, 5, 8}
➢ {1, 2, 3, 5, 8}
➢ {1, 2, 3, 3, 5, 5}
➢ Error
2. Given odd and squares as shown. odd = set([1, 3, 5, 7, 9]) squares = set([1, 4, 9, 16]) How
do you find the symmetric difference of these two sets?
Assignment-1
1. Write a function circle which returns the area and perimeter of a circle with given radius
r.
Assignment-2
1. How many arguments can be passed to a Python function?
➢ None
➢ One
➢ Two
➢ Any
2. Write a function to find the area of a rectangle.
- def rectangle_area(l,b):
Return l*b
Assignment-1
1. Redefine the function welcome, by interchanging its arguments.
2. Place the name argument with its default value of "World" before the greet argument.
Assignment-2
1. Redefine the function welcome with a default value of "Hello" to the greet argument.
Assignment-3
1. All the arguments of a function cannot have default values. True or False?
- False
3. Choose the correct answer from the given options for the following statement:
1. While calling a function,
➢ the arguments should always be in the order in which they are defined
➢ only keyword arguments can be in any order, but should be called at the beginning
➢ only keyword arguments can be in any order, but should be called at the end
Assignment-1
1. Write a python script to plot a sine wave from -2pi to 2pi.
from numpy import linspace, pi, sin
from matplotlib.pyplot import plot, legend, show, title
from matplotlib.pyplot import xlabel, ylabel
x = linspace(-2*pi,2*pi,100)
plot(x,sin(x))
legend(['sin(x)'])
title('Sine plot')
xlabel('x')
ylabel('sin(x)')
show()
Assignment-2
1. Which among the below is the most correct ?
➢ from matplotlib.pyplot import plot
➢ from numpy import plot
➢ from matplotlib import plot
➢ from scipy import plot
2. Functions xlim() and ylim() can be imported to the current namespace as,
➢ from matplotlib.pyplot import xlim, ylim
➢ import matplotlib
➢ from numpy import xlim, ylim
➢ import numpy
Assignment-1
1. Write automated tests for LCM as GCD. Use data from the file lcmtestcases.txt for inputs.
Assignment-2
1. What is the proper indentation for python code according to the style guidelines?
➢ two space indentation
➢ three space indentation
➢ four space indentation
➢ no indentation