0% found this document useful (0 votes)
170 views73 pages

Python Univ QP

Uploaded by

vengai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
170 views73 pages

Python Univ QP

Uploaded by

vengai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 73

Reg.No.

:lo e R |
Question Paper Code : 60035

B.E./B.Tech. DEGREE EXAMINA'TIONS, APRIL/MAY HO88

First Semester

Civil Bngineeri1g

GE 3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

(Commonto: All Branche8)


(Regulations 2021)
Time: Three hours Maximun 100 marke
Answer ALL questions

PARTA--(10x2 20 mark8)
1. Write an algorithm to find smallest among three numbers.
2. Which is better iteration or recursion Justily your anéwer

3 List any four built in data types in Python.


4. How do you assign a value to a tuple in Python?

5 What are the purposes of pass statement in Python?

6. What is Linear Search?


7. Give examples for mutable and immutable objedts

8 What is purpose of dictionary in Python?

9. List any four file operations.


10. Write a python program to Count Words in a sentende 1sing spilt 0 funetion

PARTB ( 1 6 B0 mark8)

11. (a) Listout the control flow statements in P'ython and explain repetilion type
in detail with a sample progra

Or

(b) What is recursion? Wrile and oxplain n P'ython progr#m to findl fatorin
of number using recursion
12. (a) Why do we call python as
interpreted and
language? Also explain about object-oriented
Interactive Python programming
Or

(b) Write and explain the python program to swap two


without temporary variables. numbers with and

13. (a) What is difference between break and


continue in Python?
suitable examples. Explain with

Or

(b) What is string function in


Hython? Explain any three Python string
methods with an example.

14. (a) Define Python Lists. How to add elements to the list?
suitable example program. Explain with a

Or

(b) Explain bubble sort


algorithm using Python programming.
15. (a) Why does Python require file handling?
with all modes. Explain opening files in python

(b) Give brief notes on Python


a
and finally statements. xception Handling using try, except, raise
EnggTree.com

Downloaded from EnggTree.com


EnggTree.com

Downloaded from EnggTree.com


Reg. No. : q e t f I \ tl* o z q

Question Paper Cod e z 25109

. B.E.lB:Tech.
.' DEGREEEXANTINATION, DECEMBER/JANUARY 20L9.

First Semester :

'
. .' CivilEngineefing :

f1E
\.rI 8151- PROBLEM l:tl-\JJ PYT}ION PROGRAMMING
\J\-rLr Y rL\'\t AND
rrYL SOLVING

?
''

(Common to all Branches)


:

(Regulations 2017)
:.'!

.-:'
. fi'Be: Three hours '.., MaXimum : lO0 marks

'
DARTA-(10x2=20marks)
IJ_,- -- .t a-_
:. -'-
1. Oistinguish between algorithm andprogram.

. 2. \Vrite an algorithm to frnd the minimum number in'a given list of nunbers.

' 3. What,areleywords?,Giveexamples.

"'.

.:- : .., .,._,1 ,


--,... : ] ,] ' ':'
', 6.. Defrne recursion with an example.
-4
I

'7. Relate strings and lists..


-j
:

8,- Givg a fttnction that can tak6 a value and return the first key mapping.to that
' value in a dictionary.

g.- ' ,What is a module? Giveexdn)ple. , ',

'.

10. Find the syntax error in the code given :


: while True print ('Hello world')

\ 1tl
P1RTB-(5x LG=80marks)

11. (a) (r) Discuss about the building blocks of algorithms. (8)
(ii) Write a recursive algorittrm to solve towers of Hanoi problem. (8)

Or
(b) (t Identify tJre simple strategies for d.eveloping an algorithm. ; (8)

, (ii) Write an algorithm to insert a card. into a fst of sorted cards. (8)

L2.. (a) (t Sketch the structures of interpreter and compiler. Detail the
d.ifferences between them. Explain how python works in interactive
mode and script mode with examples. (2+ 2+ 4)
(ii) Summarize'ihe precedenee of mathematical operators in python. (8)

Or
0) (il Explain the syntax and. structute of user :'defrned functions in
Python with examples. Also discuss about parameter passrng rq
'o
mncuons. (r2)
(D Write'a,python'funclign to swap the values of tws variables. (4)

13. (r) .List *ie thrbe types of cond.itional'statements agd explain them. (16)
'

Or
(b) (t Pythgn strings are immutable. Justifu with an exainple-. (8)
(ii) .Write a python code to p"ifo"- binary search.;Trace'it with an
. example of your choice,
14. (a) (i) Discuss the different options to traverse a list, , (gl
'i
(ii) Demonstr'ate the working of +, * 4nd bliee o'perators in python. (8)
:l

\
:

(b) (i) Compare and contrast tupleg and lists in Python' : , .(4),
(D Write a sgrlptin Pvthon i;;t n numbeis using selection sort (LZ)

15. (a) ' (i)


r' Explain the commands used'tolread
;
and write into'a frle:with'
. eximples.
(ii) Discuss ab'dut the use of format operator in file processing. , (8)
. .Or
(b) Describe how.exeeptions,are handled in Python with necessary exdmples.
'(16) '

25109
V.S.B ENGINEERING COLLGE
DEPRTMENT OF CSE
UNIVERSITY EXAMINATIONS JANUARY, 2019
GE8151 _ PROBLEM SOLVING AI{D PYTHON PROGRAMMING

ANSEWR KEY

PartA
t. Distinguish between algorithm and program.
An algorithm is a self-contained step-by-step set df operations to be performed to solve a specific
problem ol a class of problems.
A computer program is a sequence of instructions that comply the rules of a
.specific programming language, written to perform a specified task with a computer.'

2. Write an algorithm to find the minimum number in a given list of numbers.

Step l: Start
Step 2: Minimum = 0
Step 3: read (number)
Step 4: if number < Minimum then Minimum: number
Step 5: Repeat from 3 as many times as needed
Step 6: Print Minimum
Step 7: Stop

3. What are keywords? Give examples.

Keywords 'are the reserved words in Python. We cannot use a keyword as variable
. q?me, function name or any other ident$er. They are used to define the syntax and structure of the
Python language. In Python, keywords are case sensitive. Example : False, class, continue while and
def import and so on.. ./
,* \L
4. State the reasons to divide programs into functions.
The first reason is reusability. Once a function is defined, it can be used over and over and over
again. You can invoke the same function many times in your program, which saves you work. Imagine
what programming would be like if you had to teach the computer about since evef! time you needed
to find the sine of an angle! You'd never get your program finished! Another aspect of reusability is
that a single function can be used in several different (and separate) programs. When you need to write
a new program, you can go back to your old programs, find the functions you need, and reuse those
functions in your new program. You can also reuse functions that somebody else has written for you,
such as the sine and cosine functions.

Present the flow of execution for a while statement.


In while loop, test expression is checked first. The body of the loop is entered only if the test
expression evaluates to True. After one iteration, the test expression is checked again. This process
continues until the test expression evaluates to False. In Pyhon, the body of the while loop is
determined through indentation. Body starts with indentation and the first unindented line marks the
'
end. Python interprets any non-zero value as T.rue. Noiie and 0 are interpreted as False.

Define recursion with an example.


. Recursion is a way of programming or coding aproblem, in which a function calls.itself one or more
times in its body. Usually, it is returning the return value of this function call. If a function definition
fulfils the condition of recursion, we call this function a recursive function.

7. Relate strings and lists.


' Strings, and lists are all sequence types, so called because they behave like a sequence - an ordered
collection of objects. T,.ist are mutable but strings areimmutable

8. Give a furrction that can take a value and retum the first key mapping to that value in a dictionary.

my_dict : {'name':'Jack',' age' : 26}


my_dict['age']:27 ,." i
print(my_dict)
my_dict['adclress'] :'Downtown'
print(my_dict)

.9. What is a module? Give example.


Modules refer.to a.file containing Python statements and definitions. A file containing python
code, for
e.g.: example.py' is called a module and its niodule name would be example. We use
moautes to break down
into small manageable and organized files. Furtherrnore,
liigt^f",q:y
we can define our most used functions in a module and import it, instead -odul.. provide r*r"uiliry
"i'."0".
of copyirg their definitions into
-different programs.

# Python Module example

defadd(a, b):
"""This program adds two
numbers anl return the result,',,,,
result: a + b
return result

10. Find the syntax error in the code given :


While True print ('Hello world')

Colon is missing in the while statement. And the next statement should have indentation.
The
Correct form is
' While True:
prlntl"H"tto world')

part B
I I . 'A).D Building Blocks of algorithms

'fhc huilding btwlx tfalgnrithrn


ar*
.$*&M$ts
'Stsse
-fr*lwlffnw
. -F'unrrirmr
St&nwt*:
*r HeFeSre J gpetl $f s$hsffirrlE:
-Inpf,ffi rnput ${ssss${*lt
-.4x*igryenr i$r$effie$t
-f.osr8sl Sinrefierrt
#t**r:
The*ear€ 3 type* *f *@: .
*tlifist sftb
-.furrearirtnte
.Final sgrrs
flunh*I flnw:
-$*qremce
strus&re is tfw sa$S{Rffit r{rere.rmEffir*ter* i*exW*gd Ef**msdrsr
ft-ry**
"Stme*
Thes*t€ctiGa *lr-$*hre.i$ ttd
ryrys$f"B* $&Rrns{rhctrt4ar€e,vrsddrrsl*ps dependtrlgsfi urlig$rera
r:snditinrevstru*re* h: T&tgE cr.FALf;E. Thrx,e mstrrw -ddj*--rs*il#1ilT,--*"**"'
.t"rF'
i. ii* nLsH
3 $WnTfir
-Rryetitior
*:ry-Tw s*r$:trffs i$_Hryyq** *-hes4,#s$tdlun!c ran be iue,auted rryr€*{ssdly tmfle csnditnru
*v*luntes ro TR"IJH dtr s'A{sH- Thse arc tr+* rqxtiticm xmrerurc* in c:
l. wf{tl$ .
t Fs&
Funriisas:
,*Srnetien.i$*htoe&*f@*sbie:qerde*is$ix,o*d,inp itgglrs6$1
11.;).ii). Write a Recursive algorithm to solve Tower of Hanoi.

Tower of Hanoi is a mathematical p-azzle which consists of


three towers pegs. pegs and more than one rings is as depicted
- These rings are of different sizes and stacked upon in an
ascending order, i.e. the smaller one sits over the larger one.
There are other variations of the puzzle where the number of
disks increase, but the tower count remains the same.

Rules The mission is to move all the disks to some another


tower wjthoul violating the sequence of arrangemgnt.
-*,:..j few
.A
rules to be followed for Tower of Hanoi are Onlv one disk can
be moved among the towers at any given time. Only the "top" disk can be removed. No large disk can sit over a
small disk. Following is an animated representation of solving a Tower of Hanoi p:uzzle with three disks.
Tower of Hanoi puzzle with n disks can be solved in minimum 2n-1 steps. This preSentation shows Ihatapuzzle
with 3 disks has taken 23 - | :7 steps.
Algorithm To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem with
lesser amount of disks, say ---+ 1 or 2. We mark three towers with
name, source, destination and aux onlytohelpmovingthedisksonlytohelpmovingthedisks. If we have only one
disk, then it can easily be moved from source to destination peg.
If we have 2 disks -
First, we move the smaller top top disk to aux peg. Then, we move the larger bottom bottom disk to destination
peg. And finally, we move the smaller disk from aux to destination peg.
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two disks. We divide the
stack of disks in two parts. The largest disk (nth disk) is in one part and all other n-ln-l disks are in the second
part.
Qur ultimate aim is to move disk n frdm source to destination and then put all other nlnl disks onto it. We can
imagine to apply the same in a recursive way for all given set of disks.
The steps to follow are -
Step I : Move n-l disks from source to aux
Step 2 - Move nth disk from source to dest
Step 3 - Move n- 1 disks from aux to dest
A recursive algorithm for Tower of Hanoi can be driven as follows - l'

;lffi.. Hanoi (disk, source, dest, aux)

IF disk=: l. THEN
move disk from sowce to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step I
move disk from source to dest /l Step 2
Hanoi(disk - l, aux, dest, source) // Step 3
END IF

END Procedure
STOP
To check the implementation in C programming,
ll).b)i). Simple Strategies for developing an algorithm

Therssf,d.S ryW sf ttl&nrents:


-hryssd;S$Sbts,,,e-;
-*wtp ,X,rg*qwt : .

-{CI*hsi'$tnremc$l
se&:
Y?l€$, ssg.,l, X*e*.*f W; :.

"y**:o*
-C&rrefit steile
-Fhifll slste
Cnnhslfiow:
-$eqmme
$mrt$re is Sw s*$-ctnfft r*ere om.st$.emffi i* e*.4cuied dltr
ffim* sH${h6r

The c8l4tien *[ruct$n t$ the $fin*trwt lo-lHxe saffsrnsilB


rur,qte}lrsrw:rCI rRuE nr w
san esiseEted o{
ritrse-r?,sur*,1 #_G$*;il€@***,
eFndi{}g oa whdel a
:q*
}-.Tfi
.:" IF-SLSE
x $lurqg ll)
:**;*" b)ii):
The rcpetition **: effsuuc* *rhEIE sratg*w#$ cqr **:-* H*ril
erffi$ed ftpeawy wrr {rs e*m$iti*n
s*r'o
F.ry
*v*luntrs t'T*I"rf; sr FALHE-
foE

t" \ryHxI-E
r*w* src n*, ,*p**it*w ilil;;{,
2" FsR
Algorithm to insert a'card in a list of sorted cards.

Step 1: Start
Step 2: Declare variabies N, List[], i, and X.
Step 3: READ Number of element in sorted list as
N
Step 4: SET i:0
ltep 5; IF i<N THBN go to step 6 ELSE go to step 9
. Step 6: READ Sorred list element as Listfil
Step 7: i:i+l
Step 8: go to step 5
Step 9: READ.Element to be insert as X
'Step l0: SET i : N-l
ftep I l.: IF i>:0 AND X<List[i] THEN go ro step 12 ELSE go to srepls
Step I 2: List[i+t ]:List[i]
Step 13: i:i-l
Step 14: go to step I I
. St"p tS: iistli+r1:X
Step 16: Stop '
l2'a)-i) Interpreter and Interactive mode and Script Mode python.
in

An interpreter is a computer progmm that executes instructions


written in a programming language. It can either
execute the source code directly or
o translates the source code in a first step into
a more efficient representation and executes
o code this
Python interpreter and interactive mode
with the Python interactive interpreter it is easy to
check Python commands. The python interpqeter
by iyping the command "python" without uny purur*i., can be
:19t1
prompt:
rono-ea by the I'retum' key at the shell
$ python >>t
once the Python iottqft:l is started, you can issue any command at the command
prompt u>),,.
example,let us print the "Hello World" staiement: For
>>> print "Hello world" Hello World
In the interactive Python interpreter the print is not necessary: >>> ,,Hello
world" 'Hello world'>>> 3 3 >>> Typing un eoo-or-fir.
primaryprcmp't causes the interpretli to-exit
l,rrururt", i6it6;;';;;;,"ffi;;
windows) at the
with a zero exit status. rthat doesn,t work, you can exit the
interpreter by typing the followirg command: quitO:
when r;;;;;.
*e read from a tty, the interpreter is said
to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually'tlree
greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...).
The interpreter prints a welcome message stating its version number and a copyright notice before printing the
first prompt: Continuation lines are needed when entering a multi-line construct. As an example, tdke a look at
this if statement: >>> the world is flat: I >>> if the world is flat: ... print "Be careful not to fall off'!"
List down the rules for na-ming the variable with examlle

A variable is a name that refers to a value. An assignment statement creates new variables and gives them
values: Variable names can be arbifiarily long. They can contain both letters and numbers, but they have to
begin with a letter. It is legal to use uppercase letters, but it is a good idea to belin variable names with a
lowgrcase letter. The underscore character, _,can appear in a name. lt is often used in names with multiple
words, puch as my_name or variable_name. If you give a variable an illegal name, you get a syntax enor: (b)
List down the different types of operators with suitable ex

Precedence of operators.
12)a)ii) .

nescnipticn

Exp*nenti*ti*r* {raise tc the pswer}

C*r*pl*n'rent. riftary Fh:s afid rniilus {met*r*d $anr€s f*r tfie


lnst two ar€ +G aild -@i

*,ul*ullt" d i vrrie" €n$ f{*e1 snv_1:jsm


T.sdr*j{}
&drfiticn snd srrhlra{tion -

Rfgft and *eft *|ou


litwlsl __ *
Bitwise'AND'td>
-
Eitw$se €xclilsi\re SR" and *-eg$.r*ar " SR-

C*x-r'lparfsr*r1,sFeFai rE

EquaNiity sF*rstsrs

- &r^- t-i: it-


it- -- Ass*gnn":ent *peu:nt*rs
J-- S- IcS*.

*s [s met tdentlty sp€{"ators


: '.. , -:
ir* *nt ix'r ffi err*bers[-* !F 0p€ retsrs

ftst 0r and L*giae* *p*r*tars

Operator pr€cedence a.ffects how ar* expression is evatuated.

12.b) i). Functions in pythion

User-defined functions '

As you already know, Python gives you many built-in functions like printQ, input0, type0 etc. but you can also
greate your own fuitctions; These frmctions are called user-definedfunctions.
Syntai of Function definition .

l1 t,t''}
def function_name(parameters) :
t""tdocshing"""
statement(s)
Above shown is a function definition which consists
l Keyword def marks the start of function header.of following components. uPv'v'LD'
name to uniquely identify lf ruo"tioo naming
follows the same rules of,wdting identifiers in
3rfii;*tiot
3' Parameters (arguments) through which we pass
values to a function. They are optional.
4. A colon (:) to mark the end offunction heaier.
5' optional documentation string (docstring)
to describe what the function does.
6' one or more valid python staGments thal make
have same indentation level (usually 4 spaces). - rr' uroLvursrr*
up the function uoov. Statements r'usr
must
7. An optional return statement to return a value
from the function.
Example of a function

def welcome(person_nameJ :
t""'This
function welcome
the person passed in as
paralneter" ""
print(" welcome " , person_name, " to python
Function Section,,)
Using Function or Function Call
once we have defined a function, we can call it
from another function, program or even the python
call a tunction we simpty type the tunction nam.-;;h prompt. To
;;;ri":" oLu,,'"r"rr.
>>> welcome('Vinu')

Welcome Vinu to python Function Section


The relurn statement
The return statement is used to exit a function
and go back to !'v place
'v the r^sve from
wheie it was called.
Syntax of return

retum [expression_list]

This statement can contain expression which gets


evaluated and the value is returned. If therg.is
the statement or the return statement itself is no expressipn in
riot present inside a function, then the function
object. {i,ill return the None

def absol ute-value(num) :.


rrrr'rThis
function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
print(absolute_value(5))
print(absolute_value(-7))
When you run the program, the output will
be:

12b) ii). Function for swap two values

# Python program to swap two variables


- # To take input from the user
' # x = input('Enter value of x: ')
#y: input('Enter value of y: 'j
x:5
y: l0
temP :
x=y " l

y: temp
print('The ralue of x after swapping:
{ },.format(x))
print(,The value of y after swapping,
ii,.forrnut(Vii
1,3 a). list three types of Conditional statements and explain them

\q3
Th€re are a number of useful operations that can.be performed
with string. one of the most useful
d,lh.:: is the function split. This function takes a stling (typically a line of input from the user) and
splits it into individual words. Another useful function is lower, which
converts text into lower case.

Hg:

>>> linE * rnput(*lffhnt is name?"}


5-r*ur
1$fu*r is .tr*ur mnnret JLtsn Budd
>ap ls$@ale -* "fu**thtr
lilrejnwsr{}
. r*>printtq*nmmraepffi
fltimnthy'" "alanl,'hu{Id'J
$rhs't**&}ft$*t!{}$s xffil *e*mh * *eing for c given rext va{us".ur*trip rea{tng ** t.*rulx
white space frorn a string. An att*rnative vgrxion *f split hkes es sr$ffie{* $e seperntrrr strry;
IIrs sring is koken int$ a lisr mi*g rt're s*pura$r a$ * divisiCIn Thi* een be u*dful fer exwnipls,
fai brenking * {ile parh r*ame intn pr*:
Eg:
\---=::
'h'*rF pqlkrr*ryJ# * o*rc{&s.sfr:&inl[$:-,

>>> pathnff:re.stllit{-/"}

l.u*r','lmal";'bifi'"'ls*l
Ttrre ir:v*** *rf *plit i* the $rxfiri{}* Th*,aqsuff * j*irr.i*:*
}*trn. *f *tringp, Ttre r*rm & tbe
Iisr
Ie{t *f dh* d** i* flre sqpmx{trr t{wt w;ll he p:***d bsrwwn ***tu *f*rmeirt
#fur thl*'k *id6y qc
'ftttpry ttrinB The vskss
in tN!* li$t ar* laminst*d alung with ttre *epr*n*r tn -h--*1nlt
.
FrCId*s*
$lfrng"
$trinE mefheds
A meth$d'r* simiier to fi fufic{i$**it takss srgurne*t$ nnst refi:rns a value-*bgt rhe *3wr4x i*
4li&rerlt" F&r' s, the method upper tghry,*,Sqiry sq$ s,nst*, *tfiqg wiffi 1ifu
l*iters:
Ins*ad,*f; ** $hrxexi*n $)ryrrjrx uFF$rtw*nl), it,ry*q*sr d syqreR w, ord-u*@
..}*.:r' wti$ * hgnrys'
p:'> $sw;nffiBrl * t*,**S'upp*{}
:er> pnnt nevf_.*r*rd

SAHANA

13 b) ii) Binary Seardh

gars*il
n * int{inputf finter Nun{ber trf filsrnsnts in the .Ansv:.,11
- print{ finrer the El*m*nffi iaA*cen*ling ftdet'
'"
} '
lbr i in range{*, n}:
x * int{iqp$tt{'Hxlsrth $tffilsetrffi,i'
.
,dat*.upeer!{x} Wi*t
win{b tft*,Slsmeut t{} k fuffitu '}}
frrxt*S
*
lg$t n*l
fourld m False
iI{isrselsg,$H$l s&t $tlt$Id}:
mid.* {first + lnst}*?
if int{ia*afmlttl]ke:
faund*Tlrue
elne:
if ec inr{darefftid]]:
last*Iftid-I
: . elge:
first*mid+l
if fcunr!:
p--r{ffieflil{at %d Fffind $t Fssitisn Hd'9{*,rnffif }}
g*:
'' f$in4"m*u,**r$t'*dig$**$**nd,iq,{h* ' {

l4.a)i) List Traversal.

A.list,biffi *rdwed ref sf ronluea wlms *a*fo vaftle is id${$iit*sd b} er*iadw" l t&wt*,W,e k
er*,*ali*d it$ s'lq$ Lis,l$,.srs'xMlnr t$ $tring$i whi* glrc $der,$d r$$ry: ,qlq{,qs ..S#t'W]..
slerwn efs-$x*axf kwe,any mlwffi*cr,qrnl ureyu tcerffi,*,gthr*ist. s**i .i*,*p
*e $lements ia squarebracmts ttandli:
1in. m. Js.4r)]

f $fertr"'bungeel" "mralknr".t
:
'trhe falt*rring,ti* e asfiisgn.*.S*et" ru: int*grr" amd tmirsbih dis$l',ss*&:'1i:*
g,$* 5;
f-xs$I4!"- {t{l-E*jl
5
* hg wi*in snnthsr H*t is said ts h nested, ti$t$ thrt cqflEia ccnrsmeiw ieryem am *wrxnoa se'S$htrn
prevides asinrple.waylu crtse tM:
-\F>r&ng$ tl$,i [].3, l- 4].

s,r#T#sssAtr{t{{s
The * rperarw concate$ntes lists
;;->:r A-{1"3; 3J
. 3:':! hr* [i$_ 5, 6l
**> g = J;;'
Fb)'prim e [1" ?, 3, 4" 5, 6]
*turlim4r" ths* Wsw'rqFsntx.a lixt,* gvxrattrnkr'*f ti w:
:"b* {0} * 4 [$, t], *. Sl

, >::" ll" ?, 3j * 3 il. g,3, l" ?" 3, 1,3,31

{*{sTsl.il*F$
Tls.xtiee'qry. nhr qlm,ln*r*m.,nr*. tri*tx.:

:FF;F t E [tst,''lo'" tU,"td . 'g', nF]

;'lb:!lf l:31 fb'..cI


. >F;' r{:41 ['a', b','c*"'dJ

>:'> t[3:l {'d""'e'.'ll] rl


R

It- r/\,f
l4 b)ii) Selection sort

# python _prodrAm
rogram for
€a* impJ-ementation
:_. .
. # Sort of Se-le.r..i^. vv urvlJ
import sys
A = Laa,'25, 12, 22,
111

# rravers"
I ,11:?ynn .alt array elements
for i in rangre et_emenrs
tfen taii:*-'dy
# Find
the
. # unsorted minimum
array
elem ent in remainingr
. mln_idx = i
for tl (i+1, r-en (A) ) :
,l. r fitman
"-tlttneidxl > Ari r.
min_rox I i --LJr.

f Swap^the found minimum


element with
j,
Ii Almin_idxj -="ot*r-r,
idxl, AliJ
# Driver c test above
' pnnt ("u;:3u 'toarraY")
ror r- ,n ,'tt"o t".TiJii
,
l5 .
\ .\ n.
a).i) file operarions
print ( 'TJ': ' ]
qsr ej$sts{fi}merns}
. . try:
f * open{filerrarne)
f .close{J

exsept ?*Effxr:
, rs{nfr}ls.{rls*'

{}} ltrri*e a'F3{hon Frsgraru fti


hansle rnt}ripl* e*mpdons. a
fry:
* .* ffrr$r{ral*tnPu(uy*ur
d.r.-*..;..
.:_- numb*r: "}}
sx*# v#,:m;
r #,':r at

except rffnffiHXll** siverr eitherdn inr or a **a,'


print ',Infiniryn

' 15 a) ir)forynat operators

A& ca;pee*:EF#.
& awit€{id:
:*tU". rs )Fil s!
I Sb).Exception handling

t:t!1M

mgffiae

,,*da *eqrtiou ban ermt, s&ic& ocm* dlriag thesxecr*icnof*$rogram ftnt


di*rry*; &x: Srxnll*f ee $r?g6ek i
q* iprlrt; b ," b;,*'&&gB srule*
e€Eou@ a sitssii@ tB it A'wst cope w*& it rsiias m ex@itr- Alr rscogiou ie,x
F:fu$ obj€rr eat repr*strts q$ error.
's,&ras*,@':,*ra!gt.r.siixea,*a,ener$&4,iFwt
s S*€mc€ffuelu
iwri*ietety c*crwise it iecuieates and:Er*tts"

$*rrr Frogrse by glaciag the srryiciorm code ts fl trlr tilcck "{fter &rry: b}cak" ilrer#
ro rrerpt Ei**Frfiffit, fCllsnw*d by a btwk of eade n'h!@ ftsf,SFs the pcblee*e ebga*fu-xs
potsrbtre:

$-YEtFr!

X{qse,b, siryle e}g@ €frditr"'"qsEw*""efse &tg$re =-

{*t
I{r,g. lon.

Q*estion Paper Code : 54$0$


g;{A:.JINATIO N, JA}.f UARY 20 1 8
B. E"/i}.TCCh. D EGRE B
First. S*mesfer
Civii Engineering
GE 8 1 5 1 * PROBLEM SOL\''I NG AND PYTHON P RO C RA1'11'{I NG
(Common ro Aii Branehes)
(Reguiations 2017)

?ime : Thu'ee l{ours lrtrlfw. recentque:stion prp*r. aom Maximum : 100.\{arks

AnswerALL questions-
PART -A (10x2=20l}larks)

1. t''hat is an algorithrn ?

2. Write an algorithm to accept two nunrbe;'s, compute the sum and print the result'
3. Name tire four iypes of scalar objects Python has'
4. What is a rupie ? How litbrals of type tupie are written ? Give example'

5. Write a Python program to accept two nurnbers, multiply them and print the result.
, G. Write a Python program to accept two nutnbers, find the greatest,-and print the
resulf
?. What is a list ? liow lists differ from tuples ?

B" How to slice a iist in Python ?


tlww'recentgug$tion paper.co;t

9. Write a Python script to display the current date and time.

1G. Write a note on modular design.


PART * B (5x16=80 Marks)

I l- a) i) Draw a {low chart to aceept three distinct numbers, find the greatest and
print the result. (8)

ii) Drawa flowchart.tofindthesum cftheseries l+2+3 + 4 + 5 +........+ 100. (8)


(oR)
b) Outline the Towere of Hanoi pratrlc*r. Suggest a solution to the Torvers of Harroi
pnrblem vrit,h reievantdirigra.ms. {lC}
lffirll$llllflffiH ffi
&.1009
{4}
is tl ttttrncric lit'errrl ? Liive
cxatttltit'x'
t:. n) i) \l'lr*l (lz1
ii}^{ptrtr*tstrtlrctrit,}r*rutic<lptlr:t|trrsitlPyrhonwillt*tr*xatmltl*.
(oR)
oy:ratorr in Python' t6)
b) il outline llr* t:pcrator precetlcrrr:e of arit'hrnetic
t'wo vari:rbles'
(4)
ii) lvrite a Pytlrcn prcgrrim ta exchange the value of
sum of firet'nl even
iiii lvrite a Pythcn progr-a$ using function to finri the
t6)
nuurhers and prini the resulf'
in Python' (6)
13. a) i) Appraise with an example nested if and elif header
and continue statement
ir) Explain with anexample while }oop, break statement
(10)
in Python ?
t*'*{wrrec€tltqu*tion paperrcom
(On1
without
b) il lVrite a Python progranr to fintl the factorial of a given number
{8}
recursi*n and with recursion
(8)
ii) lVrite a Pyfhon program to generate first'N' Fibonacci numbers'
Note : The Fibonacci numb-ers ate 0, 1,1,2,3, 5, 8, 13' 21'
34' """' where
each number is the sum of the preceding two'
i (4)
la. a) i) What is a dictionary in Python ? Give example'

ii) Appraise the operations for d.y namically manipulat'ing dictionaries' tls)
toR)
(8)
b) r) Write a Python prograln to perform linear search on a list.
ii) Write a Python program to store'n'numberg in a list and sort the list using
(6)
selection eort.

(16)
lb.. a) Tabulate the different modes for opening a file and explain the same.
(oR)
b) l) Appraise the, use of try block and except block in Python with syntar. {6}

ii) Sxplain with an example exceptions with arguments in Python. " (10)
i;
'! 3
iolvfs tJNtvFRgFY €urstro^ts Saxu ePF 2*o1g

%'+ *A

f) Nt*l ; 4r,' "I-na-"h- ?


A \Aa;rbn^, ; of ,Uf tJ
a. ge?u."-nra-

ttt? irxtr.raH ora< tb"t a-r6Q- .ua4*ivc-d .b t*- .f-sll'r^re4


bH b-roP"tr*r +. Srrt,.e- o^- ?.nogle-,rr, 'i.'- 6 firit,t-- a-ro'r.,-h
u,
"{ F.r,r- *t^J {-i"-ata oo"o.rrtt e{ A^9^'
f+ c-6.-l.r-
"l,n V* J"f^.4 44 t t^gt.,
vsf.',**a- 3,rt^.-li-w Uh- V2- gr?tassa4 in a\- lis{. of
i rrcl-r..c+iorr ,

.Z) kl*te &L "n t" alr-pt +*'- ne'n'Bat<, crr,Dpc.-&


? fh- .4utru ^1ui;:,tt
^^4 P"i-f TL. .t-ar..Qt .
t? L : s+^z+ -TE._ FT-^- .t

g+-? 2-' :
&.t ty d ^ ,L *iT ?n7"f' c> {<r.ncfroo,
s+a 2: e^ntt["[ .9'.rr> =<,_S
4: nt ,s"--Y'r,
"t.? 1"i
s+*P s.' st-f Tt* fT-^,r,

, [.la.r,.,ur* -tdrr tt"* o-f xco-Q-at rI"jae& p'trqryo /4"-,4

D i*-t
.lJ
z\ +1"---[

$ L*-e.

4) t.l*.:-- rt)
4) LILI i^ 4 +'?le ? U€-"' tlf'4'^-&g of +a'ge l*?l'
acre ,,>*ttl,en ? frriw- ay-a-r-p{"

T*1ft: dlt-c- |ea:*-nts- qf i ' "o.,*oA l<' ?Ae *


utlecl-s . A W" U'*1'<t of a' n-"Len a{
g yv b{ t'^atz>roa-3 a?l* a-"oL o-nobt'A utl rni '-
I "frA
PPto sis
?*
Ex :'
tr - r)
1-a : fl .*+'^'o' , z>
.. .,

g) l.lfiha L TAtt""t +- |,ro huna4an6,

L =in4*t C"Er,t.rr t v^q,r";


| -
L'rr-

i4t ^>b) : r
PdtDt C " frao.-^}esl t,ut'-ben 'nn , o)
etEe- :

Poi.rt C' Ca'oo-,tcs+ nt."n8c-'lr L" , b)

t) l,<l*ta dL tfl** l'" a.-ue-<f* h^*' r'n'>n8 c*S


F-tr"-" -
eovlti pf tD,-.-'., 4^1 ff "+ It rrarutrt

A - ttO ( *t*cn
t=i.*g*-t f "Ent." V v*-O'u-") :

' i-.)o-t- :- a t L

?;*+ { .-d)
.!
I
(-'
?) Hk-t i. &-
YI
J

-l-Jst ? U-.. /is+ J.ifier


+{f,ts ?

,4r L:s F i4 a- -.4*"9[e- ptr*. ueie-]s . A

,[Js t tt aD o"dr,r-d &eay,-n-ncr-- q1E vEX!-n-l , r're.lr

u9-9^ \/^'i"i- A i&rai .ci-J bg L*\. ?kdi-i.


'U
+- L;rt J-i+fu"r f".-"- )*1-s tj ur€- sn -"s6a
th or,.- yar"--n"lt'o< i
g
S.^--L*ls .

E* ...

o,=(l ,uq.rro',.3) + Ljsf


t=tl ,"f.^r.arr 3) g 1.,3{zx.

s) t+'..o tz aliu- a t&+ ?ru Pfll.*^ ?


,' SeTt'-o r-o" v
A 6rr-bsc4.v-L-Drtr.-
.Y "f
sl;e *^4 c'1c-tta-fi.rrr +L"S 4 giibs'e?q-e-t\-0-e
I

U c' 0a-",{ xgl.dnX .

Na r8e- L')
^t Sr;p- 1,ar.,tgx- - rae- +.^""
i *f,* v*ltzs S1'^ ^+4 tt b{"-"' C: )

6tc :

. f ' o- r z t'b t , tc tJ

,o'
L' ,.a t ]
q) h-lqle a! oiPt 'l' l'( ?k tt"
?flt"* f
c.*trx.4'L

A&e o_*d Li*a


iy# A"k-4i^^c*

?;n+- C 'tD.ffo -Tl,^ e. "- , J.rto $ .t"fu-k*o , nr'^rrr)


"^4 ^^-n-

to) k[;t" L r,ofe ff) n",o.&r-0'qr A' <i g"

\A-d--t--v d.s?gn i^ .^ f lt t'u"drc S *1 "+


h's&J'!- ca-rL f*^'} *3'
?fl* 6r{e . 'A '7s'fi"a
c^b ..-{a o i ^a{'tJ
Cl*ssz9 ^"'1 V^nlJtc_s A rtro+,,-0l'
.6.-o,-n-a.-bla t-t*e

E"
c Storua-aai r.r'Cr,-0c-
-"/
{l-+ +ibt> '.

arb
=@rl -)
t.

,,shi.le t > F)

Van+Cb)
A,r) =brafbl I

.k i"-y"'t ILl' o',o4"0o tl \1e 4:L b Fto'$lCr")


?^n' -B
i) ?r* a* *t*.L*ryf t" q-ra-ef F mr.l-,- d; H
rr)
") ^rt
Wl-oo'&e:f, / S-d tt- E.-*"f
rsf "-xd r'* ]Lr. trg".-Qt

r. a> b .{{
Ptl ttl o
Xr"otect

.!

{- u-s-- tl^*- Aet"i.o-s


rr)a)',i ) Dtt-'^' q- $r*c_3''-vP S ^1 "! "f
l+A+3+*'" ttltt

\fu?
,l)b) S.,tr-H*-. n- -Tu...,o"rs '{ l{*-rli f""Il'-',>. ;q'st
o{ U"*'+ L; fL
d dot o-ti o't ,tt tf,{- {u'^rr-nr< fd-glt*'
efolsr"-rt t^tt a-rt>4'
'f"'.".l,S o j: tt*r"ti 6a-3 i.t"-,'frtd t t 8J.".^^.4

Vb4 ;''- I g6 3 , Ol '1" rr>"-I[L '>*J{ cJ od ,yr-:-l;fll- '


T-^.
et + of tL'rs- 644 '"1
C-,,,t""t *n'^"\u:v o{ dil t(
'rr.'- a- gt-^t*. ?"- **^n xl-'Y o{ ;it* 6rt1- ctr^-c-

,r4 / "{f,o- 6",,^)la-zl ,-+ IL - +T , *#*1 a t-*i-c^-0-

zsL".-?e
I
, Aor4- .*']"s :
,) .^t .,u,-- dt k c^^- t'e- "o*J *-+ a- [it^^-'

Z) E 1n.'{"Q- Lu-*"''gk of +a*-.h Tf. F=n-.


"",4
o{ -Tt'- ''{- h?
1--',, r;1'\-e- 6l-''Lz;s ^^{ C--1 .".,
Lu, **4
fl^gt /6+agL \* a_ &a\ry. A;^k- c,.-.rL-

- 11+
o^-r'u
-l
i4 U '-?P* r'''st aLlc- Frl a- Kl--a-L

e) fr[" ,;l( ar^t Lu fU4 * *? o$' 's-*I\"'{ d;k t(

s"L :

-tcFa+a-!- a
n- t 'r,'v* a-cr@- ,.,o-.4t .

Ai
u-\ j
I
I

I
I
, r-f-1
I

----+-_t___J__

J+c7 c
1_
s+d-y a:'

l
I
I I
,t
I i
I
t
j i
i
a^ '-1
I
-'"-.:i- -'. '*-+"''. i i

t
.--j__--_
sJ.? 1
sff t-A

b '
s+a +
S.1.1

Ah-stb- :
U

S+.-f 4 : 3+4YF 1fi.a- yrtlt ao


s+"7 L : ?.*y' vAL {l-*^'i ( d; r Awr@ . 4'-st , a-u-r<)
' tkf t : if disk. :o tho*n- +D s+.? 4 ufl^r-t.ts?se-
= 0.
zt"r'AJ- s +D T

J+ef + : M,'.'e- A|AE t"* ,$at*'rrt Fo degt 'i

J+€? S : $*ofi (Jir -l , fiotx't+n' . a)r-r^ r4zs+)


9tc-y L ; [4.'vr- {isk f,rorr> ['w"rr<r- 4- 4.8f
strP ?: +--,.i(4isn-r , ats'-f,- tA'e-strsourru-)

sh'P I : stuP I

e'rc'-n^3fe '
z)^) i) ht!.*,+ iA ,L p-r^.lic t3re'..*'A' 2 t'r"rna

A
' rrt*-r^or.i c- gilu-J ^
u a* 'I,_T-ery-a--
18 - i^i^1J
/51l""--A' C@+=

*-[1 €ve *rr-+.g-*ic crr *dk Co-t)


Lo1'-f^'t a* A!; n'^-(-
rJ {-J 4. nt" or^'-o ti c 1;l-x--:'
p"in* ', ttrst Tf )-e-t"e-4eg xp^4 r1-f.,*-c- srn #t-*-L '.
[bl
f r'.' o
s,. c_.1
>-<'
c- rL
r{
1€(
r r) a) ii ) Atp:"'. Tf,- .*-,3 16.
-o- Pi c 64 a tra- frcrus
I
i ,n-

"SfE 2a-^-r"'vlla '


?fl-
a'-[-lsrtr;s +' tttttA""t t, ".r'i c 4rtaf\..o+ie
?$t-'t 0
t..* lit* Fict , S..$rr-ao-F on , .n *Iti Pr-f
c^-+i*.
ey**--I+ "(-l-J'i
J &i.,isi *.!

or*}* D*.d? Fi.r'>

n-rtte-r
+ Aaaitiar, v&atl crn-
o*'d = 3o
s?&- of T**
S.,!t^"J{ dcr - s*S---rJr-ls ;$
-0"#
'&^d T"-^^+ +*'"" .r(
-*U = Io
ls-^4
"?1*-d
{< t 4"HFl^'c,--li.nn
I
- -"JfiP{as * * .(
=Aeo
V*Ir.as dn 2i1t"-x 'i'!' +
7t'r-^-l:x

/ !"{ t"^4 "14^-^^4


Di..il-s tf n= 2-
;6s-t ).-^4 T" -._4
\ _l
"r/, $.l,"fu* - Dir, ? !-'-s ,rft t-.^4
u?"^"-"J L,a 4{e .l^--A $"/'X =-O

-K i< ?@ a-*7."*.'^t * }e re :t
[
ctY' ae"^*--a'L--S ,Fo
I
lr."^ J

tt Ft'lr-" D?.r^?si ar' -j tL"- 4r'if i5ic'o "$


r6as,a_[b',A
"._:f_ova_ q lt{ : 4
41u:rlif e,r>t lv,
,'vrXt*- i_-?i is "j-Lrr
d:.-.ed"r:"^Q *c,ir-i- t?-'xa t.-,--r*d
t);) eofti*"- T""*k ?'rre&-l!r,t-{-{,
I
r+ *o,itli"oe -?
'2) or"r
I''l."J'":.o ?f,t.orn"

?n**A.nnn 'B vl'{ l" d-1."-* ^l. fe"- ct"{.rr

u'ei"-0.- Ai++ "r"n-o.t T*'-ftt '' i ,.' cs'"o1&r e-rp tcasit4s


?r.
4vrl. ,A'ai,---Ed

l^lL.-y, fr16t^ll- ft s-l- crl^c- i rr-


^?11a-a-O
o.rgr-esi.rn , onlov- o$ e-v*0*-^-$i"rn W trrL vttirr *+

P"arlJ.-o-ruq-'

l. +e
t-t o-r*
de E

1- . * t l r',/.
"ll F t..r{,Lthe.f.^-Son . +oo-o-- J'irisicrr ,6''at'L
si",r, - E, |f,.os'o_ baJ€a- i n 9-.-n,c. e1.,.*}4 "^.1
+ua- &ivi T'-^-W
- 1L- a'1)r---4..n L**4 ?.,,^- W l-t "46et'
g. + , - AfJ:-Fo", --{ 5.^Sr,a-o-}i.n 6s\3- ,l-St- -?"o b-+6t

+- ytr-r^- ' -;

tL) b)',1) l^l€fa ?$*, 1---0* to "***-0" Vl.Irrr4

,] 4 {o'" v*#r"'$lgg '

o =i.ry*f C" E D+/! #"ut v'--0t* " )

b = i*1*E ( " fttt-'t S.a"-n{ V^!-}'-Q-")

?*^f 1'ri"-0'-e-o ucfe- **'f " ' ^ 'b)


b-rt = Vrd
?-.nl- ('\t va['.a- ^4-t
'tr J.'*-P " , a ,b)
O*E*e :

T nl,'r' f.rrst v-n-.'-a- :

' lo t \
,/
.l
e..l e v -luA--.>l r,-qi-.e',a \U
&c
o , \#" gcr'T to d_o
vt-{--

Vat r4- *-tL" s*f d-.D lo


*ln {-r-^-F?.^', F"
,") u)i',l) \^l*{" o.
? f,t"" r\l
fztr":r%4ra-r'rt
*4 rosc0
S^4 Ad-ff' 6-1 &".t \ t) | g.ve-tL nrr-rl&eers 1n.'l "t
d.1 9e-v'tt'Cn) I
nY
I
r =4.
S\4-rr,'= O

r,rf€le Ci< = D l{ 16u,,/. d ==O


jtlrcr 3c-e_rrr
= .fl
i c itfe
6e{*-r'-n 385l}
n='rr* C;"g*-t (rfnt*.r n 1p.-t-r-.2")J

rn: Scsre-aCo)

?A*t* -t|--c.- Au,rrr o.f *i*l lt .nve:", r*t:"t%on L " , -)

O"41*t '
.,
E''+'- n ao
nLe- ,>.,--rtr o.,t *,*f N ex+-* n"-"'?e:V tt ltD

'*:to."l i-f *,.^4 iy


ra ) ^1i) AlPr-*isa *ftTL o\-w
""(---#t
L-4i.c-Y i n
t--,J-ili.rn
A+&.rrc'\''L a{ "}-i*-A
",[iJ
+o cA".-k '-*ffi P(o

a Lg"'A o.L b&-

9r*.l.-o,--fi-s Fo +t"ta-

3q ol-or :'
\ z*FocsS?crrr r 1
I
a

3f-& "qe
n f' f g)
thl

,li+ e'r1w*siclr> A :

g|*-lr-r",-r"f CS )
e-Ll s?cnr' 3 :

s+-j:--r'w^* L9)
d;"e-
3 $"fr-rt t-r* C s)

t t-.*.*7f" '"
n r-rD = "?

i+ bu,rn >o :
,pt-trl4 ( " prc.,li.re >*rr-%zn ', )
'l
il;+ h...-ro = =-o '.
?*-+ 6* 1o-r'o" )
oQs.
.rf C" *-^Xve ,v-rrr?oe'r ")
1nrr

o*\"o t
p"<i{i.re N"rtc.rBe-r
-\
r
\-.-, t{"*t { at
'T
'
r! rt-q.r.'
'oc"-'--t '- L'o t"'qgt*4 *lltir- *,n-o-rb\.or
'tt^r- G.l-i F

51-€--x :

i+,l err<par'oas i cm r;

g\-^fu-*vx>*C s )
ilzp-
i'f '1o*sicm 4 :

- olso :

3.raf-"ozar=& f s) t\-2
l*^-"p" ^'

[" t'"torr ,tr-ta8en " ) )


nrr*.D = $t'-D- ( i.r.?.^t

i+ f nr-r-t'nlo:
1+ D^l-rnn = =- o '.

f t' zo'o " )


?"i *f
g)Ae- ^ -r,\
n'f ( 't gtsi [i"c- n\YQtSoA )
f"t
o]>o
.1-fr.& t" N\"ff-H\.e- ,*'--'Lc't)

E*.o n'-t-r6o'tr ) r

'*t*"<"x
9"<i$ "a
t'i"tL c'c^-"oft' w9'i[2- W
f a) a) ;,; E*f'Rd' '
sm4is'*g B{=g+9n4 t
t+.*Il.;d,f,a "-+ ,n
tr.llifu
'l Pl',+ :
,"r<-.r-i-!-s cL bucu 4
htl^it- &T x+.i'-'.,"-"*
.,

*--+:l tU-l C"'A; fi.oa' 'J


g+o..Gr.r-rrFs
^n-in ^-^A -f,*
e&r>6 +-jxa
g *6{a* :
q

usgG [. c.f>6'e'ss? "ngr I

e +*-b-.tan'&-Ca)

t&**"*'.
L*-S :o
,S11" t e^'-*-t <3) :

,!' - P-\
f.J-_.J_ry'L I

!'n"f [ "
.r1^o- L"..--t"g
{+ j
f1x,^-* 3c-.,-"8 + t

?*r,''* [-c,"4 btr")


0"+f -E '-

-fu {""'^{7 -p
-tL c.-.'^A f4 '. L

tt^"- c--r-rr{ k :>


q*J b-r,t-
q

B"tF--k sl-I't^<r-t : .

B*.-t s+=?.r'r l* +"--E r.F.s TL l-.-p s,t=*-m.-n*


\-r*^<1."ts 1t"- e,rs'*liol^' Fo tf,"- sF*g-r.a",'* ?-"^".J.i*k
"tC
M"( rul. *T
Sa"'o* t
,n,e^n(

.--) l"-e"- ln ' ru*"",


.es-tt!.r -.Lt ,

b.rr-A
t\ uu'renl &-!fi.' :"
Pd ^,t , f.fl*"

O"b*[I
:

cttx-.Lr+ !,'S-Y ?
'*o-vtt.* A..if,Y IU
\&r
fu*S**-r- S{-1" rqo-a.t '-

t+ -ffs_ C*]htdt +- t2 i-'"'l^g o ,$ lt..-

G"rfi*-
tx^-.",'gta :

+-" 1p-14-x- rtn ' ?ff"k--o '

i4 .{rd,-v =- ='{'
(rrr+4n-r*..la.-

?; -* 'r ur-rrrar:& f"-dot 't, zts-t{s-Y

0*a?*t :

c-rrrtrc-?',t i.a-!faY P

tr'-n"crrft lrie-rr
t -;
Cr.--rtnt -1"- b

Crp"r"e-r.
j.o-Sl-x :o
\
lr.Yguntt leJtrx :YT \.-/

b {n fi^{ f*--c-t"ryt *!-


re;$t) l-i*t"- o- ?St** f.'nlr&rrl r
I
o .tt-
+
t ern d-t"-lt ust lr{-
6c.:r-r-r-16
t^itV',
of d' ng-mr8ztr "ttt
d"o-"
?
qrc.glirA I cn'
I

.o
ttfitL rne-c!-{3;dr>
"

i1 ':=
.f.C-|ro-.-*.
4so
rc-**-rn h..k +a-P (n -- r)

o =-in-P Ciy't ( " F-^fr.x *,.)


)
* = t*-Ftn)
?"a* C''-1*-r"^i^g L ", + )
ObT*t

E.,$* N:F
nt^r- {.-o-$..,fi*tr iE \a-o

hlftG.t rreru-rsl trn :

. ri=-id Gtd f"L"Er N i))


+r+=t
4c'r i in -6crnz Ct
\| "'r{)
-;

'1..s$'e.4
?"+r+ C " TLr.- U" , +^-+)
O"\*t'
E-t"-. N '. f
1[^"- .$'-4qri aQ- 'ts ta-o .

r 3) u
j',t
) hle{o * tt -" fl'TI.-*
? T*- tu fixe N

$b-.'n-.i Seri B-g .

h =1*t t l"i*t C" l^f'a- * " ))


I
a

, A =-s
\D =' 'J \$f
r,'&ilo L d ry
l

ifi

A ,b : b.n&

Ot,ef t.€

th-r',+-"'nt N : !-
o
I

d
3

"t4 &ic-li"c'^x1 ir,-- tdt*'t I (n'e


ra)^) i ) Nt-S
"4 a-h., 4&5o'f *$i G*+e""\J
?ff 4itli"-*T 'x-
b53i"0,-pr-ot-"'!sarDj.'ra-&<V*46111*(^t'..-ftq'-rr'tL*'"-
\"4"x

?; "g C " Jic$ ti"d J


., "
, arj- [. xr^,',,o-'l )
O'4f*r "
4i" 1 f' r.l*,,"e' 1 : *-r'ini

t4) o)',1 ) Tt- T^ o-13q{v< Jrf ^"r>t.^05


^?f"Jt" * onl'e s
,., ^-^ib *Q-i-iv.1 d'i cF? '
r.(l
Ttt* o-f- up*.ry-"-ticm< a-r> di.ti"rrroti .g
I

1:^$-r f -ot^"^-0i"'"'
I

I-r,t,. t4 ) "ne,f-...-r-< lT.-q- t""-t"-r'rv&z-^r *+ I fc.'x-a

.n fv?. I 't
e- tLa rl\e-4-n-g?-'r oI
a o-t - v-.Q--"-a- ) P.^'v:
6)
tut- 4 L"l J-t.}. tf,.- t-t [c- l-trr U-x ,,ift_
TIA \F$r-a-

L?n 4 rT'4^.c- i+ cL k-ox h oois l* in


A o a\a
d-e Lt-tcrrrarr? d

L< 6rlp ? n 4 /fn".o.


, 4 a- b-a K A-i. ."oF prrjs,{-'-
i.' dict+,"' o"-6 4 .

r*) b) i) l^f"+f" & ??tu" ?*1t** h' T"-k"" &-t^"--r

Ber-rrc'L ('?\- a- ,!iSl "

l"+ s.17-vf+o-tre---lr.A, L^d.f , ',F,--', ) '.

?t c =-o
+r."..4 : F*.Qaa

rstile- ?"s' < A,^- t "-[is+) 4^4 ,"6t- 1C---,4 :

!+ 4+{- Lt*I = =lFrq :- I

-f-."i 4,E 'l*<rq


a]tgq

?es =. po< +-l

nsa+4x-t.,, f-*-'1
tert?st- = f. ,1 r 3> 18 . t* rl4 t4\ r t" ro)
('tegttist
?"a",t- C s:t:'o?i ' 3 ))
6aan'a-0'-

go^rreD"' ( ha*t^isf l3))


?*t+ C s.n*--^'Fz"'t '

o*st*
' F^!su_ -

_T-nl*-a
\5?
) hl"ito A ffft-" T*{ i€-Yn h" s {."rc I n
t4) b )if -n
' ntrtr)S€{6

fw & tfst **4 S<r<F tul- ,f-is| *lX Sql"a-0i"'"- cl crtfF .

4"$ Sr-lepli.,rr sq{+


"U*l-; C :

t-t 4;ll slo} in **n" C-[s-!'-C40"isl ) -1.o,*l)


?"ciXqn, €-o

4-" Ige."-Si.n in y^te. ( r , 4ittstr"t- fi) :

!ac?Fi"-' = [uco.]?"'n

,list f4i ttst-e 1 . a,Q&,t- L prsi $i.o,l - agfs t- fgos? H *l , -'


a-lis F L{i tts l.rff

^.Q-Jrf = fr+ t&L, 13t tf tLt]


.('tc-aj{"D S"ir{- C--oist-)

ta-;rc-a";"-{-)

D*4 t

r8 vL e4 q3 i

rs) ") Tt9*[,"fa- G- "Li{-}c,n.^-t


ttJ.X +". wy"d*: .
#l' ,,^4 g,4re^ih-
\
IL& /sa-t.'tc- .

\4Je Dr"*igli*r

\- oY* |. lo f'- c-a?li^€ *t


tt-rj w lL-e- ;|,4*--t ,-*J*
t---\

t4 1* a- f"t.* f-rr rar..{.i lry


-*t-
bil^**.{ *""".- ^f. 4^;} - tt- J^f ot-t
:
'
F.'de .

r&+ u?"* d St" $-r LutA lru-&'1 e,bt

tt ' *^*
"-*ET i n f-,-t^t

s-* r* u- tilo f"- b-tf-


r^rfi Hn1
rc.d.u't^1

^^4

ro "?orl, a- t. 1--.{i r^--r *? r^3 ,%


srrr-."g,ir&s tta fit- ?P ;+ *-4"
'*
a'xj CE . o]*e crrec1r q. fit".
^4s)

r'b 4* SV +-" ur-.&Fi.a ir-


*
blh--t +".t>,t
rot +.- - brfh .rpo]+\ ql^{
iJ

rot +

* Tr*
4^-
f\- F -tp"{ ;*1 . 'rls Sl
g^i*Sr"t i,' ,^t "^A q fil. ?.f Jit-
exjgk - 3+ fle- *-es D1t+ qrds Fs , 1f
Ct c-"-h-s a- r^!rq) SL +* *UX ,

r! no
G-PP.l-\dLr uq b
I n^-
a-L T* [r J
b;*^*T

\5'
rs-) b) l) lte- vt''- -f
,41g-'.r'ca tt*& ^^d l,c'-f t
\
b.tr-$q lL HXT"^ "itt ,XV"l^x- .

ft 1+ L^ts- /'-'-'x' l-Afit-i.'"x u'J* It-*-t-


ff
as}t- "t"F'"d ,o..:{":".-
Y>-a* *aitv ^t''' ".t'{"* ' fi
u -T-r^r 4 t,,-ti cia-t'* [-J"- i n t-,.6 H-"e
,3 l^"'-f
fi S$z'v -t : b t'LL i t."-t"j-0-o- a,rw l-?
"r,,'-

gV-br',1r-r^k '{*-tJ-.r.i tt o\- b\"'*- 4 Ld" r'sfficA/ !,


}l.nft"-r P-',:'glz-6 a'3 ffi oJ' y'<sitla '
SX,n+*x i

QuXSoq A
C+ fU.oryt- iS
. O- C M
[r.""?ff.rn 3 , than exoetfu- ]f,} H".-p

Qrrclj+*
rl Lr.^-+t*t> ! I

o,t E-x"--fe n .r*s.fie, lHx


f4 tE >c- rr, t- IEc- t{..-q

.,1 .-

e)sa '-

$+ tt s.a"- U t)o z'"rt-yA+ "tr> +ttr^- et"x-t-tn ff,a


tft

-k A {.\4" q sl'g"tot{-rts c€'-e" :f""."'^'q r^r.,.,_$ ti#-


€-Ped- i"5ts-'"- l'-
f-*te-.o-r"4r , {L3'< k
u'! LX*-lt
ev'e-p+ g rJ
,tr"ryk =F-tr'-o di4+" - .-".+
@
G'-I-Lru g Uea- tbaS

of g'K-t-oph/) cin<
k?* \

# hlE- ts..,^-
fi&!- t*-""* c\^tt/* , *tic-g-,
ff*.
J--*dlz-s *t
o
'4< d^- p-Ize bt'ct tr c,--
1^.=4 T.t"'.- t^ r.,j e-

b r-f' Aor* nrsF ""r4 tt".h's f"--f"-F €r\

tr) t)''i) t*g[.i" t,$tE FLe- ,"r.a-t-fr-6


d-,\- a'*.--r^ d tL

n
dt ?6u. "f"^- to
.^-!J-"^r3 L.ra--fre-
t.*- sr.r.)

bd Jdvf \T cA"asPx 1f,4- S U^Ja"r4


o.*p"{ sx* {""tt"

b.i' \t - in atn< .

-----et-,uls a.;*-rr t?.,rnfi-nriz. t


,"4. l.r|- Cs"$jf , "*f,) ',

grq.*t = ^-t
\_--,

Ot*o- t^1C- F."- cLAr6 ttlc A.a-t"l .ooi'sc- lt-c-

et'rof+4"*' 4,r9 ,

I
I tq
(r

ta-r^ f- Nrl-,-t-<e errs€tr C" ts^4 J.s,[.cr^-^a t )


Nf,q!.s.-xq znv-atr /. L.,

*+ t - a-"ti -

\$?
* & oJ'','"<

?,ro'4*'* L"--ttt '

Afu *.o'"d roct6-4 S zfaif{ c- Ln+-.^"-rs'..-Fic/n


"re,e_a- av *^"_*f k *
'U
w-Afe
(J
"6
r ^-
fqtl *{ .Lt"-1. , Tf,r-- ttLtss A"# *rd A
o'*-'-p(Ar^t
I

it ,".3A 4 "-*+ r""<* in 21",-0. .

+ -rt"- v**i *Lle e- on ur e4 +- C-"ur--of-t- &*!n

i*L<^tcr*t- o f Ur- ala*6 Nzl-*j-rr€ e/Trcn'r .

r:
9
Reg. No. :

Question Paper Code :90277

B.E./B.Tech. DEGREE EXAMINATIONS, NOVEMBER/DECEMBER 2019


First Semester
Civil Engineering
_
GE 8151 PROBLEM SOLVING AND PYTHON PROGRAMMING
(Common to all Branches)
(Regulations 20L7)

Time: Three Hours Maximum : L00 Marks

{l
Answer ALL questions.

PART * A (10x2=20 Marks)

1. How will you analyse the efficiency of an algorithm ?

9. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of
problem solving ?

3. Compare interpreter and compiler. What type of translator is used for


Python ? p

4. Write a python program to print sum of cubes of the values of n variables.

5. Do Loop statements have else clause ? when will it be executed ?


n
6' write a proglam to display a set of strings using rangeQ function.

?. How will you update list items ? Give one example.

8. Can functions return tuples ? If yes give example

9. How to use command line arguments in python ?

10. Write methods to rename and d"elete files.


90277 -2-

PART -B (5x16=80 Marks)

11. a) i) What is a Programming Language ? What are its types ? Explain them in
detail with their advantages and disadvantages. (8)
ii) Write a function find*indexQ, which returns the index of a number in the
Fibonacci sequence, if the number is an element of this sequence
:and returns-L if the number is not contained in it, call this functiorr using
user input and display the result . (8) 4.

' (oR)
b),i) What is recursive function ? What are its advantages and disadvantages ? :

Compare it with iterative function. , ''' '(6)


ii) Implement recursive function in Python for the sieve of Eratosthenes. The
a
sieve of Eratosthenes is a simple algorithm for finding all prime numbers up
to a specified integer. It was createil by the ancient Greek mathematician ,^
Eratosthenes. The algorithm to find all the prime numbers less than or ,

equal to a given integer n: (f0)


L) Create a list of integers from two to n: 2, 3, 4,...., r.
2) Start with a counter i set to 2, i.e,the first prime number.
3) Starting from i + i, count up by i and remove those numbers from the
list, i.e. 2*i, 3*i, 4*i,...
a) Find the first number of the list following i. This is the next prime
number. i
5) Set i to the number found in the previous step.

6) Repeat steps 3 and 4 until i is greater than n. (As an'improvement: trt's


enough to go to the square root of n)
?) Atl the numbers, which are still in the list, are prime numbers. t
12. a) i) Write a python program to rotate a list by right n times with and without
slicing technique. (4+4)
ii) Discuss about keyword arguments and default arguments in python
with example. (4+4)
(oR)
b) i) Write a python program print the maximum among'n'randomlf
generate 'd' numbers by storing them in a list. (10)
.3. 90277
| fi]llllill lllll llllilllll llll llll
(6)
ii) Evaluate the fotlowin$ expressions in python'
r) 24ll60/o8
ii) fl oat(4+in t(2.39)o/o2)
iii) 2**2**3
or rya{ not be able to arrange them in
13. a) i) If you are given three sticks, you may 12 inches long and the other
a triangle. F; r;;piu, if o"* of tfti sticks is
short sticks to meet in
two are one inch long, y"u *iii not be able to.get the
test tg see if it is possible
the middle. For any three turrgths, there is a simple
greater than the sum of the
to form u tri*rrgi;'if u"y of tfi* lfttee lengths is
. ;lh;"-t*o,lf,*riy"o cannot form a triangle. Otherwise, yoU can'
l) write a function named is - triangle that takes three integers as
r"y'ft" or "Nol" depending on whether
argumentsn and that prints either
given lengths' (4)
you can or cannot form a tti-"gl- ftom sticks with the
Write a function that prompts the.user to input three stick sticks
lengths'
ii) whether
I converts them to integert, *ta'*t*s is-triangle to check (4)
with the given lengths tu" i** u triangle'
given string
ii) Write a python program to generate all permutations of a (8)
using built'in function.
. (oR)

b) example. can
i) compare lists and array with--v--F---r--' - list be considered as an (6)
array?Justify. '
strings are
ii) Write a python function are Anagtamt Oto check whether two
and are Anagram20 to
anagram of eaeh other or not *iUr Uilitt-in siring function
cheik th- J;r;;ttilil;ng built'it, Jttit g function' (10)

t4. a) i) DefineDictionary in python. Do the fo-llowing operatione on dictionaries.(10)


1)Initializetwodictionarieswithkeyandvaluepairs.
ii) Compare the two dictionaries with master key list and print missing
keys.
iii) Find keys that are in first and not in second dictionary.
iv) Find same keyp in two dictionaries'
v) Merge two dictionaries and. create a new dictionary using a single
expression.
with example. (6)
ii) what is list corqprehension in python ? Explain
(oR)
90277 -4- I lillt illil|fft il]t ilttilt lilt

b) r) What is tuple in python ? How does it differ from list ? (8)


ii) write a python program to sort n numbers using mergesort. (8)
15. a) il What are exceptions ? Explain the method to handle them with example. (8)
ii) write a python program to count the number of words in a
text file. (8)
(oR)
b) i) How to Merge multiple files in to a new frle using python. (6)
ii) What are modules in python ? How will you import them ? Explain the
concept by creating and importing a module. (10)
t

j
Reg. No. :

Question Paper Code : 80173

B.E./B. Tech. DEGREE EXAMINATIONS, APRILA{AY 20 1 9.

First Semester

Civil Engineering

GE 8151- PROBLEM SOLVING AND PYTHON PROGRAMMING

(Common 16 all Branches)

(Regulatio n 2Ol7)

-./ 'Time : Three hours Maximum : 100 marks

Aqswer ALL questions.


. , PART A : (10 x.2 = 2O marks)

1. Listthe symbols used in drawing the flowchart-


2. ' Give the Python code to find the minimum among the list of 10 numbers.
f\
.[e)
v Outline the logic to swap the contents of two identifiers without using third
variable.
4 State about Lo$cal operators available in python language w-ith example.
5. Comment with an example on the use of local and global variable *rrh ,n"
same identifier name.
6. Define recursive function.

: 7. How to create a list in python? Illustrate the use of negative indexing of list
with example.
8. Demonstrate with simple code to draw the histogram in python. .

9. Categorise the d.ifferent types of errors arises during programming. Interpret


the following python code

/home/dinsdale
10. What is command line argument?

\'\ 1
PARTB-(5x 16=B0marks)
*{. (a) Mention the different types of iterative structure allowed in Python.
Explain the use of.continue and break statements with an example. (16)

Or
(b) (t What is an algorithm? Summarise the characteristics of a good
algorithm. (8)
(ii) Outline the algorithm for displaying the first n odd numbers. (8)

12. (a) Describe about the concept of precedence and associativity of operators
with example. (16)

Or
(b) (i) Mention the list of keyrvords available in Python. Compare it with
variable name. (8)
(ii) What are statements? How are thev constructed from variable and
expressions in Python? (8)

13. (a) (t Analyse string slicing. Illustrate how it is done in Python with
exa'nple. (8)
(ii) Write a Python cod.e to search a string in the given list. (8)

Or
(b) (r) Outline.about function definition and call.with example. (10)
(ii) Why are functicins needed? (6)

1a. (a) Demonstrate with code the various operations that can be performed on
tuples. 5 (16)

Or
(b) Outline the algorithm and write a Python program to sort the numbers in
abcending order using merge sort. (16)

15. (A) Explain about the file reading and writing operations using format
operator with Python code. (16)

Or
(b) (t Explain about how exceptions are handled with example. (8)
(n) Design a Python code to count the number of words in a Python file.
(q)

80173
V,S.B ENGINEERING COLLEGE, KARUR

Academic Year 201 9-2020(ODD Semester)

CE 8I5I. PROBLEM SOLVINC AND PYTHON PROGRAMMINC

Nov/Dec 2019 Examinati'on - Answer Key

PART-A

l- t'he efliciency ot'an alsorithm is analy'ze<i b,v- fincling oul rheir space and tirne complexity. ...
The time and space contplexitv shoulcl be mirrimum as rvell as thc algorithm should satisfy
all dillerent tesl cuses frlr a giverr problem.

2. An algorithm is a set of steps to be followed in solving some pafticular problem. Flowcharts


and pseudo codes are representations of algorithrns.-... po, .*urpl., a pseudo .oa" io1.
printing the sum of all numbers between I and 100 would be: A flowchart is more of a
diagririlttrtllicrc1rr'elsetl1iltitltlrrl.iji,'lrlgtrt.itltttt.

3, A conipiler is a translatot'rt,hich lransfbrmssource lanruage (high-level language) into object


langLrage (nrachine language). lrr contrast with a comp"iler, an iit.rp.et., is"u p;";r;;
;;;
irnitates the execution of progranrs rvritten in a source language.

4. Python Program for cube sum of first n natural numbers

Stttti ol'sclie's lt., ft* it J Jl * . .....+ nl till n-th term.


Examples:

def sumOfSeries(n):
SUM:U i
for i in range(1, n+l):
sum +Ji*i*i , '

' retr-rrn sum


" ' :

# Driver Function '

n=t'
pri nt(sumOfSeri es(n) )
:

5' No. The Do loop doesn't :-


have else clause in python. 'else' clause is used in While. For. If.
Fxception handl ing methods.

6. 1: ['one','two','three',,four,]
for i in range(len(l)):
print(l[i], end =t' ")
Output :
One two three four

.a

{,q
vt t t
1 appendQ: Adds a new entry to thc cnd of the list.
clear0: Removes all entries fionr lhe list.
copy(): Creates a copy of'the clrn'ent list and places it in a new list.
extendQ: Adds iterns from an existing list and into the current list.
insen0: Adds a nerv entrv to the position specified in the list.

def test2():
return 'abc', 100, [0. l, 2]
a. b, c: test2o
print(a)
# abc
print(h)
# 100 .

pnnt(c)
# [0, l, 2]
.

9. ^:^
Python Command Line Arguments. Python Command line arguments are
input parameters passed to the script when executing them. Almost all pfogramming
lanctiase provide supporf f'or conrnand line arsuments. Then we also have command
lirte opriilrts t() scl \onru specific irplirrlrs for the pl'ogram.

10. renameQ method is used to renanre a file or directory. This method is a part of the os module
ancJ comes extremely handy. Syntax fbr os.renameQ : os.rename(src" dst) : src is source
address of file to be renamed and dsr is destination with tlre nen'name. f

Jtr ifclctc ii trlc.'inr.;lor"t thc OS rr,,,Jiu1c *nd run its os-remove() tunctiorr: ,' ,

Example:Remove the flle "dernofile.txl"i: i " .


import os ,,t ,

osremovd("demofi le.txt")

llai :

:- .: :::i
P.vthon is an irrterpreted. ob.ject-oriented programming language similar to PERL, that
has gained popularity because of its clear syntax and readability. ... Python offers dynamic data
type, ready-made class, and interfaces to many system calls and libraries. It can be extended, .:..:

using the C or C++ language.

Types of Programming Languages

. Proccdrrral Prnrnullr:i,11 Ilrngtraue'. .

o FunctionaI Programming Language. ...


o ()t'r.icct-tlrictttccl l)roQt'lrrttttlilrl l,attguage' "'
. . Scripting Programnring [-.anguage' .-,
r Logic Programming I.anguage, ."
o C++ Language. ...
o C Language. ...
o Pascal Language.

Advantages of Python
Compared to other programnring languages Python is the most broadly applied by the

developers lately.
The main Python language advantages are that it is easy to read and easy to learn. lt
is

easier to write a program in Python than in C or C++. With this language,


yo' gu]l-
:h.'
ytpssibilit,r,to think clearl;- rvhile coclirrg, which also makes the code easier to sustain' Which
r"Or".r ti.," .ort for maintenance of tile program and seen as one of Python programrning
advantages

python has some unique characteristics that are valuable for programmers because they
make coding easier,
An irnportant advantage of Python language is that it has wide applicability, and is
extensively used by scientists, engineers, and mathematicians.

D isadvantages of P.vthon
As an interpreted language, Python has a slow speed of execution.
It is slowerthan C and C++ because it works with an interpreter,.not the compiler.
The language is seen as less suitable tbr mobile development and game develbpment.
Developers like Pvthon for its simplicity in learning and coding.
I I i
lI a- ::il ,

// if Fibonacci number is less than 2,


// its index will be same as number
.,'.-".^.-'.^
if (n <: 1)
,.ruro ,i,

inta:0,b=l,c=l;
intres= l;

lliterate until generated fibonacci number


// is less than given fibonacci number
wlrile 1c < n)
i
ii'i
{2'.:
_.::a:: .. ,

t r2s keeps track ofnlmber,of generated


=,.
..'.':j;',' I
,
i=;i
// fibonacci number: ,: , l

.. I

i: "
l a=b; :

;1i+i b: c;
:;'..t- i
,:::i..' ll,
l.:;?;:::,::-.::
ii.turn,..;
'
-;:;-,,,
1,,' 'l'

int rnain() ' -i


.in'a.
-;,;.,t:'l:' t :,::; ,',, ,' , ,'
'lii , int result = findlndex(21);
i:' ..',:
:..:,4,.:...,
pri nt("%d\n ", result);
t'i-.:.''
al:!ia:iil.: )
,,.
,,, Output
f
-."

F
llbi
ll b ii
,:.. -
.
::,:";:. , :

,def,sieve0fEratosthenCs(nll' '1' '

', priiiie =.1True for t in'r6nge(n + l),J l


p=2
white (P * p .= n),
# If primelpl is'not'changed, it is a piime
if (prime[p] == True): "o'it
# Llpdate all multiples of p
for i in range(p * 2,n + l, p):
prime[iJ = False
,' .p"*:1',r' ;' ::
,' Prirne[0]= False '

False '
1rime.[1]=
for p in range(n + 1):
-'if prirne[pl:
r','."-LI.)'
pflnt p,
if nalne ==r main ''
n:lO -
print 'tFollowing are the prime nrrU.r, smaller",
print 'than or eq=ual to", n
:i.:
lieveOfEiatosthenes(n)'
i' Outpirt:
..
Following are the prime- numbers below 30

23s7.llt317192329, .,
1',t^ i
''
;;ghtRotate(tists, num):
'
'
_ . i"iiii;'];;l],'",
n no' n !o
i^l;i;;;"""il"r,rrom ro the
tl;#tl:ffi::lT;rilt"_;Ii,1,,,,
,ffi,li1Tff:1H'3iii;n,iff
new risr
rhe ni
ren(rrsts)): ; t'
,:

,I # Will add the values before ,.

r,.j:1.:

.'
. , :t
BASIS FOR RECURSION ITERATION
COMPARISON

The statement in a bodY of Allows the set of instructions to be


Basic
function calls the function itself' repeatedlY executed.

ln recursive function, onlY Iteration includes initialization,


Format
termination condition (base case) condition, execution of, statement
is specified. within loop and update (increments
and decrements) the control
variable.

A conditional statement is The iteration statement is ,

Termination
included in the bodY of the repeatedly executed until a certain
- force the function _.to condition is reached.
:-----.--- to
function
-

return without recursion call being


executed.

Ifthe function does not conve[ge If the control condition in the'


Condition
to some condition called (base iteration statement never become
case), it leads to infinite recursion' false. it leads to infinite iteration'

Infinite recursion can crash the Infinite loop uses CPIii cYcles
infinite Repetition
system. repeatedly.
t,

'
Fast in
.:- execulion. '. ' '
Spqed
,
t ,.,.:
:,,.,,, : ",
".a,:a:, ' .

Size of Code ;:,;;;n.,;i*n Iteration makes the code longer'

"od. : , t,t
" ,', .'',t.
,t ,
' ' '
,. ',tt.,t,,,,

'^'
The statement in a bodY of Allows the set of instructions to be
Basic
:1, - :
function calls the function itself. repeatedlY executed.

+-
....:,-;.'.r'

: ::,
".::tj, I ,t :r :,:l

-':
print(rightRotate(list_ l, rotate_num))
Output:
t456r??t
L.tvtvr.)-r-!

l2a ii

When rve calla lLrrctiort vr,ith sonrc riilues. these values get assigned to the arguments accorcJing
. - .t. -'
lo theit'position. ... Pvfhon allorvs f Lrrrctions to be called using kevword arguments. When we
call functions in this way, the order (position) of the arguments can be changed.

deffunc(a, b:5, c:101:


print'a is'. a. 'and b is'. b. 'and c is'. c

func(3, 7)
func|s;, ci4)
func(c=5O,'a= 100)
v.

l,-:' , Output,
is l0
a is 3 and b is 7 and c
ais25 and b is 5 and cis24
- ais 100 andb is 5 and c is 50

Python Default Arguments


In.p-vthon can provide a defbrrli value to an argument by using the assignment operator

lrn.-ljsr.ec1uirciJ(lltatltleitlt..ritiLrringrrcall.ontheotherhand.tlreparametermsghaS
'
a default value of "Cood ,r',orningi " .

def sum(a:4, b:Z): #2 is suppliecl as default argument

rrrt
. 'fThis function will print sum of two numbers
- if the arguments are not supplied
it rvill add the default value """
plint (a+b,1
sum( I .2) #callingwith arguments
sum( ) #calling without argumenrs
Output

6
j ::l
t2bi
def Nmaxelements(l ist l, N):
final_list = []
for i in rang"i-0, N;,
maxl :0
for j in range(len(listl )):
if listlfil > maxl:
maxl : listl[];
list l.remove(max l):
final-l ist.append( max | )

print(finaUist),,,,
. : ,,,
'

# Driver code
listl = 12,6;41,85,0,3,7,6, l0l
N:2
L:

t85

1z.b)ii)
ii) def triangleQ:
s l=int( l2)

l' s2=in(12) , ,

li s3=int( l2)
i(sl=:s!;=s3); ,
i
.

it:' prinr(?ssible to formliiangle'l) ,

,
else:
?; prTn!:Not possi ble ro ftorn'triangte,')
triangtre$ ' :

i; tr.iili "'
from itertools import permutations
def al lPerm utations(str):
permlist : permutations(str)

for perm in list(permList);


print ("join(perm))
if name == "--main-":
str__'ABC-
uiler.r*o,ions(str)

OUTPTJT:
ABC ..

ACB
BAC
:.
:: : :
:

, ,
BCA.: I

CAB.]...ii'....'...'......,.;....
CBA

.'-.',*:"|astrvoa{1str'uctures,t'istsandt,npies,thatconsistofa|istofoneormo
'
, elernents' The elements of lists gr
or tuples ean be numbers or strings. horh Lists
strinss- or both. wiil
rwe will
[,ists (we
:

..
individual '-
FbeHffi:*i;-:;:##
i,; discuss tupleb later) are defined bv
by a pair of sqiare
squaie brackets on either end with individual
either'end
: fT:,11f'.ff,f,:
...#
nrodule has ro be inrported as:
fiorn array import *
-lhen
an arrav has to he declarecl as:
arral'l D = array(typecode, | | n itializersj)
Here, 'arrayiD' is rh. :r;o;.oa.' the type ofiarray and .rnitiarizers,are
"m. "r"";;r;;,
the values with which an arrav is initializec.l ',

rny_arra)' = array(' i'.1 1,2.3.4])

Tnhle .1.1 T.vpescode.s in P.rthon erru.t'q


'l'ypecode
Description
.b'
signed integer of size I byte
!B'
unsigned integer of size 1 byte
U
characterofsize lbyte
'Lr' unicode character ofsize 2 bytes
t
'l^II signed integer of size 2bytes
II Lrrrsigrred inte.qerof'size 2 bytes
I
si-ened integer ol-size 2 hytes
irl
I
unsigned irrtegcr of size 2 b.ytes
unicode character of size 4 b,vtes
rlt
signed integer of size 4 bytes
'L' unsigned integi:r of size 4 bytes
floatin_e point of s ze 4 bytes
'ti
tloatinq point ol's ze 8 bvtes

Sample Code
::: :.a'.
: i:j:r i
fiom array import + .
':::i.

: array(' i', 11,2.31)


Tvl:ruy
for i in myArrav:
pflnt r

Sqmple Output:'.
l. : '
ti,.,. .t'', '
2', ,;.t.; , l

;,;:,''"','t: .--

rs,u)iii

..
print("T'he strings aren't anagrams.")
s I ="listen"

s2 ="silent"
check(s I . s2)
Outl'rut:
The strings are anagrams

14 a) i) Define Dictionary in python. Initialize two dictionaries with key and value pairs.

. Dicticlnarf is one ol'rhe compouncl data type like string. list and tuple.
. In dictionary the index can be' immutable data type.
e It is a set of zero or more ordered pairs(key, value) such that:
o The value can be any type-
o Each key ruy o..r, nnly on"" in the dictionary
o No key may be mutable. A key may not be a list or tuple or dictionary and so on.
o A dictionar:y is set o1'pairs of value with each pair containing a key and an item and is
enclosed in curly brackers.
r There are two ways to create dictionaries.
o It is created by specifying the key and value separated by a colon(:) and the
- elements separated by commas and entire set of elements must be enclosed by

o dictQ constructor that rrses a sequence to create dictionary.

Examnle.nv i
d1:{].fruit,'2ivegetab|esl,3;'cerepls'}
d2:dict({'name':'aa','age':40rr; ' ' , , ,

, [1])
print(dl : ,

-^'
print(d2) : :
t l
,'
Output:
fruit ,, .. .

- l
ii) Compare the two dictionaries with master key list and print missing keys.
In python, dictionaries are containers which map one key to its value with access time
complexity to be O(1). But in many applications, the userdoesn't know all the keys present in
the dictionaries. In such instances, if user tries to access a missing key, an error is popped
indicating m issin g keys.
import collections
defd = collections.defaultdict(lambda : 'Key Not found')
:

::' a.
defd['a'] = 1

defd['b'] :2
print ("The value associated with 'a' is : ",end:"")
prinr ldeld['a'J)
# printing value associated with 'c'
print ("The value associated with 'c' is : ",end="")
print (defd['c'])

a.!ry
T'he value associated u,ith 'a' is :I
..:
The value associated with 'c' is : Key Not found

iii) Find Keys that are in first and not in second dictionary.
print("initial dictionary", str(ini_dict)) : .

# finding duplicate values ,

# from dictionarv
# using a naive approa.h
rev_tict:{} :' : , .

fbr key, value in^ini_dicLitems$:


rev_dict.setdefau I t(val ue, set0).add (key)
result : [key for key, values in rev_dict.items0
if len(values) > ll
# printing result
pr:int(l'dupllcate valuesl', str:(result))
l4 a) ii) What is list Comprehension in python? Explain with example.
. List comprehension is used to construct lists in an easy and natural way.
' . lt create a list with a subset of elements from another list by applying condition.:
. The list comprehension makes code simpler and efficient.
. The execution is much faster than for loop.
Example.pv
x=[i for i in range( l0)]
print(x)
xl=[i lbr i in range( l0)if io/o2::Ql
print(x l)
*2=li*2for i in range(10)l
pnnt(x2)
vowgl S=('a'r'et,'i trto'r'Ll')
w-,'-h3ll1"
x3=fch
'
fcrr,ch in w if ch in vowelsl tl
,l l
print(x3) ., ,.
-:
, ,.:

Output:
[0, l, 2, 3, 4, 5, 6,7 g, g]
:^'-' -'--' ^'.-' "' ", '- : : :

[0, 2, 4. 6, 8]
-t0,2, 4,6, g , I 0, 12, 14,1 6, I g]
tot]
[tet,

14b)i)Whatistup|einpython?Howdoesitdifferfrom|ist?
, . , ', , ..
o A tuple consists of number of values separated by commas,and'drclosed within
parentheses.Tuples are similar to lists.Tuples are immutable sequences. The elements in
the tuple cannot'be modified.The difference between tuple and lists are the tuple cannot
be modified like lists and tuples use parentheses, whereas list use square brackets.
Examnle.pv
its:('apple','orange' )
fru
print(fruits)
Output:
('upple', 'orange')

Creating and Accessing tuple


l uples can be creared by putting ditferent values separated by commas and enclosed
w thin parenthes s.
Eiamnternv
___t
l-=-1T
,

^.,
nll_1t,Z,l;

#Nested Tuple
n I =("python",[' list',' in','tuple])
print(n l[0])
print(n2F J)
#rnixed tuple
,1=1j,,,aaa,,)
nos,value=m I

print(nos)
print(value)
Output:
(I l:r)
pl thon
[' I ist',' in','tuple']
i

aaa

S.NO LIST TUPLB


I Lists are mutable Tuple are immutable

2 lmplication of,iterations is Time- Implication of iterati ons' i s comparatively'Faster


onsumrng

J The list is better for performing Tuple data type is appropriate for accessing the
operations. such as in'sertion and elements
dr'let ion

4 Lists consume more memory Tuple,consume less memory.as compared to the list

5 Tuple does no have must built-in methods.

6 The unexpected changes and errors are In tuple, it is hard to take place.
more likely to occur

mb gm g

iil:;:::::::::::::::::;:
for i'in range( l,n I +l ):
b:int(input(" Enter element: "))
a.apperrd(h)
ber or em en ts:"))
f;'il';il:i;T;T,lim 1'

el emen t:" ))
5'#:'ffiT'rEnter
new.sort()
print( llsortedlistis:'l-neu') I , : ':,, , - :

Output:
Enter number of elements:3
Enter element: l0
Enter element:0
Enter element:45 i

Enter lrLrmber of elemerrts:2


Enter element:78

:"':',"j:':"1:e. ^ 45,78,99J
Sorted list is: [0, 10,

15. a) i) What are exceptions? Explain the methods to handle them with example.
The try: block, include an except: statement. followed hry a block of,code which handles
thcprrlblentasclegaltt|-rlsprrssiblc'.
Syntax ' ,
.. '

trv:
You do your'operationS'.here; '

except Exceptionl: '

lf there is Exceptionl. then execute rhis block.


e,rcepf Exceptionll
If there is Exceptionll. then execute this block.

;ff;r. is no exceprion then execute this btock.


..
l.The except Clause with No :*' '""
"r"-n, with no exceptions defined as follows
You can also use the except staremenr -
:'t:.:: try:
:,t:i
,.:
tt..!
You do your operations here;

except:
If there is any exception, then execute this block.
it'.a. '

ii;. '

Tra-;
Due to any exception,,this y be,skjpped.
#l
i:,:ji;,,:.
li rrally':
This would always be executed.
+::."
#"' ' .
We cannot usE else clause as well along w'ith a finally clause, ;
i:{:.'., Example.pv(divide bv 0)
try: , ,,, '

?is, x=I0/0:
pri nt("Never executed ")
i. except:. .

r ,,
.;j ,

print("this is an emor message")


Output:
:i= this is an error message
Examp le.py (except statements)
;-
ty:
,.
:ti : a=int(input( "Enter a :"))
:ua -r' b=int(input("Enter b:")) :
:
print(a+b)
print(a/b)
except ArithmeticError:
{ print("Divide by 0")
:
Output:
O]ta-, , ,U
Enter b:0
10 ';

.tit-.',

find the fiie")


Welcome to world of robotics
be inresring
Il:':'l
I hrs rs the end
File closed
0utput:2
( lrrnor lind the lllc

User-Defi ned Exceptions


Pyhon also allows;;; ;; create your own exceptions by deriving classes
from the standard
built-in exceptions.

ii) Write a python program to count the number of words in a fext file.
15 a)
ll'orrr crlllccIiorrs irnpor.t ( ourrLer
f,
fn:input("enter the file name")
c:open(fn. "r")
prinrl"no. of words in the file,,)
:
pnnt(uounter(c.readg.sptru))
c.close0
Outpirt: ' , '

]I
enler the Itle namee:/sotrrce.txt
^:a.-

no. of words in the file


,python,:
Counler({'welcome': l. 'to,: l, I, ,i,: I,'am,: l, 'using': l, 'module': l))
15) b) i) How to merge murtipre fires in to a new fire using python.

import os
fi le names : os. Ii stdi r(z f)i rectorvNa nreW ithA I lTursgl5/,
I
otltput - " .

for file in file_names:,'


with open(file) as,f: , '
content: f.readr"t).srflp('\n')
output *: content + ,\t0\n'
with open('OutputFileName', .wb') as f:
f,write(output)

15) b) ii) What are modules in python? How will you import them? Explain the
conceot bv
creating and importing a module.
1,,. . I Simply, a module is a file consisting of Python code. A
r--r^ ^^-,.1^fi
module can define f',nnfin
-- functions'

,'' classes and variablcs. A nrodr:lc .on als,, itt'clu<Je runnable


code' I
l', Types of modules:
l. Pre-defined modules
:: 2. User-defined modules
,1,'
,
.-'
;;;;t;;';;;;;""
i;"; modules are already defined in python package itself.
;;;; ilt math,random'calendar'o'''y',nutpy'string etc''
'-,' 1, Exampfe.nr' l

irnport math
print(math.sqrt( l6))
Print(math.Pi)
OutPut:
''.,'
.: 4
,,.,.. 3.1467
: ,, User-tlelined modules
. These modules are created by the user' :

.'-. .,' Userhastb''writefunctiondefinitionsinafileandgiveanamewithanextension'p; '

rThenisnameusedinpythonprograma|ongwithimporto.'Yo,o.^.
ile has ro be executecl before the execution of python program'
- Exarnple (calc.qY)
,
de I add(a.b)

:.
c=a*b
return c
'. def sub(a,b)

dtfmul(a,b) : i
, : :

:.:
return c
def div(a.b)
c:alb t,,
:
return c
def mod(a,b)
c:aYob

'fi]:;;
il:il{lllj1;'u
print(calc.s ub(!,2))
pnint(calc.mod(4,2))
0utnut:

o an import Statement ln Some


Python source file can be used as a module by executing
other PYthon Ol.:
:oyce ^

to"J;il;fl#f
'' ::iJil;ll,, you import specinc attributes rrom a modure into the current
nurn.rpur..i.eonlywhensomemethodsareneededfromamodule'
Syntax:frommodnameimportname|.name2,'.'namen
Example: from calc imPort add
3. Aliasins Modules
. tt is also possible to give another ttatne to the existing modules'
o This is done using 'as' keYword'
s'' n,o*' i;;;;;;.-;;" ,, u,,,,,r'.'.-nu"
-
n'xu*,ptet imPort math as rn . '

tult
Reg.No.:lo e R |
Question Paper Code : 60035

B.E./B.Tech. DEGREE EXAMINA'TIONS, APRIL/MAY HO88

First Semester

Civil Bngineeri1g

GE 3151-PROBLEM SOLVING AND PYTHON PROGRAMMING

(Commonto: All Branche8)


(Regulations 2021)
Time: Three hours Maximun 100 marke
Answer ALL questions

PARTA--(10x2 20 mark8)
1. Write an algorithm to find smallest among three numbers.
2. Which is better iteration or recursion Justily your anéwer

3 List any four built in data types in Python.


4. How do you assign a value to a tuple in Python?

5 What are the purposes of pass statement in Python?

6. What is Linear Search?


7. Give examples for mutable and immutable objedts

8 What is purpose of dictionary in Python?

9. List any four file operations.


10. Write a python program to Count Words in a sentende 1sing spilt 0 funetion

PARTB ( 1 6 B0 mark8)

11. (a) Listout the control flow statements in P'ython and explain repetilion type
in detail with a sample progra

Or

(b) What is recursion? Wrile and oxplain n P'ython progr#m to findl fatorin
of number using recursion
12. (a) Why do we call python as
interpreted and
language? Also explain about object-oriented
Interactive Python programming
Or

(b) Write and explain the python program to swap two


without temporary variables. numbers with and

13. (a) What is difference between break and


continue in Python?
suitable examples. Explain with

Or

(b) What is string function in


Hython? Explain any three Python string
methods with an example.

14. (a) Define Python Lists. How to add elements to the list?
suitable example program. Explain with a

Or

(b) Explain bubble sort


algorithm using Python programming.
15. (a) Why does Python require file handling?
with all modes. Explain opening files in python

(b) Give brief notes on Python


a
and finally statements. xception Handling using try, except, raise
Visit For More : www.LearnEngineering.in

GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING

Question Bank

UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Part-A

1) Define Computer
2) Define algorithm

.in
3) What are the two phases in algorithmic problem solving?
4) Why algorithmic phase is a difficult phase?Justify
5) What are the steps involved in algorithm development process?

ng
6) Compare computer hardware and software.
7) State some properties of an algorithm.

eri
8) What are the three building blocks of an algorithm?
9) Define Input , Output , Assignment statement
10) Describe different notations in algorithm and classify each.
11) Define pseudocode.
e
gin
12) Define the rules to be followed on pseudocode.
13) Define flowchart.
14) What are the different types of flowcharts?
En

15) What are the symbols used in flowcharting type?


16) Describe the Data Processing Symbols in Flowchart.
17) List some guidelines for drawing flowchart.
arn

18) List the merits in drawing the flowchart.


19) List the demerits in drawing the flowchart.
20) Explain some of the qualities of Programming Language?
Le

21) What is the difference between the algorithm and the program?
22) Give the pseudocode to check the biggest of 2 numbers.
23) State the differences between Iteration and Recursion.
w.

Part-B
ww

1) Explain in detail about Algorithm (16)


2) What is pseudo code? & how it will be used to solve a problem? (16)
3) Define Flowchart and explain symbols used in flowchart with example (16)
4) Write the Algorithm, pseudo code & draw the flowchart for Towers of Hanoi (16)
5) Develop an Algorithm, Pseudocode & Flowchart for minimum in a list (16)
6) Develop an Algorithm & Pseudo code for Guessing an integer Number (8)
7) Explain with example the building blocks of an algorithm (8)

Visit For More : www.LearnEngineering.in


Visit For More : www.LearnEngineering.in

UNIT 2 – DATA, EXPRESSIONS, STATEMENTS

Part-A

1) What is a program?
2) Define Computer languages.
3) How computer languages are classified.
4) Define assignment statement.
5) List the statements in python.

.in
6) Given the strings x=’alpha’ and y=’beta’ print the following string operations.
7) List some of the keywords in python.
8) Define Identifiers in Python

ng
9) What is the comment statement in python?
10) Define variables in python.

eri
11) Explain Input and output statements in python.
12) List the data types in python.
13) What are the operators in Python?

e
14) Solve the mathematical expression 7/3 * 1.2 +3/2.
gin
15) Define functions in python?
16) Explain the precedence of operators in python.
17) What are the function arguments used in python?
18) List the types of functions.
En

19) What is the anonymous function in Python?


20) Define modules in Python.
arn

21) How modules are incorporated in a python program?


22) List some of the built-in modules in python
23) Write a simple program to add two numbers in python.
24) Write a simple program to convert KMPH to MPH in python.
Le

25) Write a simple program in python to convert decimal number into binary, octal and
hexadecimal number system in python.
w.

Part-B

1) Explain various types of operators used in Python (16)


ww

2) Explain Values & types supported in Python (16)


3) What are the different function prototypes? Explain it with suitable example (16)
4) Explain Interpreter & Interactive mode in Python (8)
5) Write a program to Circulate value of N numbers (8)
6) Explain about various statements in python (8)

Visit For More : www.LearnEngineering.in


Visit For More : www.LearnEngineering.in

UNIT 3 – CONTROL FLOW, FUNCTIONS

Part-A

1) Define Boolean datatype?


2) What are the conditional statements used in python?
3) Define if…else statements in python.
4) Write the syntax for ternary operator in python.
5) Define chained conditionals.

.in
6) Write the syntax for if…elif…else conditionals.
7) Define Iteration.
8) What are the different iterative statements?

ng
9) Define range() function and its syntax.
10) Define while loop.

eri
11) Write the syntax for nested for loops and nested while loop statements.
12) What is python break statement?
13) What is python continue statement.
14) Define fruitful functions in python.
e
gin
15) What are the types of parameters in functions?
16) What are the various parameter passing techniques?
17) Write the scope of the variable.
18) What is recursive function and its limitations?
En

19) Write the merits of using functions in a program.


20) Write the syntax for composition.
arn

21) Define strings and name some methods.


22) List some of the methods in List Operations.
23) State the differences between linear search and Binary search.
Le

Part B
w.

1) Explain in detail about Control flow structures (16)


2) Explain Various String functions used in python (16)
3) Write a Python program to compute the factorial of a given number using recursion (8)
ww

4) Write a Python program using while loop first N numbers divisible by 5 (8)
5) Explain the concept of Linear & Binary Search with Python program (16)
6) Discuss Function arguments in Python (16)

Visit For More : www.LearnEngineering.in


Visit For More : www.LearnEngineering.in

UNIT 4 – LISTS, TUPLES, DICTIONARIES

Part A
1) Define List?
2) What is cloning of List?
3) What is aliasing?
4) Define tuple.
5) Explain Tuple Assignment with example.
6) What is slicing?

.in
7) Define Dictionary.
8) Give an example for List comprehension.

ng
9) What is mutability?
10) List the functions of tuple data type.
11) List the methods of list data type.

eri
12) Comment on tuple as return type.
13) When a dictionary is used instead of a list?
14) Differentiate between append() and extend() methods?
e
15) What is the output of print list + tiny list? List =
gin
[‘abcd’,786,2,23,’john’,70.2],tinylist=[123,’john’]
16) What is the difference between tuples and lists in python?
17) What is the difference between del() and remove() methods of list?
En

18) How to merge two dictionaries?


19) Define mutable and immutable data type.
20) When is dictionary used instead of a list?
arn

Part B
Le

1) Explain the following:


a. List Slicing &List Mutability (6)
w.

b. List Accessing Methods &List Comprehension (10)


2) Explain Selection & Insertion sort methods with python program (16)
3) Explain Merge & Quick sort methods with python program (16)
ww

4) Explain Dictionary Operation & Methods (16)


5) Write code snippets in Python to perform the following
a. Accessing Elements of a Tuple (5)
b. Modifying Elements of a Tuple (5)
c. Deleting Elements of a Tuple (6)

Visit For More : www.LearnEngineering.in


Visit For More : www.LearnEngineering.in

UNIT 5 - FILES, MODULES, PACKAGES

Part A
1) Define File.
2) List the file opening Modes.
3) List the different ways to read a file.
4) What the difference is between append and write mode?
5) What are the attributes of file objects?
6) List the methods in file objects.

.in
7) Differentiate Errors and Exceptions.
8) Illustrate try-except-else

ng
9) Define modules.
10) Define packages.
11) Define pickling.

eri
12) Give the mechanism to handle exceptions.

Part B

e
gin
1) What are the two types of files? Explain different file operations (16)
2) How will you create a Package & import it? Explain it with an example program (16)
3) Write a python program to count the number of words in a text file (6)
4) Explain the concept of Exception Handling in Python with suitable program (10)
En

5) List out the types of Modules and Explain any two types in detail (16)
arn
Le
w.
ww

Visit For More : www.LearnEngineering.in

You might also like