Python Unit 3
Python Unit 3
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
Special Symbols
The most commonly used special symbols in python are as follows,
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
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
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?
print C 1009 A
toopaot
Jet prsncf'BOin
'Leep(O '
•leop b done
loopA )
¯ö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: /
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 •,
OUTPUT
1.0
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
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
print (• nioov.
ct.snet))
det
at: % ctl.me())
thread' • t)
n100P' range (loops) )
tot . snnioop•t
%hxe0ding.Thread
chread'. append ( loops (a) ) Y
UTPUT
Python 3.7A Shen
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
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
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
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)
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,
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy