You are on page 1of 53

Vidya Vikas Education Trust’s

 Universal College of Engineering, Kaman, Vasai

One week FDP in association with Spoken Tutorial IITB, Mumbai


On

“Python”
4 May – 8 May 2020
th th  

Sr. Number: 159


Name of Participant: Thakur Shilpa
Email ID: thakurshilpa18@gmail.com
Mobile Number:9949568478
Day1 Date 4th May 2020

Assignment-1
1. Find out the commands starting with ab.
In [2]: abs
            abs()
            absolute
            absolute_import
                           

2. List out the commands starting with a.


In [2]: a
   abs()          amin               arctan             array_repr         assert             axvline    
absolute           angle              arctan2            array_split        async              axvspan   
absolute_import    angle_spectrum     arctanh            array_str          atleast_1d        
"Application Data"    acorr()            annotate           argmax             arrow            
atleast_2d         AppData/    add                any                argmin             asanyarray        
atleast_3d         %alias    add_docstring      append             argpartition       asarray           
autoscale          %alias_magic
   add_newdoc         apply_along_axis   argsort            asarray_chkfinite  autumn           
%autoawait    add_newdoc_ufunc   apply_over_axes    argwhere           ascii             
average            %autocall    alen               arange            around             ascontiguousarray 
await              %autoindent
   all                arccos             array              asfarray           axes              %automagic  
allclose           arccosh            array2string       asfortranarray     axhline    alltrue           
arcsin             array_equal        asmatrix           axhspan    amax               arcsinh           
array_equiv        asscalar           axis

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

 In [4]: round(2.48,1)

Out[4]: 2.5

 In [5]: round(2.484)

Out[5]: 2

 In [6]: round(2.484,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 (?)

                Using plot command interactively - Assignments

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')

2. Zoom and find the maxima.

3. Bring it back to  initial position.


Assignment-2
1. Create 100 equally spaced points between -pi/2 and pi/2.

In [12]: t=linspace(-pi,pi,100)

2. How can we find the length of a sequence?

In [13]: len(t)

Out[13]: 100

3. What will the command linspace(-pi, pi ,100) do?


➢ returns 100 evenly spaced samples from -pi to pi?
➢ returns 100 evenly spaced samples from -pi to pi excluding pi but including -pi?
➢ returns 100 evenly spaced samples from -pi to pi excluding -pi but including pi?
➢ returns 100 evenly spaced samples from -pi to pi including both -pi & pi?

Embellishing a plot - Assignments


Assignment-1
1. Plot the curve of x vs cos(x) in red dashed line and linewidth 3.

In [14]:plot(x,cos(x),'r--',linewidth=3)

output:

Assignment-2

1. Make an annotation called “root” at the point (-4, 0).

In [24]: annotate("root",xy=(-4,0))
Out[24]: Text(-4, 0, 'root')
2. What happens to the first annotation?

Creates a new 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

command “ylabel”. (Yes or No)

NO
Saving plots- Assignments
Assignment-1

1. Save the sine plot in the eps format.


In [44]: savefig('sine.eps')

Assignment-2

1. Save the sine plot in PDF, PS and SVG formats.


In [45]: savefig('sine.pdf')
In [46]: savefig('sine.ps')
In [47]: savefig('sine.svg')

Assignment-3

1. Which command is used to save a plot?

➢ saveplot()

➢ savefig()

➢ savefigure()

➢ saveplt()

2. savefig ('sine.png') saves the plot in,

➢ The root directory “/” (on GNU/Linux, Unix based systems), “C:” (on windows).

➢ Will result in an error as full path is not supplied.

➢ The current working directory.

➢ Predefined directory like “/ documents”.

Multiple plots - Assignments


Assignment-1

Draw two plots for the given form

1. First plot is a parabola of the form y = 4x 2


2. Second plot is a straight line of the form y = 2x + 3 in the interval -5 to 5.

3. Use legends to indicate each plot.

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.

2. Save each of them.

In [40]: figure(1)

Out[40]: <Figure size 640x480 with 0 Axes>

In [41]: plot(x,x)

Out[41]: [<matplotlib.lines.Line2D at 0xb524610>]

In [42]: figure(2)
Out[42]: <Figure size 640x480 with 1 Axes>

In [43]: plot(x,2*x+3)

Out[43]: [<matplotlib.lines.Line2D at 0x1a7d928>]

In [44]: figure(1)

Out[44]: <Figure size 640x480 with 1 Axes>

In [45]: savefig('plot1.png')

In [46]: figure(2)

Out[46]: <Figure size 640x480 with 1 Axes>

In [47]: savefig('plot2.png')

Assignment-3

1. What command is used to get individual plots separately?


Figure()
2. What will be the command to identify sine and cosine curve?
Legend([‘sin(x)’,’cos(x)’])

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.

Draw two different plots as subplots:

1. Pressure v/s Volume plot and

2. Pressure v/s Temperature plot.

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)

Additional features of IPython-Assignments

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

In my case show command is at the line 52,so I write the command as

in [58]: %save show_include.py 39-52

2. Run the script to produce the plot and display the same.

In [60]: %run -i show_include.py


10: subplot(2,2,2)
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-3

1. How do you save the command lines 2 3 4 5 7 9 10 11?


➢ %save <filename> 2-5 7 9-11
➢ %save <filename> 2-11
➢ %save <filename>
➢ %save 2-5 7 9 10 11
Assignment-4
1. Which is the command to run the script?
➢ %execute <script name>
➢ %run -i <script name>
➢ %run <script name>
➢ %execute -i <script name>

Loading Data From Files –Assignments


Assignment-1
1. Read the data from the file pendulum_semicolon.txt available at the code file link of this
tutorial.
2. This file contains data in two columns. These columns are separated by semi-colons.
3. Use the IPython help to see how to do this.

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

Plotting Data –Assignments

1. Plot the given experimental data with large dots.


∂l ∂t
0.08 0.04
0.09 0.08
0.07 0.03
0.05 0.05
0.06 0.03
0.00 0.03
0.06 0.04
0.06 0.07
0.01 0.08

In [3]: t= [0.69, 0.90, 1.19,1.30, 1.47, 1.58, 1.77, 1.83, 1.94]

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]

In [21]: errorbar(l, tsquare, xerr=dl, yerr=du, fmt='bo')


Out[21]: <ErrorbarContainer object of 3 artists>

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>]

In [33]: errorbar(s, n, xerr=delta_s, yerr=delta_n, fmt='bo')


Out[33]: <ErrorbarContainer object of 3 artists>

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)

2. Plot l versus t in red pluses from the Simple Pendulum Data.


In [2]: l=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]

In [3]: t= [0.69, 0.90, 1.19,1.30, 1.47, 1.58, 1.77, 1.83, 1.94]


In [43]: plot(l,t,'r+')

Other Types Of Plots -Assignments

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 [85]: pie(profit,labels=year,colors=('w','r','k','m','y','b',' g','c','y','m','b'))


Assignment-3
1. Plot a bar 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 [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='\')

Getting started with Lists –Assignments

Assignment-1

1. What happens when you type mylist[-1]?


In [93]: mylist=['spam','eggs',100,1.234]
In [102]: mylist[-1]
Out[102]: 1.234

Assignment-2

doublelist=['a', ['b','c','d'], 'and', 5, 6, 7, 8]

1. What is the command to get the element 'and' in the list doublelist?

In [138]: doublelist[2]

Out[138]: 'and'

2. How would you get 'and' using negative indices?


In [140]: doublelist[-5]
Out[140]: 'and'

3. How would you get element 'd' from the list doublelist?
In [141]: doublelist[1][2]
Out[141]: 'd'

Assignment-3

1. Delete the fourth element from the list doublelist

In [131]: doublelist.remove(doublelist[3])
In [132]: doublelist
Out[132]: ['a', ['b', 'c', 'd'], 'and', 6, 7, 8]

2. Remove 'and' from the list doublelist.

In [134]: doublelist.remove('and')
In [135]: doublelist
Out[135]: ['a', ['b', 'c', 'd'], 6, 7, 8]

Assignment-4

1. How do you create an empty list?


Mylist=[]
2. Can you have a list inside a list?
yes
3. How would you access the last element of a list without finding its length?
Using negative indices

Getting started with for -Assignments

Assignment-1

1. Use the same example we used in sqrt_num_list.py


2. Type each line of the code in the IPython interpreter.
3. Skip the line: print("This is outside for-loop").

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

1. Print all the odd numbers from 1 to 50.


In [3]: for i in range(1,50,2):
...: print(i)
...:
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49

Assignment-4

1. Indentation is not mandatory in Python.


➢ True
➢ False
2. Write a for loop to print the product of all natural numbers from 1 to 20.
In [7]: p=1

In [8]: for i in range(1,21):


...: p*=i
...: print("product of first 20 numbers is",p)
product of first 20 numbers is 2432902008176640000

3. What will be the output of: range(1, 5).


Produces a list of integers from1 to 4 i.e(1,2,3,4)

Getting started with strings -Assignments


Assignment-1
1. Obtain the string %%--------------------%%(20 hyphens) without typing out all the twenty
hyphens
In [31]: s='%%'+'-'*20+'%%'
In [32]: s
Out[32]: '%%--------------------%%'

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'

Getting started with files – Assignments


Assignment-1

1. Re-open the file pendulum.txt (available in the code files link of this tutorial) with f as the
file object

Assignment-2

1. The open function returns

• string
• list
• file object
• function

2. What does the function splitlines() do?

• Displays the data as strings, all in a line


• Displays the data line by line as strings
• Displays the data line by line but not as strings
Parsing data – Assignments
Assignment-1

x = “08-26-2009; 08-27-2009; 08-29-2009”

Split x using space as argument. Is it same as splitting without an argument?

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']

Is it same as splitting without an argument

NO

In [73]: str1.split()

Out[73]: ['welcome', 'to', 'python', 'tutorial']

In [74]: str1.split(' ')

Out[74]: ['welcome', 'to', '', '', '', '', '', '', 'python', 'tutorial']

Assignment-2

1. What happens if you type int(“1.25”) in the terminal?


ValueError: invalid literal for int() with base 10: '1.25'

Assignment-3

1. How do you split the string “Guido;Rossum;Python” to get the words?


In [90]: str='guido;rossum;python'
In [92]: str.split(';')
Out[92]: ['guido', 'rossum', 'python']

2. What does int (“20.0”) produce?

➢ 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.

Download and save the file in the present working directory

1. Find the total goals for each player.


In [21]: l=np.loadtxt('football.txt',usecols=(1,2),delimiter=',')
In [22]: np.sum(l,1)
Out[22]: array([153., 99., 86., 47., 88., 99.])
2. Find the mean of home and goals away.
In [23]: np.mean(l,0)
Out[23]: array([49.33333333, 46. ])

3. Find the standard deviation of home and goals away .

In [24]: np.std(l,0)
Out[24]: array([20.72572208, 15.57776193 ])

Assignment-2

1. Given a two dimensional list as, two_dimensional_list=[[3,5,8,2,1],[4,3,6,2,1]] How do you


calculate the mean of each row?
In [25]: two_dimensional_list=[[3,5,8,2,1],[4,3,6,2,1]]
In [26]: np.mean( two_dimensional_list,1)
Out[26]: array([3.8, 3.2])
2. Calculate the median of the given list. student_marks=[74,78,56,87,91,82]
In [28]: np.median(student_marks)
Out[28]: 80.0
3. There is a file with 6 columns. But we want to load text only from columns 2, 3, 4, 5. How do we
specify that?
In loadtxt for usecolns value should be usecolns(2,3,4,5)

Getting started with arrays – Assignments

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

Out[31]: array([1, 2, 3, 4])

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]])

Accessing parts of arrays – Assignments


C = array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, -14, 15], [16, 17, 18, 19, 20], [2, 2, 2, 2, 2]])
Assignment-1
1. Obtain the following elements one by one from array C.
1. [7, 8]
In [114]: c[1,1:3]
Out[114]: array([7, 8])
2. [1, 6, 11, 16]
In [117]: c[0:4,0]
Out[117]: array([ 1, 6, 11, 16])
3. [6, 11, 16, 2]
In [118]: c[1:5,0]
Out[118]: array([ 6, 11, 16, 2])

Assignment-2

1. Obtain the elements [[8, 9], [13, -14]] from array C.


In [120]: c[1:3,2:4]
Out[120]:
array([[ 8, 9],
[ 13, -14]])

Assignment-3

1. Obtain the following elements from array C.

1. [[2, 5], [17, 20]]

In [122]: c[::3,1::3]

Out[122]:

array([[ 2, 5],

[17, 20]])

2. [[2, 3, 4], [2, 2, 2]]

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]

2. B = array ( [ [10, 11, 12, 13],

[20, 21, 22, 23],

[30, 31, 32, 33],

[40, 41, 42, 43] ] )

How do we obtain the elements [[21, 22], [31, 32]] from the given array B?

B[1:3,1:3]

Image manipulation using Arrays – Assignments

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)

Basic Matrix Operations – Assignments

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 [82]: from numpy.linalg import inv,norm

In [83]: im=inv(m)

In [84]: norm(im)

Out[84]: 3.7059917700933944

Assignment-2

1. Find the infinity norm of the matrix 'im'


im = [[ 2.50000000e-01, -6.25000000e-02, -2.50000000e+00, 1.81250000e+00], [-5.00000000e-01,
1.54638207e-16, 1.50000000e+00, -1.00000000e+00], [ 2.50000000e-01, 1.87500000e-01,
5.00000000e-01, -4.37500000e-01], [ 1.24900090e-16, -1.25000000e-01, 2.50000000e-01,
-1.25000000e-01]]

In [86]: from numpy import inf


In [87]: norm(im,ord=inf)
Out[87]: 4.624999999999995

Assignment-3
1. norm(A,ord='fro') is the same as norm (A) ?
➢ True
➢ False

Least Square Fit – Assignments

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

1. Find the square root of 3 using Python?


3**0.5

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

Sequence datatypes– Assignments


Assignment-1
1. [1,7,5,3,4]
• Check if 3 is an element of the given list.

• Change the third element in the list to 21.

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

2. If a = 2 and b = 4.5, what is the result of the following action?


print ( ' a is %d and b is %2.1f ' %(b,a))
➢ a is 2 and b is 4.5
➢ a is 4 and b is 2
➢a is 4 and b is 2.0
➢ a is 4.5 and b is 2
Conditional Statements – Assignments
Assignment-1
1. Given a number, num as input.
2. Write an if else block to print num, if it is divisible by 10, else print 10 * num.

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.

2. Convert the below if else code into ternary conditional statement.


x = 20
if x > 10:
print (x * 100)
else:
print (x)
Loops– Assignments
Assignment-1
1. Write a “while” loop to print the squares of all the even numbers below 10.

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.

2. Which statement do you use to skip iterations?


➢break
➢paas
➢continue
Manipulating lists– Assignments
Assignment-1
1. primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]Obtain the primes less than 10, from the list
primes.

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?

2. Given a list p, of unknown length. Obtain the first 3 characters of it.


Manipulating strings – Assignments
Assignment-1
1. s = "saturday"
Obtain the substring excluding the first and last characters from the string s.

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"?

2. Given a string s = “F.R.I.E.N.D.S”, change the string to “friends”.


Getting started with tuples – Assignments
Assignment-1
1. Given a = 5 and b = 7, swap the values of a and b.

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.

Hint: use items() and for loop.

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?

3. If a is a set, how do you check if a variable b exists in a?


- b in a

Getting Started with Functions

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

Advanced Features of Functions

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.

2. Then, call the function without any arguments.

Assignment-3
1. All the arguments of a function cannot have default values. True or False?
- False

2. The following is a valid function definition. True or False?


def separator(count=40, char, show=False): if show: print char * count return char * count
- 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

Using Python Modules

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 5 - Writing Python Scripts


1. Which of the following variables contains the locations to search for python modules?
➢ sys.pythonpath
➢ sys.path
➢ os.pythonpath
➢ os.path

2. A module should contain only one function.


➢ True
➢ False

Assignment 6 - Testing and Debugging

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

Assignment 7 - Handling Errors and Exceptions


Assignment-1
1. How do you start the debugger on IPython?
➢ debug
➢ %debug
➢ %debugger
➢ start debugger

You might also like