Python Univ QP
Python Univ QP
:lo e R |
Question Paper Code : 60035
First Semester
Civil Bngineeri1g
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
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
Or
14. (a) Define Python Lists. How to add elements to the list?
suitable example program. Explain with a
Or
. 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
?
''
(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.
"'.
8,- Givg a fttnction that can tak6 a value and return the first key mapping.to that
' value in a dictionary.
'.
\ 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)
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.'
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
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.
8. Give a furrction that can take a value and retum the first key mapping to that value in a dictionary.
defadd(a, b):
"""This program adds two
numbers anl return the result,',,,,
result: a + b
return result
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
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
-{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
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
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
C*x-r'lparfsr*r1,sFeFai rE
EquaNiity sF*rstsrs
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')
retum [expression_list]
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:
>>> 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
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* ' {
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
{*{sTsl.il*F$
Tls.xtiee'qry. nhr qlm,ln*r*m.,nr*. tri*tx.:
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.
exsept ?*Effxr:
, rs{nfr}ls.{rls*'
A& ca;pee*:EF#.
& awit€{id:
:*tU". rs )Fil s!
I Sb).Exception handling
t:t!1M
mgffiae
$*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!
{*t
I{r,g. lon.
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 ?
I l- a) i) Draw a {low chart to aceept three distinct numbers, find the greatest and
print the result. (8)
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
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,
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{"
i4t ^>b) : r
PdtDt C " frao.-^}esl t,ut'-ben 'nn , o)
etEe- :
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
E* ...
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
E"
c Storua-aai r.r'Cr,-0c-
-"/
{l-+ +ibt> '.
arb
=@rl -)
t.
,,shi.le t > F)
Van+Cb)
A,r) =brafbl I
r. a> b .{{
Ptl ttl o
Xr"otect
.!
\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
zsL".-?e
I
, Aor4- .*']"s :
,) .^t .,u,-- dt k c^^- t'e- "o*J *-+ a- [it^^-'
- 11+
o^-r'u
-l
i4 U '-?P* r'''st aLlc- Frl a- Kl--a-L
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
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@+=
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
-K i< ?@ a-*7."*.'^t * }e re :t
[
ctY' ae"^*--a'L--S ,Fo
I
lr."^ J
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^- ' -;
' lo t \
,/
.l
e..l e v -luA--.>l r,-qi-.e',a \U
&c
o , \#" gcr'T to d_o
vt-{--
rn: Scsre-aCo)
O"41*t '
.,
E''+'- n ao
nLe- ,>.,--rtr o.,t *,*f N ex+-* n"-"'?e:V tt ltD
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" ^'
i+ f nr-r-t'nlo:
1+ D^l-rnn = =- o '.
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'-'.,"-"*
.,
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
-fu {""'^{7 -p
-tL c.-.'^A f4 '. L
B"tF--k sl-I't^<r-t : .
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 '-
G"rfi*-
tx^-.",'gta :
i4 .{rd,-v =- ='{'
(rrr+4n-r*..la.-
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 \.-/
.o
ttfitL rne-c!-{3;dr>
"
i1 ':=
.f.C-|ro-.-*.
4so
rc-**-rn h..k +a-P (n -- r)
E.,$* N:F
nt^r- {.-o-$..,fi*tr iE \a-o
'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
, 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
1:^$-r f -ot^"^-0i"'"'
I
.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-
?t c =-o
+r."..4 : F*.Qaa
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'-
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
!ac?Fi"-' = [uco.]?"'n
ta-;rc-a";"-{-)
D*4 t
r8 vL e4 q3 i
\4Je Dr"*igli*r
tt ' *^*
"-*ET i n f-,-t^t
^^4
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- .
QuXSoq A
C+ fU.oryt- iS
. O- C M
[r.""?ff.rn 3 , than exoetfu- ]f,} H".-p
Qrrclj+*
rl Lr.^-+t*t> ! I
.,1 .-
e)sa '-
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-
n
dt ?6u. "f"^- to
.^-!J-"^r3 L.ra--fre-
t.*- sr.r.)
b.i' \t - in atn< .
grq.*t = ^-t
\_--,
et'rof+4"*' 4,r9 ,
I
I tq
(r
*+ t - a-"ti -
\$?
* & oJ'','"<
r:
9
Reg. No. :
{l
Answer ALL questions.
9. What is the use of Algorithm, Flowchart and Pseudo code in the perspective of
problem solving ?
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 ? :
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)
j
Reg. No. :
First Semester
Civil Engineering
(Regulatio n 2Ol7)
: 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. .
/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
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.
def sumOfSeries(n):
SUM:U i
for i in range(1, n+l):
sum +Ji*i*i , '
n=t'
pri nt(sumOfSeri es(n) )
:
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: ,' ,
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, .:..:
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
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 ,
inta:0,b=l,c=l;
intres= l;
.. I
i: "
l a=b; :
;1i+i b: c;
:;'..t- i
,:::i..' ll,
l.:;?;:::,::-.::
ii.turn,..;
'
-;:;-,,,
1,,' 'l'
F
llbi
ll b ii
,:.. -
.
::,:";:. , :
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'
,:
r,.j:1.:
.'
. , :t
BASIS FOR RECURSION ITERATION
COMPARISON
Termination
included in the bodY of the repeatedly executed until a certain
- force the function _.to condition is reached.
:-----.--- to
function
-
Infinite recursion can crash the Infinite loop uses CPIii cYcles
infinite Repetition
system. repeatedly.
t,
'
Fast in
.:- execulion. '. ' '
Spqed
,
t ,.,.:
:,,.,,, : ",
".a,:a:, ' .
"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.
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
lrn.-ljsr.ec1uirciJ(lltatltleitlt..ritiLrringrrcall.ontheotherhand.tlreparametermsghaS
'
a default value of "Cood ,r',orningi " .
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
.
,
else:
?; prTn!:Not possi ble ro ftorn'triangte,')
triangtre$ ' :
i; tr.iili "'
from itertools import permutations
def al lPerm utations(str):
permlist : permutations(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 ',
Sample Code
::: :.a'.
: i:j:r i
fiom array import + .
':::i.
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
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)) : .
# from dictionarv
# using a naive approa.h
rev_tict:{} :' : , .
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')
^.,
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
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
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
:"':',"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:
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 ,
.tit-.',
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.-
import os
fi le names : os. Ii stdi r(z f)i rectorvNa nreW ithA I lTursgl5/,
I
otltput - " .
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'
irnport math
print(math.sqrt( l6))
Print(math.Pi)
OutPut:
''.,'
.: 4
,,.,.. 3.1467
: ,, User-tlelined modules
. These modules are created by the user' :
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:
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
First Semester
Civil Bngineeri1g
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
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
Or
14. (a) Define Python Lists. How to add elements to the list?
suitable example program. Explain with a
Or
Question Bank
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
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
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
25) Write a simple program in python to convert decimal number into binary, octal and
hexadecimal number system in python.
w.
Part-B
Part-A
.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
Part B
w.
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)
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
Part B
Le
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