0% found this document useful (0 votes)
15 views12 pages

cst362 Draft Scheme

Uploaded by

ktusemester
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)
15 views12 pages

cst362 Draft Scheme

Uploaded by

ktusemester
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/ 12

lOMoARcPSD|31948820

CST362- Draft Scheme

Computer Science and ENgineering (APJ Abdul Kalam Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by DAMU GAMING ([email protected])
lOMoARcPSD|31948820

0300CST362052201

DRAFT Scheme of Valuation/Answer Key


(Scheme of evaluation (marks in brackets) and answers of problems/key)
APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY
SIXTH SEMESTER B.TECH DEGREE EXAMINATION, JUNE 2022
Course Code: CST362
Course Name: PROGRAMMING IN PYTHON
Max. Marks: 100 Duration: 3 Hours
*General Instructions :
Programming questions may be answered in different ways. The given answers are for reference.
PART A
Answer all questions, each carries 3 marks. Marks

1 Analysis and design provide detailed blueprints for coding a system. Without (3)
these blueprints, it may be difficult to determine whether the system will do
what it is supposed to do, and it may be difficult to minimize errors in the code
and structure it in a way that eases maintenance. (Similar explanation may
give marks)
2 i) 13 ii) 2 iii) 6 (3)
3 Cmue (3)
retupmoC
Computer

4 def gcd(a,b): (3)


if (b == 0):
return a
else:
return gcd(b,a%b)
5 i) turtle.setheading(0) - Turn turtle to face east (3)
ii)turtle.forward(50) - Draw a line /move forward 50 units
iii) turtle.left(90) – Turn left 90 degrees
6 Any two differences (2 * 1.5 ) (3)
7 Many built-in Python classes usually include an __ str __ method. This method (3)
builds and returns a string representation of an object’s state. When the str function
is called with an object,that object’s __ str __ method is automatically invoked to
obtain the string that str returns. For example, the function call str(s) is equivalent

Page 1of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

to the method call s. __ str __ () , and is simpler to write. The function call print(s)
also automatically runs str(s) to obtain the object’s string
representation for output.
8 When you inherit a child class from more than one base classes, that situation is (3)
known as Multiple Inheritance. When you inherit a class from a derived class,
then it’s called multilevel inheritance. And, it can go up any levels in Python.
9 [[0 2] (3)
[2 4]
[4 6]]

10 loc selects rows and columns with specific labels and iloc selects rows and columns (3)
at specific(implicit) integer positions . - 1 mark
Example – 2 marks

PART B
Answer one full question from each module, each carries 14 marks.
Module I
11 a) import math (7)
n = int(input('Enter the value of n :'))
x = float(input('Enter the degree :'))
d=x
x = math.radians(x)
s=1
t=1
i=1
for i in range(1,n):
t = ((-t * x * x)/((2*i)*(2 * i - 1)))
s=s+t
print ('cos(',d,') = %0.2f' % s)
b) x = int(input("Enter the value of x: ")) (7)
y = int(input("Enter the value of y: "))
product = 1
for count in range(y):
product = product * x
print(product, end = " ")

Page 2of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

print("\n")
print("product = ", product )
OR
12 a) n = int(input(“Entter the value of n : “) (7)
for i in range(1,n+1):
for j in range(1, i+1):
print(chr(64+j),end=" ")
print()
b) print ('Enter the range :') (7)
a = int(input('Enter the lower range :'))
b = int(input('Enter the upper range :'))
for i in range(a,b+1):
prime = True
j=2
while (j <= i/2):
if (i % j == 0):
prime = False
break
j=j+1
if (prime):
print (i, end = ' ')
Module II
13 a) a. data.split() (6)
b. data.upper()
c. data.index("rules")
d. data.replace("!", "?")
4 * 1.5 = 6 marks
b) count = 0 (8)
inputFile = open("myfile.txt", 'r')
for line in inputFile:
wordlist = line.split()
for word in wordlist:
if len(word) == 4:
count += 1
print("There are", count, "four-letter words.")
OR
14 a) f = open(“numbers.txt”, 'r') (10)

Page 3of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

numbers = []
for line in f:
words = line.split()
for word in words:
numbers.append(float(word))

# Sort the list and print the number at its midpoint


numbers.sort()
midpoint = len(numbers) // 2
print("The median is", end=" ")
if len(numbers) % 2 == 1:
print(numbers[midpoint])
else:
print((numbers[midpoint] + numbers[midpoint - 1]) / 2)
b) numbers = [1,-2,3,-4] (4)
list(filter(lambda x: x > 0, numbers))

Module III
15 a) from turtle import Turtle (5)
def square(t, length):
#Draws a square with the given length.
for count in range(4):
t.forward(length)
t.left(90)
b) def blackAndWhite(image): (9)
"""Converts the argument image to black and white."""
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
average = (r + g + b) / 3
if average < 128:

Page 4of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

image.setPixel(x, y, blackPixel)
else:
image.setPixel(x, y, whitePixel)

def main(filename = "smokey.gif"):


image = Image(filename)
print("Close the image window to continue. ")
image.draw()
blackAndWhite(image)
print("Close the image window to quit. ")
image.draw()

main()
OR
16 a) def hexagon(t, length): (5)
#Draws a hexagon with the given length.
for count in range(6):
t.forward(length)
t.left(60)
b) def shrink(image, factor): (9)
"""Builds and returns a new image which is smaller
copy of the argument image, by the factor argument."""
width = image.getWidth()
height = image.getHeight()
new = Image(width // factor, height // factor)
oldY = 0
newY = 0
while oldY < height - factor:
oldX = 0
newX = 0
while oldX < width - factor:
oldP = image.getPixel(oldX, oldY)
new.setPixel(newX, newY, oldP)

Page 5of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

oldX += factor
newX += 1
oldY += factor
newY += 1
return new

def main(filename = "smokey.gif"):


image = Image(filename)
print("Close the image window to continue. ")
image.draw()
image2 = shrink(image, 2)
print("Close the image window to continue. ")
image2.draw()
image3 = shrink(image, 3)
print("Close the image window to continue. ")
image3.draw()
print("Close the image window to quit. ")

main()
Module IV
17 a) from math import sqrt (9)
class Complex:
def __init__(self, real, imag):
self.re = real
self.im = imag

def __add__(self, o):


return Complex(self.re+o.re, self.im+o.im)

def __mul__(self, o):


return Complex(self.re*o.re-self.im*o.im, self.re * o.im + self.im * o.re)

def __str__(self):

Page 6of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

if self.im == 0:
return '%.2f' % self.re
if self.re == 0:
return '%.2fi' % self.im
if self.im < 0:
return '%.2f - %.2fi' % (self.re, -self.im)
else:
return '%.2f + %.2fi' % (self.re, self.im)

def solve(comp1, comp2):


print(comp1 + comp2)
print(comp1 * comp2)

comp1 = Complex(2, 2)
comp2 = Complex(5, 3)
solve(comp1, comp2)
b) Multiple inheritance – Explanation – 2 marks (5)
Example : 3 marks
OR
18 a) class Rational(object): (9)
"""Represents a rational number."""

def __init__(self, numer, denom):


"""Constructor creates a number with the given numerator
and denominator and reduces it to lowest terms."""
self._numer = numer
self._denom = denom
self._reduce()

def numerator(self):
"""Returns the numerator."""
return self._numer

Page 7of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

def denominator(self):
"""Returns the denominator."""
return self._denom

def __str__(self):
"""Returns the string representation of the number."""
return str(self._numer) + "/" + str(self._denom)

def _reduce(self):
"""Helper to reduce the number to lowest terms."""
divisor = self._gcd(self._numer, self._denom)
self._numer = self._numer // divisor
self._denom = self._denom // divisor

def _gcd(self, a, b):


"""Euclid's algorithm for greatest common divisor."""
if (b == 0):
return a
else:
return self._gcd(b, a%b)

# Methods for arithmetic and comparisons go here

def __add__(self, other):


"""Returns the sum of the numbers."""
newNumer = self._numer * other._denom + \
other._numer * self._denom
newDenom = self._denom * other._denom
return Rational(newNumer, newDenom)

def __lt__(self, other):


"""Returns self < other."""

Page 8of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

extremes = self._numer * other._denom


means = other._numer * self._denom
return extremes < means
b) An exception is an event, which occurs during the execution of a program (5)
and disrupts the normal flow of execution. When a program raises an exception,
it must handle exception or the the program will be terminated. - 2 marks
try:
file = open("sample.txt",'w')
try:
file.write("Hello Good morning")
finally:
print("Closing file")
file.close()
except IOError:
print("Error while reading") - 3marks
Module V
19 a) from os import getcwd, listdir (5)
dirList = listdir(getcwd())
for name in dirList:
print(name)
b) arr1 = np.random.randint(0,20,(3,3)) (9)
arr2 = np.random.randint(0,20,(3,3))
print(arr1)
print(arr2)
print("Resultant matrix after addition :")
arr3 = arr1 + arr2
print(arr3)
print("Resultant matrix after multiplication :")
arr4 = np.dot(arr1,arr2)
print(arr4)
print("Resultant matrix after Transpose")
arr5 = arr4.T
print(arr5)

Page 9of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

OR
20 a) import csv (4)

# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
import csv
# data rows of csv file
rows = [ ['Nikhil', 'CSE', '2', '9.0'],
['Sanchit', 'CSE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'IT', '1', '9.5'] ]
filename = "student.csv"

# writing to csv file


with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)

# writing the fields


csvwriter.writerow(fields)

# writing the data rows


csvwriter.writerows(rows)
b) import numpy as np (10)
import panda as pd
df = pd.read_csv("student.csv")
1. #To find the average CGPA of students
avg = np.mean(df['CGPA'])
print("Average CGPA = %0.2f" %avg)
2. #To display Name and CGPA of students having CGPA > 9
df[df['CGPA'] >= 9][['Name','CGPA']]
3. # To display the details of all CSE students with CGPA > 9
df[(df['Branch'] == 'CSE') & (df['CGPA'] >= 9)]

Page 10of 11

Downloaded by DAMU GAMING ([email protected])


lOMoARcPSD|31948820

0300CST362052201

4. #To display the details of student with maximum CGPA


df[df['CGPA'] == np.max(df['CGPA'])]
5. #To display average CGPA of each branch
df.groupby('Branch')['CGPA'].mean()

[5 * 2 = 10 marks]

****

Page 11of 11

Downloaded by DAMU GAMING ([email protected])

You might also like