0% found this document useful (0 votes)
54 views

Python Unit 3

Uploaded by

Charan Cherry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Python Unit 3

Uploaded by

Charan Cherry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

3.

4 PYTHON PROGRAMMING IJNTU-HYDERABAb)

PART-B
ESSAY QUESTIONS WITH SOLUTIONS
3.1 REGULAR EXPRESSIONS
3.1.1 Introduction
09. Give a brief introductionon regular expression.
Answer t
Regular Expressions
as
The regular expression provided an infrastructureto perform certain functions such extraction, advance textpattern
matching and search-and-replace. Regular expressions are in the form of strings including special symbols and characten
representing pattern repetition or several characters in order to match the strings with pattern.
Input Regular expression Output
abc Engine
Mnm
Bar Foo
wdu0 filter
1 "(A —Za abc

Mnm Bar
z4.l wdu0
its

Figure: Filtering the Regular Expressionswith Valid Identifiers


Python provides a standard library remodule to support regular expressions. They can contain text with uppercase
lower case alphabets and numeric digits including or excluding the specialized alphabets.

3-1.2 Special Symbols and Characters


QIO. List out various special symbols and characters.
Answer: Model Paper-u.

Special Symbols
The most commonly used special symbols in python are as follows,

Special symbol Description Example


literal It matches the literal string value literal foo
It matches any character x.x
It matches the end of string /biW*shS
re I /re2 It matches the regular expression rel or re2 f00/bar
It matches 0 or more occurrences of the previous regular expreysion
It matches the beginning of string Astring
It matches I or more occurrences of previous regular expression [a —z] +\.com
{N) It matches N occurrences of previous regular expression [0-91 {2}
It matches Oor I occurrences of previous regular expression. xyz?
It matches the enclosed regular expression and saves it as subgroup. ((0 —91 {2}) ?, x(yzla) pqr
It matches from M to N occurrences of previous regular expression. [0-91 {2, 6}
It matches any single character from the character class [aeiou]
It does not match any of the character from character class [ Aaeioul, [ AA— Za— zo—9
It matches a single character from x to y [0-9), IA-Za-zl
It does not apply "non-greedy" versions of the specified symbols

Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy
Cbgrøcters
1
sr•cjø most commonly used special characters in Python are as follows.
11te
Character Description
Exam le
It matches a decimal digit like (0 —91
data \d+.txt
It matches alphaneumeric character like A-Z.a-zo-9
A-Za-z
It matches as word boundary the
It matches any s cial character C precisely
It matches white space character as of\sthe
It matches the be inning of string. SADear
It matches the saved subgrou nn rice:\20
inn

gsømple
Single Character
botching
symbol is used to match the single character excluding the NEWLINE. It includes letter. number,
Thedot or period(.)
symbol, printable and non printable characters.
whitespace,
Strings Matched
RE Pattern
A pair of characters
A character between x and o such as x20, x$o etc
x.o
.end
It is a character beföre string end

morethan one RE Pattern with alternation (1)


Mgtcbing
A pipe symbol (1) i.e., a vertical bar represents alternation operation. It is used to select one among various regular
separatedby pipe.
expressions

RE Pattern Strings Matched


me/home me, home
got/get/gst got,get.gst
x5c5\v5po x5c5, v5po

CreatingCharacter Class
Sometimes user might need to match desired set of characters. This is possible by creating Character class using [ l. Ihe
expressionwill match the characters enclosed in the brackets.
tegular

RE Pattern Strings Matched


g [aeiouJt gat, get, gef, got, gut
[ry][23] [agl [05] Astring of 4 characters:
The first one is "r" or then. "2" or followed by "a" or "g" and at last 'Y
o" or "5"

3.1.3 RES and Python


QII. Explain in detail about RES and python.
Answer : Model Paper-UI,Q6(a)
Pythonsupports regular expressions through remodule. The core functions and methods of re module are as follows,
Remodule
Function
Function Description
Compile(pattern, flags = O) It compiles RE pattern with any optional flags and returns a
regex object
SPECTRUM
RU-IN-ONE JOURN8L FOR ENGINEERING STUDENTS SIA GROUP
3.6 PYTHON PROGRAMMING t.jNtu
bunctions Reces Obje€t
F u •eti•en
match stun . RV wtth• matO'
'tong. max •tong Mtntetet
O)
mat€bcs
search(patt«n. RE in stung and
nags O) It the first

sub (vvttem. rcpl. stnng. max O) all ot RE pattern in stung with


if max svtded.
find'tet( and returns iterato€
. It fot
tindall (pattern. ot• tn stnn and set or
. flags)) It matches fot
Match Object Methods
sub intu te
It n•tutns the matehi
(num —O) It returns the Icte match
Example
Matching more than one string (i) and single character

3.2 MULTITHREADED PROGRAMMING


3.2.1 introduction
Q12. Write in short about multi threaded programming.
Answer
:
Multithreaded Programming
Multithreaded programming is a concept in which a program is divided into two or more subprograms that
at a time. The part of program or subprogram is called as thread and each thread executes separately. It is a powerful
that enables to write efficient programs by maximum use ofCPU because the idle time of it can be to minim. It
to perform multiple things at a time. A large program can divided into threads, that can be executed parallety.
switches between the threads and executes them concurrently.
It executes every thread so fast that it apFars as if they are being done simultaneously.
For example, a programming task such as MT program with queue data structure can be accomplished withfew
that have certain functions.
i. User Request Thread: It reads client input LO channel. Ihe program creates a thread for each client
sent through the queue.
2. Request Processor: It retrieves the request from queue. processes them and generates the output.
3. Reply Thread: It extracts output dut is to sent to the tset and forwards to local file ot ifbxke&
Use of multiple threads to perform such task can reduce complexity and enables clean and emcient

L06k for the SIA GROUP LOGO on the TITLE COVER beforepubuy
Programming 3.7
and MuttÄhreøded
expressions
3.2.2 Threads and Processes
threads and processes.
in brief about

entities that can share memory and execute concurrently. It is a bur unit ofCPtJ
ned as software
ocess. Multiple threads can be created by a particular process. Each thread shares code, du
process with other threads. However. each Of them has thetr rparate regiaer-set valws and
e of a pagernaker or any word processing application. It has two important threads executing in
and other a spelling and grammar checking thread running in background.The
kes from the keyboard in it.
keystro having two threads
a process
toreød ten times faster than creating a process i.e., it takes less time to create a new thread within an
figure threadis rather than creating it in a new process.
process
the process termination.
l' ination is faster than
the threads of a single process is faster no memory mapping has to beset up and the mem«y and
need not be invalidated.
Jddress more efficient than processes as they provide feature of shared memory thereby requiring any system
are communication.Therefore, threads are more appropriate for tightly coupled parallel activities
inter-thread
calls
for
data structures are used
similar creation and destruction are cheaper as no allocation and deallocation of new address spaces
and
essesofthread required.
resources are
otherprocess
5, J
concept of operating systems structure. A program under execution is referred toas a process.
is the fundamental entity that can be assigned to a processor for execution. A process is a dynamic objæt that
procesSdefinedas an active
registers. Each process
A process includes the current values of the program counter and processor's
inmainmemory.CPU. A process contains the following two elements,
itsownvirtual
and
program code
set of data.
(ii) A
Attributes
in an operating system is characterized by a set of attributes as follows,
Eachprocess
Identifier
is associated with a unique identifier which makes it distinguishable from all other processes.
Eachprocess
processState
describes whether a process is ready, running, blocked or suspended.
Thestateof a process
priority
priority relative to other processes within the system.
Eachprocesshas some
ProgramCounter
to be executed next is stored in the program counter.
Theaddressof the instruction
MemoryPointer
It refersto the pointers associated with the program code and data along with the memory blocks shared with other

ContextData
Thisdatais usually stored in the processor registers, while the process is executing.
1. Input/OutputStatus Information
Itcontainsall the information related to I/O processing, I/O requests, I/O devices etc.
Accountinglnformation
Itcontainsthe information about the processor time, clock time used, time limits, account numbers, etc
SPECTRUM
ULAN-ONEJOURML NR ENGINEERINGSTUDENTS SIA GROUP
3.8 PYTHON PROGRAMMING(JNTU-HYDERABADJ
3.2.3 Python, end the 010b•JInterpreter Lock
014. Write short on global interpreter lock. How do threads exit?

Global Interpreter Lock (GIL)


Python virtual mehine is responsible for controlling the executing of python code. Only one thread of
in the main loop among multiple threads. Access to this python virtual machine is controlled by Global Interpreter
It allows only one thread to execute at a time in CPU. Working of python virtual machine in MT environment is as
Initially set the GIL
2. Switch the thread to run
3. Execute either (i) or (ii)
(i) For fixed number of bytecode instructions.
(ii) If thread generates control voluntarily.
4. Retum the thread back to sleep.
5. Unlock GIL
6. Repeat the complete process.
The GIL gets locked and no longer works if any external code such as built-in-functions of C/C++ are called. But GIL
can be unlocked by certain extension programmers. For example, in I/O based routines, the GIL is released before and I/O call
is made so that other threads can continue while I/O is performed.
Exiting Threads
A thread can exit after it completes the execution of the function for which it is created. It can exit by calling tHRead.exn
or sys.exit () functions. It can even raise a system exit exception. The thread module is mostly not used because when the main
thread exits, all the remaining threads die without any cleanup. Whereas the threading module makes the complete processtobe
alive until all the threads exit.
Q15. How thread are accessed from python? Explain how life is without threads.
Answer Model
Accessing Threading from Python
The concept of multithreaded programming is supported by Python based on the operating system on which it is run.The
Unix based platforms such as Linux, Solaris, Macos X, BSD and win32 support it. Python makes use of pthreads or POSIX.
complaint threads. The threads are activated by default in python while installation.
Availability of threads can be checked for interpreter by the below statement.
>>> import thread
Here, the thread module is tried to be imported from the interactive interpreter.
If threads are available, errors will be generated. Otherwise module import fails.
>>> import thread
Traceback (innermost last):
File "<stdin>",line l, in ?
Importerror: No module named thread
In case of above errors, the python interpreter must be recompiled to access the threads. To do this, the configurescript
must be invoked with with thread" option.
Life without Threads
Consider and example oftime.sleep () to depict the working ofthreads. This function accepts floating point as argument
and then "sleeps" for specific number of seconds by halting the executing temporarily from time import sleep, ctime

Look for.the SIA GRWP LOGO on the TITLE COVER beforeyoubuy


Expressions and Multi-threadedProgramming
Regular 3.9
tS.py • C
Run

print C 1009 A
toopaot
Jet prsncf'BOin
'Leep(O '
•leop b done

loopA )

print C nil OOZE.

¯ösn ()

OUTPUT
Shen
•1.0 Python
Edit Shd Debug Options Wmdow
python 3.7.4 a 2019. (%.SCy. 1916 bit •
an vxn32
type "copynght•, ••credlt•••
tor more
RESTART: C: /

Begins at: rue Oct 22 2019


loop A at: Tue oce 22 2019
loop A done at: Tue occ 22 2019
Begin loop B at: Tue Oct 22 2019
wav b done rue occ 22 2019
DONE at: Tue Oct 22 2019

In the above example two loops are used and they are run sequentially. Here one loop must complete for the other loop
tostart.When one thread sleeps when the other is running or vice versa. Since both of them are two separate functions, they can
to cut down the overall yunning time.
berunparalelly
3.2.4 Thread Module,Threading Module,Related Modules
about tHRead module.
016. Explain
Model Paper-I, Q?
Answer:
tHReadModule
The tHReadmodule is responsible to spawn the threads. It provides a synchronization data structure called lock object.
of lock object are mutual exclusion lock, simple lock, primitive lock, mutex and binary semaphore. Some of the
Example
used thread functions and lock type lock object methods.
commonly
tHReadModule Functions
1. allocate_lock ()
This method is used to allocate lock type lock object.
2. start_new_thread (function, args, kwargs = none)
It is used to spawn the new thread and execute function with given args and optional kwargs.
3. exti
It makes the thread to exit.
LockObject Methods
l. Locked O
It returns true if lock is acquired other wise false is returned.
2. acquire (wait = none)
It tries to acquire lock object.
3. release O
It releases the lock.
SPECTRUM
NL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS SIA GROUP
3.10 PYTHON PROGRAMMINGIJNTU-HYDERAe
Example

Run
thread
tree
ioovAOt
the toe-p
'ieep (S)
prant'loov A •,

the B at: •, enne()


'ieep (S)
2 end'
def nasn():

thread. •cart nev thread (LoopA, O )


thread. scart nev thread O )
sleep (4)
•t: % etame()

OUTPUT
1.0

Fk Shd Debug Options Wmdow Help


txsc V.',SOO 64 bit
Python 2.7.17 (v2.7.17:c2f26dE6e6, Oct 19 2019,
on Win32
• for note intonation.
Ine •help", •copy:ight•, •credits" or "license

RESTART: C:/Python27/3a.py
Beginning at: Tue Oct 22 2019
2019
'tart the loop A the loop 3 at: Tue Oct 22
loop 3 end' at: Tue Oct 22 2019
coqieted at; Tue oct 22 2019

Q17. Write about tHReading module.


Answer: Model Paperqu,

tHReading Module
The tHReading module consists ofTHRead class and a set of synchronization mechanisms. Various objectsoftHReadiq
module are as follows,

Object Description
Thread It indicates a single thread of execution
Timer It is similar to thread but it waits for the specified time before running
Semaphore It offers a structure like "waiting area" for the threads that are waiting on lock
Lock It is a primitive lock object.
RLock It is re-entrant lock object that allows a single thread to acquire an already held lock
setDaemon (daemonic) It sets the daemont flag of thread according to the boolean daemonic
Threads can be created in three ways, they are as follows,
1. By passing thread instance in function.
By passing ThRead instance in callable class instance.
3. By deriving the THRead and creating a subclass inStance.

Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy
UNIT-3 Regular Expressions and Multi-threaded
Programming
By Passing TIl Read Instance in Function 3.11
In this method a TllRead instance is created
by passing it in the
function. ms function Wili be executed when thread
Example:
ti.py •
(3.74
Edit Options Window HOP
threading
ctne •ieep. cume

Loop €nioov. noec»


Loop •e nioop, •nt:•

print (• nioov.
ct.snet))
det
at: % ctl.me())
thread' • t)
n100P' range (loops) )

tot . snnioop•t
%hxe0ding.Thread
chread'. append ( loops (a) ) Y

nioops: t •cart threads


for a tr•,
chte•d' .•cart

tor a In nioop•: wast for ax i


thread' (al thread' to rsna•h
etxmet))
t name
nasn ( )

UTPUT
Python 3.7A Shen

Edi Debug Options Window Help


Python 3.1.4 (tags/v3.7.4:e093S9ii2e, Jui e 2019, (M.scv.19i6 64 bit •
(AHD")) on vsn32
Type •heip•, •copyright", •credits" or "license • for more intonation.

RESTART:
'tarced Thu OCC 2019
•cart ioopøcart loop 01
act Thu Occ 17 2019
Thu Oct 2019
loop i done at: Thu Oct 2019
loop O done at: Thu Oct 2019
co.ieced Thu occ 2019

By Passing THRead Instance to Callable Class


In this approach, a thread instance is passed to the callable class. It is flexible and object oriented type approach.

Bounded semaphore It is similar to semaphore but it does not exceed the initial value.
Condition It makes a thread to wait until another thread satisfies a condition

SPECTRamRU-IN-ONE JOURNRL FOR ENGINEERING STUDENTS SIA GROUP


PYTHON PROGRAMMING (JNTU+fYDERAn
3.12
Thread Class
Various functions of this class are as
thread class is a pnmary object in threading module.
Description
Method
Stan(i It beguns the thread
getName
0 It returns the thread name
run () It defines the thread functionality
setName (name) It sets the name for thread thread ts runmn ot not
whether the
isAlive O It retums a boolean flag that indicates
is issued.
(timeout = none) It suspends the thread until a timeout

Example:
(J.
t2.y

roe•

OUTPUT

Ea Opom •
Pythca 3.1.4 (tag./v3.'.4:e093S9212e. cui 2 txsc v.i9i6
on vxn32
type Phelp•. •copynght•. •eredit•• or tot more

RESTART:
•carted ac: Oct 2029
'tart 10090 at: tbo Oet 2019
Thu
ion done Thu 2019
loop O done at: Thu Oct i7 2019
at: Thu Oct 2019
UNIT-3 Regular Expressions and Multi-threadedProgramming 3.13
Byderiving the THRead and creating a subclass instance
3.
In this approach the THRead derived and a subclass
is instance is created.
Example:

•ear.

OUTPUT
Shen
1.0 Python174
Deb'"
python 3.1.4 e 2019,
txsc 64 bit
on vxnsa
Type •neip•, •copyrsghz•. •credit" or "iieen•eO • tor more
information.
RESTART:
•carted Thu occ 14:38:•S 2019
•oop at' Thu oct 17 :4:38:" 2019
O at: thu occ it 20i9
zoop done act Thu Oce 2019
loop O done •e: Thu Oct 2019
thu oct 20i9

018. Explain producer consumer problem and queue module.

ne producer is responsible for creating goods and storing in a data structure called queue. The time in between producing
the goodsas well as consuming these goods is said to be non deterministic. The queue module will provide an inter thread
communication mechanism that enables the threads to share data among them.
Example:
from random import randint
from time import sleep
from Queue import Queue
from threading import Thread
def writeQ(queue):
print('producing object for Q...',
queue.put('xxx',
l))
print("size now", queue.qsize())
defreadQ(queue):
SPECTRUM
RU-IN-ONE JOURML FOR ENGINEERINGSTUDENTS SIA GROUP
PROGRAMMING (JNTU-HYDERAQ
3.14 PYTHON
val J" queue.get( 1)
printCconsumed object from Q.. . size now.
queue.qsize())
def writer(queue. loops):
for i in range(loops):
writeQ(queue)

def reader(queue, loops):


for i in range(loops):
readQ(queue)
sleep(randint(2, 5))
funcs s [writer. readerl
nfuncs = range(len(funcs))
def main():
nloops = randint(2, 5)
q = Queue()
threads = [l
for i in nfüncs:
t = MyThread(funcs[il, (q, nloops),

threads.append(t)
for i in nfuncs:
threads[il.start()
for i in nfuncs:

print('all DONE')
if name main
main()
Q19. Write about related modules.
Answer :
The modulus that are used while programming multithreaded applications are as follows,

Module Description
tHRead It is a basic and low-level thread module
Queue It is a synchronized FIFO queue that is used for mutliple threads.
mutex It is a module for mutual exclusion objects.
threading It is a higher-level threading and synchronization objects.
Socket server It is a module for TCP and UDP managers with some threading control.
For example, the regular expression and the strings matching them are as follows,

RE pattern string mathched


Python Python
xyz789 xyz789
Me Me

Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy

You might also like