0% found this document useful (0 votes)
8 views13 pages

PYQ1

The document outlines the examination structure for the Python for Machine Learning course at APJ Abdul Kalam Technological University, detailing various programming tasks and theoretical questions across multiple modules. Each question is assigned specific marks, covering topics such as print statement formats, math module functions, recursion, exception handling, and data manipulation using libraries like NumPy and Pandas. The exam format includes both short answer questions and programming tasks, emphasizing practical coding skills and theoretical understanding.

Uploaded by

Aann Mariya Sabu
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)
8 views13 pages

PYQ1

The document outlines the examination structure for the Python for Machine Learning course at APJ Abdul Kalam Technological University, detailing various programming tasks and theoretical questions across multiple modules. Each question is assigned specific marks, covering topics such as print statement formats, math module functions, recursion, exception handling, and data manipulation using libraries like NumPy and Pandas. The exam format includes both short answer questions and programming tasks, emphasizing practical coding skills and theoretical understanding.

Uploaded by

Aann Mariya Sabu
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/ 13

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 3
dictionary.

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 3


member function findArea() to compute and display the area of triangle.

8 Distinguish between accessors and mutators 3

9 Explain the following functions from os module 3

getcwd() listdir() walk()

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

Module 1

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

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

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

b)Discuss about identifiers , variables and keywords in Python

Module 2
13 a) Write a Python program to print all prime numbers less than 1000. 7

b) Illustrate recursion and recursive function with a suitable example

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

b) Demonstrate the use of Lambda function with an example

Module 3

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

b) Explain any four Set operations in python with examples

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

Hint: use set for efficient implementation

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

Module 4

17 a)Explain the concept of operator overloading 4

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.

10

18 a)Discuss the exception handling mechanism in Python with examples 8

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

Module 5

19 a)Illustrate numpy arrays with example. How indexing, slicing and sorting is done with 6
examples
b)Write a python program to read numbers from a file named num.txt.Write all 8
positive numbers from num.txt to a file named positive.txt and all negative numbers to
a file negative.txt.

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

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.
8
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’

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") 3

print("x=%d"%x)
print("{} {}".format(x,y))

2 Use of math module and 3 functions 1*3

3 Extract digits 1

Check for even 1

Correctness and printing sum 1

4 Function advantage 1

Example 2

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]

5 Logic 2

Correctness 1

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)

6 Any valid 3 points 3

Definition difference
Mutability

indexing

7 Class defn 1

Constructor 1

Member function 1

8 Explanation 2

Example 1

9 1 mark each for explanation 1*3

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

10 Use of matplotlib 2

Correctness and syntax 1

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

PART B

Answer any one full question from each module. Each question carries 14 marks

Module 1

11 a) Explanation- 6+2

Fig 1

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

12 a)use distance formula to compute radius r 3

compute area and print 3

syntax and correctness 1

b) identifiers

variables

keywords 3

Module 2

13 a)explanation of recursion and recursive functions 4


example 3

b)logic

syntax and correctness 4

14 a) Logic 5

Syntax and correctness 2

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. 5+2

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

Module 3
15 a)logic 4

Syntax and correctness 2

b)

>>> A={3,2,1,4}

>>> A.add(5) 4*2

>>> 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}
16 a)logic + syntax + correctness 4+2+2

b)

from datetime import date 3*2

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

Module 4

17 a) Operator overloading is another kind of polymorphism. Python operators work for 4


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
2
display function
2

18 a) Definition 2

Handling exception 4

Example 2

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
2

Module 5

19 a)

Creating numpy arrays 2

Indexing/slicing 2

Sorting 2

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

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


2
opening/closing files
2
2

20 a)Any 4 operations 1.5*4

b) import pandas as pd

df = pd.read_csv("student.csv") 1*8

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy