[go: up one dir, main page]

0% found this document useful (0 votes)
194 views39 pages

Wa0002 PDF

This document provides the previous questions with answers of Computing and Problem Solving for the first semester B.Tech degree examination from January 2016. It includes 14 multiple choice and short answer questions related to topics like I/O devices, buses, flowcharts, algorithms, variables, functions, files and more. Sample code and explanations are provided for all questions.

Uploaded by

Sreenath Sree
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)
194 views39 pages

Wa0002 PDF

This document provides the previous questions with answers of Computing and Problem Solving for the first semester B.Tech degree examination from January 2016. It includes 14 multiple choice and short answer questions related to topics like I/O devices, buses, flowcharts, algorithms, variables, functions, files and more. Sample code and explanations are provided for all questions.

Uploaded by

Sreenath Sree
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/ 39

KTU B-Tech Questions

A complete Solution for B.Tech…..

ass Get Class Gmat Info. Metasearch &


Social Results Now.
mat » info.com

HOME SOLVED_QUESTIONS QUESTION BANK SYLLABUS

STUDY MATERIALS KTU NEWS RESULTS TIME TABLE

ary examination timetable june/july 2016::: KTU B.Tech Transfer Details Published::: Model Question for

Class Gmat »
info.com

Get Class Gmat Info. Metasearch &


Social Results Now.

KTU PREVIOUS QUESTIONS WITH


ANSWERS OF COMPUTING AND
PROBLEM SOLVING
One comment
KTU Previous Questions with
answers of Computing and
Problem Solving
Reg. No:
………….
Name…………………..

FIRST SEMESTER B.TECH DEGREE


EXAMINATION, JANUARY 2016

Course Code: BE 101-05

Course Name: INTRODUCTION TO


COMPUTING AND PROBLEM SOLVING

Max Marks: 100


Duration:3 hrs

PART A

Answer all questions, each question carries


4 marks (40 marks)

1. a). Name any 3 Optical input devices.

ANS:

bar code readers, image scanners, optical


character recognition

b). Name the different I/O ports used in a


computer.

ANS:

USB

The Universal Serial Bus (USB) port is the


most versatile interface used on modern
computers. USB ports can be used to
connect mice, keyboards, printers,
scanners, Cameras, external hard drives,
network switches, and more.

DVI
The DVI port is used for video on newer
monitors.

Network/Ethernet (RJ-45)

The port used for networking on most


modern computers is typically referred to
as an Ethernet port,but may also be called
a RJ-45 jack, network port, or Cat5 part.

c). Define System software with an


example.

ANS:

System software is a type of computer


program that is designed to run a
computer’s hardware and application
programs. If we think of the computer
system as a layered model, the system
software is the interface between the
hardware and user applications.

Eg: Microsoft Windows ,Linux, Unix, Mac


OSX,DOS

2. Write a notes on buses.

ANS:

A bus, in computing, is a set of physical


connections (cables, printed circuits,
etc.) which can be shared by multiple
hardware components in order to
communicate with one another.

–>The address bus (sometimes called the


memory bus) transports memory
addresses which the processor wants to
access in order to read or write data.

It is a unidirectional bus.

–>The data bus transfers instructions


coming from or going to the processor. It
is a bidirectional bus.

The control bus (or command bus)


transports orders and synchonisation
signals coming from the control unit and
travelling to all other hardware
components.

–> It is a bidirectional bus, as it also


transmits response signals from the
hardware.

3. Draw the flow chart to find out the


greatest of three numbers. (2)

ANS:

Flow chart for finding greatest from three numbers

ktubtechquestions.com

4. Differentiate between top down and


bottom up problem solving strategies (2)

ANS:
Top-down Approach

A top-down approach (also known as


stepwise design) is essentially the
breaking down of a system to gain insight
into the sub-systems that make it up. In a
top-down approach an overview of the
system is formulated, specifying but not
detailing any first-level subsystems.
topdown – of an approach to a problem
that begins at the highest conceptual
leveland works down to the details; “a top-
down analysis might begin by looking at
macro-economic trends”; “top-down
programming”

Start from given data or observations,


derive other data or observations.
Use derived data together with given
data to derived more data.
Eventually, the desired conclusions can
be reached.

Bottom-up Approach

Bottom-up processing as an approach


wherein there is a progression from the
individual elements to the whole.

An approach to a problem that begins wit


h details and works up to thehighest conce
ptual level; “bottom-up parser”; “a bottom-
up model of the reading process”

The bottom-up approach helps thinking


because the objective is clear.
The top-down approach is effective for
doing numerical computation from given
data.
Alternating between the two
approaches is an effective strategy for
thinking.
Drawing the data-flow diagrams while
solving problem helps thinking by clearly
identifying the given data, derived data,
and desired objectives.

5.Write an algorithm to compute 1-x^2/2!+


x^4/4!- x^6/6!+……..n terms..(2)

ANS:

Step 1: Start

Step 2: Read x, n values as integers

Step 3: Set i = 2, s = 1, pwr = 1, nr = 1

Step 4: Convert x1 into degrees

Step 5: Assign x1 as sum

Step 6: while (i <= n)

begin

pwr ← pwr + 2;

dr ← dr * pwr * (pwr – 1);

sum ← sum + (nr DIV dr) * s;

s ← s * (-1);

nr ← nr * x1 * x1;

i ← i + 2;

end

Step 7: Print sum

Step 8: Stop

6.which of the following is a valid variable


name in python ? (1)

a) i) 12xyz ii) break iii)A_123 iv) A?B?C

ANS:
A_123

b)Evaluate the expression x**y**z given


x=2,y=3,z=2 (1)

ANS:

2**3**2 = 64

c) Predict the output of following code: (1)

for i in range (10,-1,-2);

print i

ANS:

10,8,6,4,2,0

7.write a python program to find the sum


of all even terms in a group of n numbers
entered by user. (3)

ANS:

beg = 0

end = 0

sum = 0

n=0

print “Enter Starting Number:”,

beg = input()

print “Enter Ending Number:”,

end = input()

n = beg

if ( (n % 2) == 1):

n += 1

print “Adding Numbers : “,

while(n <= end):


print n,

sum += n

n += 2

print “\nThe result is: “, sum

8. Show how you will use the cosine() and


log () functions in your program with the
help of an example. (2)

ANS:

log()

math.log(x,[ base])

With one argument, return the natural


logarithm of x (to base e).

With two arguments, return the logarithm


of x to the given base, calculated as log

(x)/log(base).

math.log1p(x)

Return the natural logarithm of 1+x (base


e). The result is calculated in a way which
is

accurate for x near zero.

math.log10(x)

Return the base-10 logarithm of x. This is


usually more accurate than log(x, 10).

cosine()

math.cos(x)

Return the cosine of x radians.

9.What will be the output of this program?


Briefly explain the working of this code.

ANS:
Def check(x,y):

If y ==0;

Print ‘error’

Return

Else:

Return x/y

a,b =10,5

Print check(a,b)

In the above program check (a,b) is


passes check two values: 10 and 5. The
function check receives copies of these
values and accesses them by the
identifiers: x and y. value of y is 5 so
control passes to else part and return 10/5
= 2.so the answer is 2.

10.Write a Python program to compute the


nth Fibonacci number . Use a recursive
function for the implementation.

ANS:

# Python program to display the n-th fibonacci


number using recursive functions

def recur_fibo(n):

“””Recursive function to

print Fibonacci number”””

if n <= 1:

return n

else:

return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user

nterms = int(input(“enter the value of ‘N’ “))

# check if the number of terms is valid

if nterms <= 0:

print(“Plese enter a positive integer”)

else:

for i in range(nterms):

f= recur_fibo(i)

print(“The nth fibonacci number”,f)

11.Let fruit =’apples’ be a string. What will


be the output of the following expressions:
(2)

i)Len(s1) ii) s1[0:4] iii) s1[6] iv) s1[-4]

ANS:

fruit=’apples’

i) len(s1)=6

ii) s1[0:4]=apple

iii) s1[6]=s

iv) s1[-4]=p

12.Let data represent the list


[‘circle’,’square’,’triangle’]. Write the
expression for following operations: (3)

i) Replace the value ‘circle’ with ‘ellipse’

ii) Add a new value’rectangle’ top end of list

iii) Remove the value ‘square’ and ‘triangle’


from list

ANS:
list=[‘circle’,’square’,’triangle’]

i) list[0] = ‘ellipse’

ii) append(‘rectangle’)

iii) list.remove(‘square’)

iv) remove(‘triangle’)

13.Let Farm={‘Sheep’:5,’cows’:2,’goats’:10}
be a dictionary . write the statements for
following operations. (3)

i)To add the key value pair (Ducks’:8)

ii)to display the number of items in the


dictionary.

iii)to remove the key value pair (cows’:2)

farm={‘Sheep’:5,’cows’:2,’goats’:10}

i) farm[‘Ducks’] =8

ii) len[farm]

iii)del farm[‘cows’]

14.Write the syntax for opening a file in


python. Give one example. (2)

To open a file for writing use the built-i open()


function. open() returns a

file object, and is most commonly used with


two arguments.

The syntax is:

file_object = open(filename, mode) where


file_object is the variable to put thefile object.

The second argument describes the way in


which the file will be used.

open() returns a file object, and is most


commonly used with two arguments:
open(filename, mode).
>>> f = open(‘workfile’, ‘w’)

>>> print f

<open file ‘workfile’, mode ‘w’ at 80a0960>

The first argument is a string containing the


filename. The second argument is another
string containing a few characters describing
the way in which the file will be used.mode
can be ‘r’ when the file will only be read, ‘w’ for
only writing (an existing file with the same
name will be erased), and ‘a’ opens the file for
appending; any data written to the file is
automatically added to the end. ‘r+’ opens the
file for bothreading and writing. The mode
argument is optional; ‘r’ will be assumed if it’s
omitted.

15.what do you mean by pickling in python?


Explain its significance with the help of
example. (3)

pickling is used for serializing and de-


serializing a Python object structure. Anyobject
in python can be pickled so that it can be
saved on disk. What pickle does is thatit
“serialises” the object first before writing it to
file. Pickling is a way to convert a python
object (list, dict, etc.) into a character stream.
The idea is that this characterstream contains
all the information necessary to reconstruct
the object in another

python script.

import pickle

pickle has two main methods. The first one is


dump, which dumps an object to a file

object and the second one is load, which loads


an object from a file object.

import pickle

a = [‘test value’,’test value 2′,’test value 3′]

[‘test value’,’test value 2′,’test value 3′]

file_Name = “testfile”

# open the file for writing

fileObject = open(file_Name,’wb’)

# this writes the object a to the

# file named ‘testfile’

pickle.dump(a,fileObject)

# here we close the fileObject

fileObject.close()

# we open the file for reading

fileObject = open(file_Name,’r’)

# load the object from the file into var b

b = pickle.load(fileObject)

[‘test value’,’test value 2′,’test value 3′]

a==b

True

The pickle module keeps track of the objects it


has already serialized, so that laterreferences
to the same object won’t be serialized again

pickle can save and restore class instances


transparently, however the class

definition must be importable and live in the


same module as when the object was

stored.

16.When does an exception occur during


program execution? How are

exception handled in python? Explain with


Examples. (3)

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 eception. 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:

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.

PART B

KTU Previous Questions with answers


of Computing and Problem Solving
(Answer any 4 complete questions each
having 8 marks)

17.(a) Draw and Explain instruction


execution cycle in a computer.

ktubtechquestions.com
FETCH

The first step the CPU carries out is to fetch


some data and instructions (program) from
main memory then store them in its own
internal temporary memory areas. These
memory areas are called ‘registers’. fetch
decode execute cycle

This is called the ‘fetch’ part of the cycle.

For this to happen, the CPU makes use of a


vital hardware path called the ‘address bus’.

The CPU places the address of the next item to


be fetched on to the address bus.

Data from this address then moves from main


memory into the CPU by travelling along
another hardware path called the ‘data bus’.

DECODE

The next step is for the CPU to make sense of


the instruction it has just fetched.

This process is called ‘decode’.

The CPU is designed to understand a specific


set of commands. These are called the
‘instruction set’ of the CPU. Each make of CPU
has a different instruction set.

The CPU decodes the instruction and prepares


various areas within the chip in readiness of
the next step.

EXECUTE

This is the part of the cycle when data


processing actually takes place. The instruction
is carried out upon the data (executed). The
result of this processing is stored in yet
another register.
Once the execute stage is complete, the CPU
sets itself up to begin another cycle once
more.

b) Write notes on OMR,MICR, and OCR


devices. (4)

MICR (Magnetic Ink Character


Recognition):

Used by banks to read numbers written on


cheque.

Special purpose machine reads character


made of ink containing magnetized particles.

OCR (Optical Character recognition):

Special preprinted characters that can be read


by light source and changed into machine
readable form.

Used in department stores to read retail price


tags by reflecting light.

OMR (Optical Mark Recognition):

An OMR device senses the presence or


absence of a mark such as pencil mark.

Used to calculate or store multiple choice


tests.

OMR is a system of reading lines or ‘marks’


which have been made in exactly the right
positions on a card or document.

CHARACTERISTICS: of OMR

The documents to be read have empty


boxes to take the marks. These have been
pre-printed on to the documents together
with information telling the user what to
do. The person preparing the data makes
pencil or ink marks in the appropriate
boxes.
The data to be input has to be simple
because the user can only make marks
and cannot write any information.

APPLICATION: of mark reading

A multiple choice question paper

The answer sheets are sent to the examining


board and are marked by a computer with an
optical mark reader.

ADVANTAGES: of using marks

Fewer mistakes are made by machines


reading marks than are made reading
handwritten characters.
Data can be prepared without any
special equipment.
Data can be prepared where it is
collected, e.g. a market researcher can
mark a questionnaire while asking people
questions in the street.

DISADVANTAGES: of using marks

Documents for mark readers are


complicated to design. If an item has
several values, then the form has to have
a different box to mark for each possible
value.
It is difficult for a computer to check
marked data.
The person putting the marks on the
document has to follow the instructions
precisely.
Optical Character Recognition (OCR)

An optical character reader can recognise


characters from their shape. As with OMR,
light is reflected from the paper and from the
ink. In OCR however the reader has to work
out what the characters are.

Scanners were originally designed to scan


pictures but they can also be used to read text.
This system relies on sophisticated OCR
software in the computer.

The following types of character can be


recognised by scanners and OCR readers.

Handwritten characters
Printed characters

APPLICATION: of OCR

Charity fund donations

Names and addresses of prospective donors


are pre-printed on donation forms. The forms
are sent to the donors. Each donor sends back
a form with some money. The date and
amount given are carefully hand printed on
the form by an operator. An OCR reader reads
the name, the date and the amount. The
computer then uses the information to update
the donor file and the accounts.

DISADVANTAGES: of using marks

Documents for mark readers are


complicated to design. If an item has
several values, then the form has to have
a different box to mark for each possible
value.

It is difficult for a computer to check


marked data.
The person putting the marks on the
document has to follow the instructions
precisely.

Optical Character Recognition (OCR)

An optical character reader can recognise


characters from their shape. As with OMR,
light is reflected from the paper and from the
ink. In OCR however the reader has to work
out what the characters are.

APPLICATION: of OCR

Charity fund donations

Names and addresses of prospective donors


are pre-printed on donation forms. The forms
are sent to the donors. Each donor sends back
a form with some money. The date and
amount given are carefully hand printed on
the form by an operator. An OCR reader reads
the name, the date and the amount. The
computer then uses the information to update
the donor file and the accounts.

ADVANTAGES: of OCR over MICR

Different printed fonts can be used (the


MICR font is fixed).
OCR usually accepts hand printing and
normal type.

Over OMR

The documents do not have to be designed so


precisely for OCR.

Over other media

The data for OCR can be read and


checked by people.
Written data and printed data can be
read at the same time.
Documents can be read directly into a
computer without any typing, e.g.
documents received by fax, old books, etc.

DISADVANTAGE: of OCR

OCR systems often fail to recognise characters


– particularly if they are handwritten or in
unusual fonts.

Magnetic Ink Character Recognition (MICR)

An MICR reader recognises characters formed


from magnetic ink. As the document passes
into the reader the ink is magnetised and the
characters are recognised by the strength of
the magnetism.

APPLICATION: of MICR

Bank cheques

The major British banks all use MICR to


encode along the bottom of cheques the
following information:

the cheque number


the branch number of the bank
the customer’s account number.

This information is printed on the cheques


before they are issued to the customer.

The customer then writes a cheque and pays


someone with it. This person pays it into a
bank and it is sent to a clearing house. Here
the amount of money is added to the bottom
of the cheque in magnetic ink using an MICR
encoder. The cheque can then be sorted
automatically and sent back to the bank of the
original customer. The money is then
deducted from his or her account.

ADV ANTAGES: Of MICR

MICR is difficult to forge.


Documents can still be read when
folded, written on, etc.

DISADVANTAGES: of MICR

MICR readers and encoders are very


expensive.
The system can only accept a few
different characters.

18.give the algorithm and flow chart for


finding the largest and smallest numbers in a
given list of N numbers. (8)

Problem: Given a list of positive numbers,


return the largest number on the list.

Inputs: A list L of positive numbers

Outputs: A number n, which will be the largest


number and smallest of the list.

Algorithm:

1. Set maxto 0 min to 0


2. For each number xin the list L, compare
it to max. If x is larger, set max to x.
3. For each number xin the list L, compare
it to min. If x is smaller, set min to x.
4. maxis now set to the largest number in
the list.
5. minis now set to the smallest number
in the list.
An implementation in Python:

deffind_max (L):

max=0

min = 0

forxinL:

ifx>max:

max=x

returnmax

forxinL:

ifx<min:

min=x

return min

19

a) Differentiate between break and continue


statement with proper examples. (3)

The break statement, like in C, breaks out of


the smallest enclosing for or while loop.

Loop statements may have an else clause; it is


executed when the loop terminates through
exhaustion of the list (with for) or when the
condition becomes false (with while), but not
when the loop is terminated by
a break statement. This is exemplified by the
following loop, which searches for prime
numbers:

>>>for n inrange(2, 10):

… for x inrange(2, n):

… if n % x ==0:
… print n, ‘equals’, x, ‘*’, n/x

… break

… else:

… # loop fell through without finding a factor

… print n, ‘is a prime number’

The continue statement in Python returns the


control to the beginning of the while loop.
The continuestatement rejects all the
remaining statements in the current iteration
of the loop and moves the control back to the
top of the loop.

The continue statement can be used in


both while and for loops

>>>for num inrange(2, 10):

… if num %2==0:

… print“Found an even number”, num

… continue

… print“Found a number”, num

b) Write a python program to display all


amstrong numbers in a given range.(5)

# take input from the user

upper = int(input(“Enter upper range: “))

for num in range(0,upper + 1):

# initialize sum

sum = 0
# find the sum of the cube of each digit

temp = num

while temp >0:

digit = temp % 10

sum += digit ** 3

temp //= 10

if num == sum:

print(num)

20 a) Write a python program to count the


number of zeroes and negative terms in a
given set of n numbers. (4)

num_array = list ()

num = raw_input(“Enter how many elements


you want:”)

count_zero = 0

count_neg = 0

print’Enter numbers in array: ‘

for i in range(int(num)):

n = raw_input(“num :”)

num_array.append (int(n))

if num_array[i] = 0

count_zero = count_zero + 1

elif num_array[i] < 0


count_neg = count_neg + 1

print (“The number of zeroes”, count_zeo)

print (“The number of negatives is”, count_neg)

b)Write a Python program to find Sum of


Digits of a Number using Recursion (4)

# Python Program to find Sum of Digits of a


Number using Recursion

Sum = 0

def Sum_Of_Digits(Number):

global Sum

if(Number > 0):

Reminder = Number % 10

Sum = Sum + Reminder

Sum_Of_Digits(Number //10)

return Sum

Number = int(input(“Please Enter any Number:


“))

Sum = Sum_Of_Digits(Number)

print(“\n Sum of the digits of Given Number =


%d” %Sum)

21.

a) Why do we need functions ? What are


the advantages of using a function?(3)

A common usage of functions in computer


languages is to implement mathematical
functions. Such a function is computing one or
more results, which are entirely determined
by the parameters passed to it.

In the most general sense, a function is a


structuring element in programming
languages to group a set of statements so they
can be utilized more than once in a program.
The only way to accomplish this without
functions would be to reuse code by copying it
and adapt it to its different context. Using
functions usually enhances the
comprehensibility and quality of the program.
It also lowers the cost for development and
maintenance of the software.

Functions are known under various names in


programming languages, e.g. as subroutines,
routines, procedures, methods, or
subprograms.

A function in Python is defined by a def


statement. The general syntax looks like this:

def function-name(Parameter list):

statements, i.e. the function body

The parameter list consists of none or more


parameters. Parameters are called arguments,
if the function is called. The function body
consists of indented statements. The function
body gets executed every time the function is
called.
Parameter can be mandatory or optional. The
optional parameters (zero or more) must
follow the mandatory parameters.

Function bodies can contain one or more


return statement. They can be situated
anywhere in the function body. A return
statement ends the execution of the function
call and “returns” the result, i.e. the value of
the expression following the return keyword,
to the caller. If the return statement is without
an expression, the special value None is
returned. If there is no return statement in the
function code, the function ends, when the
control flow reaches the end of the function
body and the value value will be returned.

b) Write a python program to simulate a


menu driven calculator with Addition,
subtraction, multiplication, division and
exponentiation operation. (5)

# Program make a simple calculator that can


add, subtract, multiply and divide using
functions

# define functions

def add(x, y):

“””This function adds two numbers”””

return x + y

def subtract(x, y):

“””This function subtracts two numbers”””

return x – y

def multiply(x, y):

“””This function multiplies two numbers”””


return x * y

def divide(x, y):

“””This function divides two numbers”””

return x / y

# take input from the user

print(“Select operation.”)

print(“1.Add”)

print(“2.Subtract”)

print(“3.Multiply”)

print(“4.Divide”)

choice = input(“Enter choice(1/2/3/4):”)

num1 = int(input(“Enter first number: “))

num2 = int(input(“Enter second number: “))

if choice == ‘1’:

print(num1,”+”,num2,”=”, add(num1,num2))

elif choice == ‘2’:

print(num1,”-“,num2,”=”,
subtract(num1,num2))
elif choice == ‘3’:

print(num1,”*”,num2,”=”,
multiply(num1,num2))

elif choice == ‘4’:

print(num1,”/”,num2,”=”, divide(num1,num2))

else:

print(“Invalid input”)

22.a) What do you mean by mutability of a


data structure ? Explain with the help
examples , why we say that list are
mutable while tuples are immutable. (3)

Python data structures are either mutable


(changeable) or not. Strings are not mutable –
once created they cannot be modified in
situ (though it is easy to create new, modified
versions). Lists are mutable, which means lists
can be changed after being created; a
particular element of a list may be modified.
Either single elements or slices of lists can be
modified by assignment:

>>> x
[1,4,9,’new end of list’]
>>> x[2] = 16
>>> x
[1,4,16,’new end of list’]
>>> x[2:3] = [9,16,25]
[1,4,9,16,25,’new end of list’]

Tuples are essentially immutable lists. There is


a different notation used to construct tuples
(parentheses instead of brackets), but
otherwise the same operations apply to them
as to lists as long as the operation does not
change the tuple. (For
example, sort, reverse and del cannot be
used.)

x = (1,”string”)
x = () # empty tuple
x = (2,) # one element tuple requires a trailing
comma (which is legal
# for any length tuple also) to distinguish them
from expressions

b) Write a python program to count


number of vowels,consonants,words and
question marks in a given string. (6)

a = “hello world”

>>> vowels = “aeiouy”

>>> Consonants = “bcdfghjklmnpqrstvexz”

>>> Quest_mark = “?”

>>> space = ” ”

>>> nv = 0

>>> nc = 0

>>> nq = 0

>>> nw = 1

>>>for char in a:

… if char in vowels:

… nv += 1

… elif char in consonants:

… nc += 1
… elif char in Quest_mark:

… nq += 1

… elif char in space:

… nw += 1

>>>print nv

>>>print nw

>>>print nc

>>>print nq

c) Write a python program to input a list of


n numbers. Calculate and display average
of numbers. Also display the cube of each
value in the list (5)

count = 0

total = 0.0

cube = 0

while True:

try:

line = input(‘Enter the number: ‘)

if line:

n = int(line)

count = count + 1

total = total + n

cube= n*n*n

print(‘cube:’, cube)
else:

break

except ValueError as err:

print(‘Enter a numeric value.’)

print(‘cube:’, cube)

if count:

print(‘average:’, total/count)

OR

num_array = list ()

num = raw_input(“Enter how many elements


you want:”)

avg = 0

total = 0

print’Enter numbers in array: ‘

for i in range(int (num)):

n = raw_input(“num :”)

num_array.append (int(n))
cube = num_array[i] * num_array[i]*
num_array[i]

print cube

total = num_array[i] +total

avg = total / n

print avg

23.a) Write a python program to create a


dictionary of roll numbers and names of 5
students. Display the contents of
dictionary in alphabetical order of names.
(7)

Create and initialize a dictionary:

>>> roll = {‘max’:1023, ‘sue’:404,


’abc’:1034:,’sdf’: 1234,’jhkl’: 6789}

To get the list in sorted form:

>>> x = sorted (roll. Keys ())


>>>for item in x.items():

… print(items)

b) Write a python program to create a text


file and input a line of text to it . Display
the line of text with all punctuation marks
removed. (7)

file = open(“ifile”, “w”)

file.write(“hello world in the new file”)

file.close()

# strips all punctuatuation

import string, os

def strip_punct(ifile):

exclude = set(string.punctuation)

f = open(‘newfile.txt’, ‘r’)

text = f.readlines()

f.close()

op_file_path = str(ifile) + ‘.punct_stripped’

if os.path.isfile(op_file_path): # Checks if o/p


file exists

os.remove(op_file_path) # deletes the existing


o/p file

for x in xrange(0,len(text)):

s = text[x]
return op_file_path

if __name__ == “__main__”:

print “Input file path: ”

ifile = raw_input()

strip_punct(ifile)

24.a) Define the terms class , attributes ,


method and instance with the help of an
example (4)

Class: A user-defined prototype for an object


that defines a set of attributes that
characterize any object of the class. The
attributes are data members (class variables
and instance variables) and methods, accessed
via dot notation.

Instance: An individual object of a certain


class. An object obj that belongs to a class
Circle, for example, is an instance of the class
Circle.

Method : A special kind of function that is


defined in a class definition.

attributes

Class attributes are attributes which are


owned by the class itself. They will be shared
by all the instances of the class. Therefore they
have the same value for every instance. We
define class attributes outside of all the
methods, usually they are placed at the top,
right below the class header.
b) Create a class car with attributes model,
year, and price and a method cost () for
displaying price. Create two instances of
the class and call the method for each
instance. (5)

1. # declare a class
2. classCar:
3. self.model = model
4. self.year=year
5. self.price=2500000
6.
7. def cost(self):
8. Return self.price
9. if __model__ ==’__main__’:
10. c=Car()#
11. Price= C.cost()
12. print”Car Info: “
13. print”model: %s”%c.model
14. print”year %s”%year
15. print”price” %d price

c) Write a python program to create a file


containing 10 numbers . Read contents of
the file and display the square of each
number. (5)

dataFile = open(“temp1”, “w”)

for line in range(10):

sq= line * line

dataFile.write(sq)

dataFile = open(“temp1”, “r”)

print (datafile)
dataFile.close()

1,266 total views, 22 views today

KTU SolvedQuestions

« KTU M.Tech Examinations Timetable for Sem2


May/June 2016
KTU Previous Questions with Answers
Engineering Mechanics »

ONE COMMENT

Sagar p June 9, 2016 3:34 pm

It’s to hard to for the beginners


to give correct answers for each
programs in the question paper

LEAVE A REPLY

Your email address will not be published.


Comment

Name
Email

Website

Post Comment

Disclaimer Powered by WordPress and Dynamic News.

You might also like