KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020
APJ ABDUL
KALAM TECHNOLOGICAL UNIVERSITY THIRD SEMESTER B.TECH DEGREE EXAMINATION, DECEMBER
2020 |
||||||
Course
Code: CST283 |
||||||
Course Name: Python for Machine Learning |
||||||
Max.
Marks: 100 |
|
Duration: 3
Hours |
||||
|
||||||
PART A |
||||||
|
|
Answer all questions.
Each question carries 3 marks |
Marks |
|||
|
1 |
Explain the input
statement with an example. How the type conversion is done |
3 |
|||
|
2 |
Illustrate the concept
of modules and explain with example how they are used in Python programs |
3 |
|||
|
3 |
Write a Python
program to print all prime numbers less than 100. |
3 |
|||
|
4 |
Demonstrate Lambda
function with an example |
3 |
|||
|
5 |
Use list to read n
names and print the names in alphabetical order |
3 |
|||
|
6 |
Let D
={‘a’:10,’b’:20} be a dictionary. Write commands to a) Add
a new key value pair(‘c’:30) b) Update
the value correspond to the key ‘a’ to 100 c) Remove
the entry corresponds to the key ‘b’ |
3 |
|||
|
7 |
|
3 |
|||
|
8 |
Describe the
exception handling mechanism in Python with an example |
3 |
|||
|
9 |
Illustrate numpy
arrays with example. How indexing,slicing and sorting is done with examples. |
3 |
|||
|
10 |
Write Python code to
plot a sin wave (from 0 to 2*pi) using matplotlib library with proper title, xlabel
and ylabel. |
3 |
|||
PART B |
||||||
Answer any one full question from each
module. Each question carries 14 marks |
||||||
|
|
Module 1 |
|
|||
|
11 |
a) Describe
the waterfall model of software development process with a neat figure. b) Write
a Python script to find the number of digits in the factorial of a given
number.(Use python built-in modules functions) |
9 5 |
|||
|
12 |
a) Write
a program to find the Area of a circle given its circumference b) List
the different types of operators in Python |
7 7 |
|||
|
|
Module 2 |
|
|||
|
13 |
a) Generate the Fibonacci
series upto n.( 0 1 1 2 3 5....n) b) Explain with an
example ,the use of functions and how functions are defined and called in
Python. |
7 7 |
|||
|
14 |
a) Given three points (x1,y1 ) ,(x2,y2) and (x3,y3),
check whether they form a triangle using a python script. b) Explain recursion
with an example and mention the advantages and disadvantages of recursion |
7 7 |
|||
|
|
Module 3 |
|
|||
|
15 |
a)Write a program to
find the median of list of numbers using lists b)Explain any four
set operations in python with examples |
6 8 |
|||
|
16 |
a) Write
a Python code to create a function called frequency that takes a string
and prints the letters in non-increasing order of the frequency of their
occurrences. Use dictionaries. b) Distinguish
between Tuple and Lists |
8 6 |
|||
|
|
Module 4 |
|
|||
|
17 |
a)Illustrate
Polymorphism and Operator overloading. b) Implement a
Complex class to read and display complex numbers with real and imaginary
parts are attributes. Overload + operator to add two complex numbers. |
4 10 |
|||
|
18 |
Explain inheritance
and different forms of inheritance .How they are implemented in Python. |
14 |
|||
|
|
Module 5 |
|
|||
|
19 |
a)Explain any 3
methods of os and sys module. b)Write a Python
program to create a text file. Read the contents of the file, encrypt every
character in the file with a distance of 3 and write it to a new file. Eg:yak
is encrypted as bdn. |
6 8 |
|||
|
20 |
a) Discuss about data
analysis and visualization in Python b)There exist a CSV
file stud.csv with following columns( rno,name,place,mark) of n students.
Write commands to do the following using pandas library. a) Read
and display the content of stud.csv file b) Display
the top 10 rows c) Display
the students list in the order of name d) Display
the students list in the descending order of marks e) Display
the maximum mark and average mark f) Plot
the histogram of mark g) Remove
the column titled place. |
7 7 |
|||
|
||||||
APJ ABDUL
KALAM TECHNOLOGICAL UNIVERSITY THIRD SEMESTER B.TECH DEGREE EXAMINATION, DECEMBER
2020 Course
Code: CST283 Course Name: Python for Machine Learning Max.
Marks: 100 Duration: 3
Hours PART A Answer all questions.
Each question carries 3 marks Marks 1 S=input(‘enter a
name’) .....using input statement N=int(input(‘enter a
number’)).....type conversion 1.5 1.5 2 explanation
of module concept- valid three points use
of module with examples- A
module is a file containing Python definitions and statements. Python
modules have a filename and end with the extension .py. We
can use the module in the following ways: >>>import
math >>>math.sqrt(25) Import
with renaming >>m.sqrt(25) We
can import specific names from a module without importing the module as a
whole. Here is an example. from
math import pi We
can import all names(definitions) from a module using the following
construct: >>>from
math import * # import all names from the standard module math 1.5 1.5 3 Program logic Syntax and
correctness 1.5 1.5 4 Demonstration
of Lambda function Example
In
Python, an anonymous function is a function that is defined without
a name. These
functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create
small anonymous functions. Syntax
of Lambda Function in python lambda
[arg1 [,arg2,.....argn]]:expression #
Program to show the use of lambda functions double
= lambda x: x * 2 print(double(5)) 2 1 5 Program logic Syntax correctness n=int(input("Enter
the number of names....")) 1.5 1.5 6 D[‘c’]=30 D[‘a’]=200 D.pop(‘b’) 1 1 1 7 Class definition Member function
definition 1 2 8 Definition Handling
exception Example What is
Exception? try: You do your operations here; ...................... except
ExceptionI: If there is ExceptionI, then execute this
block. except
ExceptionII: If there is ExceptionII, then execute this
block. ...................... else: If there is no exception then execute this
block. For example,
we might prompt the user for the name of a file and then try to open it. If
the file doesn’t exist, we don’t want the program to crash; we want to handle
the exception: else:
f.close() As
previously mentioned, the portion that can cause an exception is placed
inside the try block. 1 1 1 9 Creating
numpy arrays Indexing/slicing Sorting import
numpy as np A
= np.array([[1, 2, 3], [3, 4, 5]]) Indexing/slicing A=np.array([[1,2,3],[4,5,6],[7,8,9]]) print(A[2]) [7
8 9] print(A[2,2]) 9 9 print(A[1:,1:]) [[5
6]
[8 9]] print(A[:2,1:]) [[2
3]
[5 6]] A.sort() will sort
the array elements 1 1 1 10 from
matplotlib import pyplot as plt import
numpy as np import
math #needed for definition of pi x
= np.arange(0, math.pi*2, 0.05) y
= np.sin(x) plt.plot(x,y) plt.xlabel("angle") plt.ylabel("sine") plt.title('sine
wave') plt.show() 3 PART B Answer any one full question from each
module. Each question carries 14 marks
Module 1 11 a)Explanation- Fig There is much more to programming than
writing lines of code.Computer Engineers refer to the process of planning and
organizing a program as Software Development. There are several
approaches to software development.One version is known as
the waterfall model. The
waterfall model consists of several phases: 1.Customer
request:In this phase, the programmer receives a broad statement a problem to
be solved. This is the user requirement specification phase. 2.Analysis: Determines
what the program will do. This is viewed as the process of clarifying the
specification for the problem. 3.Design: Determines
how the program will do the task 4.Implementation: The
programmers write the program. This step is also called coding phase. 5.Integration: Large
programs have many parts. In the integration phase, these parts are brought
together into a smoothly functioning system as a whole. 6.
Maintenance: Programs usually have a long life, a span of 5-15 years is common.
During this time, requirements change, errors are detected and minor or major
modifications are made. b) import math n=int(input('enter a
number')) f=math.factorial(n) print("factorial=",f) print("number of
digits",len(str(f))) 6+2
1 5 12 a) Circumference=
2*pi*r compute
r from this area=2*pi*r b) Arithmetic
Operators 7 7
Module 2 13 a)logic syntax and correctness hint: sort the list
and get the middle value b)Functions and use Function definition/calling example The
following are the two simple reasons to write a function Creating
a new function gives you an opportunity to name a group of statements.
Functions can simplify a program by hiding a complex computation behind
a single command. Creating
a new function can make a program smaller by eliminating repetitive code. Syntax
of Function def
function_name(parameters): """docstring"""
statement(s)
[ return value(s)/expression] 4 3 4 3 14 a)logic syntax
and correctness b)definition
example advantages
and disadvantages Recursion
is a method of solving problems that involves breaking a problem down into smaller and smaller sub
problems until you get to a small enough 4problem so that it can be solved trivially.
Usually recursion involves a function calling itself. While it may not seem
like much on the surface, recursion allows us to write elegant solutions to
problems that may otherwise be very difficult to program. Advantages of
recursion 4 3 1 2 4
Module 3 15 a) logic syntax
and correctness b) >>>
A={3,2,1,4} >>>
A.add(5) >>>
A {1,
2, 3, 4, 5} >>>
B=A.copy() >>>
B {1,
2, 3, 4, 5} >>>
B.clear() >>>
B set() >>>
A {1,
2, 3, 4, 5} >>>
A.discard(5) >>>
A {1,
2, 3, 4} >>>
A.update({5,6}) >>>
A {1,
2, 3, 4, 5, 6} >>>
B={1,2} >>>
B.issubset(A) True >>>
A.union(B) {1,
2, 3, 4, 5, 6} >>>
A.intersection(B) {1,
2} >>>
A.difference(B) {3,
4, 5, 6} 3 3 4*2 16 a) logic,
syntax, correctness def
list_of_frequency(s):
d=dict()
for c in s:
d[c]=d.get(c,0)+1
print("letter count in the decresing order")
l=list(d.items())
l.sort(key=lambda x:x[1],reverse=True)
print(l) s=input("Enter
the string…..") list_of_frequency(s) b) any
valid 3 points Definition difference Mutability indexing 4+2+2 6
Module 4 17 a)definition of
polymorphism and operator overloading b)class defn member function to
read member function to
display overloaded + operator
( _add_ function) 2+2 2 2 2 4 18 Illustration of
inheritance Different types Sample Python code
showing different types of inheritance 3 3 8
Module 5 19 a)3 os functions 3 sys function b)opening file reading file encryption writing file closing file 3 3 1 1 4 1 1 20 a) Illustration
of plotting library matplotlib Illustration
of numpy and pandas b)import pandas as pd df =
pd.read_csv("stud.csv") print(df) print(df.head(10)) print(df.sort_values(by='name')) print(df.sort_values(by='mark',ascending=False)) print(df['mark'].max(),df['mark'].mean()) import
matplotlib.pyplot as plt plt.hist(df['mark']) df.drop(['place'],axis=1,inplace=True) print(df) 3 4 7*1=7
We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide re usability of code.
We can define our most used functions in a module and import it, instead of
copying their definitions into different programs.
>>>import math as m
# import only pi from math module
Lambda functions can have any number of arguments but only one expression.
The expression is evaluated and returned. Lambda functions can be used
wherever function objects are required.
Example of Lambda Function in python
Here is an example of lambda function that doubles the input value.
names=[]
print("Enter {} names".format(n))
for i in range(n):
nam=input()
names.append(nam)
names.sort()
print("names in alphabetical order")
for nam in names:
print(nam)
An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a
Python script encounters a situation that it cannot cope with, it raises an
exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can defend
your program by placing the suspicious code in a try: block. After the try:
block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks
filename =input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print ('There is no file named', filename)
print(A[2][2])
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems using recursion.
Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of recursion
Sometimes the logic behind recursion is hard to follow through.
Recursive calls are expensive (inefficient) as they take up a lot of memory
and time.
Recursive functions are hard to debug.
Comments
Post a Comment