Python For Machine Learning - CST 283 - KTU Minor Sample Question Paper and Answer Key Dec 2021

 

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

 

Duration: 3 Hours

 

Answer all questions. Each question carries 3 marks

Marks

1

Describe any three formats used with print statement

3

2

Explain with example the usage of any three methods from math module.

3

3

Write a Python program to find the sum of even digits in a number

3

4

Illustrate the use of functions with an example

3

5

Write a Python program to find the frequency of each word in a string using dictionary.

3

6

Distinguish between List and Tuple

3

7

Write a Python class Triangle with a constructor to initialize 3 sides(a,b,c) and a member function findArea() to compute and display the area of triangle.

3

8

Distinguish between accessors and mutators

3

9

Explain the following functions from os module

getcwd()      listdir()    walk()

3

10

Write Python code to plot histogram of marks of students stored in a list L, with proper title, xlabel and ylabel using matplotlib library.

3

 

                                                        Module 1

 

11

a) Describe the waterfall model of software development process with a neat figure.

b)Write a Python script to find nCr .Use math module to find the factorial

9

 

 

5

12

a)Area of the circle given center point (x1,y1) and one point on the perimeter (x2,y2).

b)Discuss about identifiers , variables and keywords in Python

7

 

 

7

 

                                                        Module 2

 

13

a) Write a Python program to print all prime numbers less than 1000.

b) Illustrate recursion and recursive function with a suitable example

7

 

7

14

a) Write a Python program to convert a binary string to decimal

b) Demonstrate the use of Lambda function with an example

7

 

7

 

                                                        Module 3

 

15

a) Write a Python program to read list of positive integers into a list and separate the prime and composite numbers into two different list.

b) Explain any four Set operations in python with examples

6

 

 

8

16

a)Write a program to remove all duplicate elements from a list.( do not keep any copy of the repeating element)

Hint: use set for efficient implementation

b) Explain any 3 formats to print current date in Python

8

 

 

 

 

6

 

                                                        Module 4

 

17

a)Explain the concept of operator overloading

b)Implement a class Point which represent a point (x,y) in Cartesian coordinate. Use a constructor to initialize a point object and a member function to display the object values. Overload + operator to add two point object.

4

 

 

 

10

18

a)Discuss the exception handling mechanism in Python with examples

b)Distinguish between function overloading and function over riding with examples

8

 

6

 

                                                        Module 5

 

19

a)Illustrate numpy arrays with example. How indexing, slicing and sorting is done with examples

b)Write a python program to read numbers from a file named num.txt.Write all positive numbers from num.txt to a file named positive.txt and all negative numbers to a file negative.txt.

6

 

 

8

20

a) Explain how the matrix operations are done using numpy arrays

b)There exist a CSV file ‘student.csv’ with the following columns(rno,name,m1,m2,m3 ). Write commands to do the following using pandas library.

a)Read and display the first 10 rows of CSV file

b)Display the rno and name in the sorted order of name

c)Add a new column total(m1+m2+m3) to the data frame

d)Display rno,name and total marks of all the students in the descending order of total marks

e)Find the mean and variance of mark m1

f)Find the highest and lowest mark in m2.

g)Plot the marks m3 against name

h) store the data frame in a new CSV file ‘studentnew.csv’

 

6

 

8


 

Scheme of Valuation/Answer Key

Scheme of evaluation (marks in brackets) and answers of problems/key

 

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

print("test")

print("x=%d"%x)

print("{} {}".format(x,y))

3

 

2

Use of math module and 3 functions

1*3

 

3

Extract digits

Check for even

Correctness and printing sum

1

1

1

 

4

Function advantage

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]

 

1

2

 

5

Logic

Correctness

S=input("Enter the string…..")

S=S.split(" ") #splitting it into words

d=dict()

for w in S:

    d[w]=d.get(w,0)+1

print("word count")

print(d)

 

2

1

 

6

Any valid 3 points

Definition difference

Mutability

indexing

3

 

7

Class defn

Constructor

Member function

1

1

1

 

8

Explanation

Example

2

1

 

9

1 mark each for explanation

Function os.getcwd(), returns the Current Working Directory(CWD) of the file used to execute the code, can vary from system to system.

os.listdir()

To print files and directories in the specified directory  on your system 

The method walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up

1*3

 

10

Use of matplotlib

Correctness and syntax

L=[10,20,30,30,30,40,50,70]

import matplotlib.pyplot as plt

plt.xlabel('mark')

plt.ylabel('frequency')

plt.title('Histogram')

plt.hist(l)

plt.show()

2

1

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)Use of math module

Computation of factorial

Compute nCr and print

6+2

1

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1

2

2

 

12

a)use distance formula to compute radius r

compute area and print

syntax and correctness

b) identifiers

   variables

   keywords

3

3

1

 

 

3

2

2

 

 

                                                        Module 2

 

 

13

a)explanation of recursion and recursive functions

example

b)logic

syntax and correctness

4

3

 

4

3

 

14

a)      Logic

Syntax and correctness

bitstring=input("Enter a binary number...")
decno=0
expnt=len(bitstring)-1
for bit in bitstring:
    decno=decno+int(bit)* 2 ** expnt
    expnt=expnt-1
print ("The decimal number is=", decno)

 

b) demonstration + 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


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.

# Program to show the use of lambda functions 

double = lambda x: x * 2

print(double(5))

 

5

2

 

 

 

 

 

 

 

 

 

5+2

 

 

                                                        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}

 

4

2

 

 

4*2

 

16

a)logic + syntax + correctness

b)

from datetime import date

today = date.today()

# dd/mm/YY

d1 = today.strftime("%d/%m/%Y")

print("d1 =", d1)

 

# Textual month, day and year          

d2 = today.strftime("%B %d, %Y")

print("d2 =", d2)

 

# mm/dd/y

d3 = today.strftime("%m/%d/%y")

print("d3 =", d3)

 

# Month abbreviation, day and year  

d4 = today.strftime("%b-%d-%Y")

print("d4 =", d4)

outputs

d1 = 12/09/2020

d2 = September 12, 2020

d3 = 09/12/20

d4 = Sep-12-2020

 

4+2+2

 

3*2

 

 

                                                        Module 4

 

 

17

a) Operator overloading is another kind of polymorphism. Python operators work for built-in classes. But the same operator behaves differently with different types. For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

 

This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading.

b)class defn

constructor

overloaded + operator

display function

4

 

 

 

 

 

 

 

2

2

4

2

 

18

a) Definition

Handling exception

Example

 

What is Exception?
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 

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:


filename =input('Enter a file name: ')
try:
    f = open (filename, "r")
except IOError:
    print ('There is no file named', filename)

else:

    f.close()

 

As previously mentioned, the portion that can cause an exception is placed inside the try block.

b)      Explanation

Example overloading issues

Example overriding         

2

4

2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2

2

2

 

 

                                                        Module 5

 

 

19

a)

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
print(A[2][2])

9

print(A[1:,1:])

[[5 6] 

     [8 9]]

 

print(A[:2,1:])

[[2 3] 

    [5 6]]

A.sort() will sort the array elements

 

b) reading file

writing positive numbers

writing negative numbers

opening/closing  files

 

2

2

2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2

2

2

2

 

20

a)Any 4 operations

b) import pandas as pd

df = pd.read_csv("student.csv")

print(df.head(10))

print(df.sort_values(by='name')[['rno','name']])

df['total']=df['m1']+ df['m2']+ df['m3']

print(df)

print(df.sort_values(by='total',ascending=False)[['rno','name','total']])

print(df['m1'].mean(),df['m1'].var())

print(df['m2'].min(),df['m2'].max())

import matplotlib.pyplot as plt

plt.plot(df['name'],df['m3'])

df.to_csv('studentnew.csv')

1.5*4

 

1*8

 


Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

46.Classes and Objects in Python- Accessors and mutators

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020