APP Unit 5
APP Unit 5
APP Unit 5
Programming Practice
Unit-5
Example:
input: switch
BATTER output: light bulb
Y
actions: flip switch
states: on, off
• Some Notations that are used in the transition diagram:
4
Simple Computer
Example:
input: switch
BATTERY output: light bulb
actions: flip switch
states: on, off
f number of flips
Another “computer”
Example:
1
2 2 2 2
off on
1
Types of Automata
DFA refers to deterministic finite automata. Deterministic refers to the uniqueness of the
computation. In the DFA, the machine goes to one state only for a particular input character. DFA
does not accept the null move.
NFA stands for non-deterministic finite automata. It is used to transmit any number of states for a
particular input. It can accept the null move
8
Alphabets and strings
A common way to talk about words, number, pairs of words, etc. is by representing them as
strings. To define strings, we start with an alphabet
Examples:
Languages can be used to describe problems with “yes/no” answers, for example:
L1 = The set of all strings over Σ1 that contain the substring “SRM”
L2 = The set of all strings over Σ2 that are divisible by 7 = {7, 14, 21, …}
L3 = The set of all strings of the form s#s where s is any string over {a, b, …, z}
L4 = The set of all strings over Σ4 where every ( can be matched with a subsequent )
Finite Automata
off on
There are states off and on, the automaton starts in off and tries to reach the “good state” on
What sequences of fs lead to the good state?
Answer: {f, fff, fffff, …} = {f n: n is odd}
This is an example of a deterministic finite automaton over alphabet {f}
Deterministic finite automata
0 1 0,1
q0 1 q1 0 q2
transition function δ:
inputs
0 1
alphabet Σ = {0, 1} q0 q0 q1
state Q = {q0, q1, q2}
states
q1 q2 q1
initial state q0
q2 q2 q2
accepting states F = {q0, q1}
Example:
• Present State Input 0 Input 1
• →q0 q1 q2
• q1 q0 q2
• *q2 q2 q2
15
Language of a DFA
The language of a DFA (Q, Σ, δ, q0, F) is the set of all strings over Σ that, starting from
q0 and following the transitions as the string is read left to right, will reach some
accepting state.
M: off on
DFA for the language accepting strings ending with ‘0’ over input alphabets ∑={0, 1} ?
DFA for the language accepting strings ending with ‘00’ over input alphabets ∑={0, 1} ?
Example of DFA
Draw a DFA for the language accepting strings containing even number of total zeros
over input alphabets ∑ = {0, 1} ?
Example of DFA using Python
from automata.fa.dfa import DFA if dfa.accepts_input('011'):
# DFA which matches all binary strings ending in an odd number of '1's print('accepted')
dfa = DFA( else:
states={'q0', 'q1', 'q2'}, print('rejected')
input_symbols={'0', '1'},
transitions={
'q0': {'0': 'q0', '1': 'q1'},
'q1': {'0': 'q0', '1': 'q2'},
'q2': {'0': 'q2', '1': 'q1'}
},
initial_state='q0',
final_states={'q1'}
)
dfa.read_input('01') # answer is 'q1‘
dfa.read_input('011') # answer is error
print(dfa.read_input_stepwise('011'))
Answer # yields:
# 'q0‘ # 'q0‘ # 'q1'
# 'q2‘ # 'q1'
Table Representation of a DFA
A DFA over A can be represented by a transition function T : States X A -> States, where T(i, a) is the state
reached from state i along the edge labelled a, and we mark the start and final states. For example, the
following figures show a DFA and its transition table.
b
a, b 1
Start 0 a
2 a, b
Sample Exercises - DFA
1. Write a automata code for the Language that accepts all and only those strings that contain
001
2. Write a automata code for L(M) ={ w | w has an even number of 1s}
3. Write a automata code for L(M) ={0,1}*
4. Write a automata code for L(M)=a + aa*b.
5. Write a automata code for L(M)={(ab)n | n ∈ N}
6. Write a automata code for Let Σ = {0, 1}.
Given DFAs for {}, {ε}, Σ*, and Σ+.
NDFA
0,1
0 1
q1 q2
q0 Exercise: Draw the complete
transition table for this NFA
note: δ(q0,0) = {q0,q1}
δ(q1,0) = {}
Example NDFA
NDFA
A nondeterministic finite automaton (NFA) over an alphabet A is similar to a DFA except that epislon-edges are
allowed, there is no requirement to emit edges from a state, and multiple edges with the same letter can be emitted
from a state.
1 a
ɛ
b
a
a
Start 0 2
NDFA
1 a
ɛ
b
a
a
Start 0 2
Examples
(b): Start
b
(c): Start a
A solution: a a
b b
Start
b a
a b
Examples
Algorithm: Transform a Regular Expression into a Finite Automaton
Start by placing the regular expression on the edge between a start and final state:
Regular
Start expression
Apply the following rules to obtain a finite automaton after erasing any ∅-edges.
R
R+S
i j transforms i j
S
to
R R S
i j transforms i j
S
to
R
R* ɛ
i j transforms i ɛ j
to
Quiz. Use the algorithm to construct a finite automaton for (ab)* + ba.
Answer: b a
ɛ ɛ
Start
b a
28
Example of NFA using Python
from automata.fa.nfa import NFA nfa.read_input('aba')
# NFA which matches strings beginning with 'a', ending with 'a', and ANSWER :{'q1', 'q2'}
containing
# no consecutive 'b's nfa.read_input('abba')
nfa = NFA( ANSWER: ERROR
states={'q0', 'q1', 'q2'},
input_symbols={'a', 'b'},
transitions={ nfa.read_input_stepwise('aba')
'q0': {'a': {'q1'}},
# Use '' as the key name for empty string (lambda/epsilon) if nfa.accepts_input('aba'):
transitions print('accepted')
'q1': {'a': {'q1'}, '': {'q2'}}, else:
'q2': {'b': {'q0'}} print('rejected')
}, ANSWER: ACCEPTED
initial_state='q0', nfa.validate()
final_states={'q1'} ANSWR: TRUE
)
Sample Exercises - NFA
1. Write a automata code for the Language that accepts all end with 01
2. Write a automata code for L(M)= a + aa*b + a*b.
3. Write a automata code for Let Σ = {0, 1}.
Given NFAs for {}, {ε}, {(ab)n | n ∈ N}, which has regular expression (ab)*.
Symbolic Programming Paradigms
• symbolic programs can effectively modify themselves and appear to learn, which
makes them better suited for applications such as artificial intelligence expert
systems natural language processing and computer games.
• Languages that support symbolic programming include the Language LISP and Prolog
Sympy-Symbolic Mathematics in Python
• SymPy is written entirely in Python and does not require any external libraries.
• To Install the sympy use command : pip install sympy
•Differentiation and integration can help us solve many types of real-world problems.
•Derivatives are met in many engineering and science problems, especially when
modeling the behaviour of moving objects.
3.Calculus
limit() in Python
With the help of sympy.limit() method, we can find the limit of any mathematical expression,
e.g.,
Parameters:
expression – The mathematical expression on which limit opeartion is to be performed, i. e., f(x).
variable – It is the variable in the mathematical expression, i. e., x
value – It is the value to which the limit tends to, i. e., a.
Returns: Returns the limit of the mathematical expression under given conditions.
limit() -method:
.
Ex:
# import sympy
from sympy import *
x = symbols('x')
expr = sin(x)/x;
# Use sympy.limit() method
limit_expr = limit(expr, x, 0)
print("Limit of the expression tends to 0 : {}".format(limit_expr))
Output:
Limit of the expression tends to 0 : 1
Differentiate in python
Differentiate any SymPy expression using diff() method.
. Syntax : diff(func,var)
Series in Python
. With the help of sympy.series() method, we can find the series of some
mathematical functions and trigonometric expressions by using sympy.series()
method.
Syntax : sympy.series()
.
from sympy import * x, # import sympy
y = symbols('x y')
# Use sympy.series() method
series_fun= cos(x).series()
print(series_fun)
O/p:
1 - x**2/2 + x**4/24 + O(x**6)
Integration in python
sympy.integrate() method
.
• we can find the integration of mathematical expressions in the form of variables
• syntax : sympy.integrate(expression, reference variable)
.
•SymPy is capable of performing powerful algebraic manipulations.
Most frequently used algebraic manipulations are expand and simplify.
expand() in python:
. Example:
import sympy as sym
x=sym.Symbol('x')
y=sym.Symbol('y')
exp =sym.expand((x+y)**2)
print(exp)
O/p:
x**2 + 2*x*y + y**2
simplify() in python
# import sympy
from sympy import *
x = symbols('x')
expr = sin(x)**2 + cos(x)**2
# Use sympy.simplify() method
smpl = simplify(expr)
print("After Simplification : {}".format(smpl))
Parameters:
• expression – It is the mathematical expression which needs to be simplified.
trigsimp() in python
.
Example :
# import sympy
from sympy import *
x = symbols('x')
expr = sin(x)**2 + cos(x)**2
# Use sympy.trigsimp() method
smpl = trigsimp(expr)
print("After Simplification : {}".format(smpl))
O/p:
After Simplification : 1
solve() in python-SymPy solving equations
.
Equations are solved with solve() or solveset().
•Example:
import sympy as sym
x = Symbol('x')
eq1 = Eq(x + 1, 3)
sol = solve(eq1, x)
print(sol)
O/P
[2]
. SymPy matrixes
N = Matrix([2, 2])
print("M * N")
print("---------------------------")
pprint(M*N)
O/p
--?
Example
Example:
Example
Example:
Event Programming
Paradigm
Event Driven Programming Paradigm
• Event-driven programming is a programming paradigm in which the flow of program
execution is determined by events - for example a user action such as a mouse click, key press,
or a message from the operating system or another program.
• An event-driven application is designed to detect events as they occur, and then deal with them
using an appropriate event-handling procedure.
• In a typical modern event-driven program, there is no discernible flow of control. The main
routine is an event-loop that waits for an event to occur, and then invokes the appropriate
event-handling routine.
• Event callback is a function that is invoked when something significant happens like when
click event is performed by user or the result of database query is available.
Event Driven Programming Paradigm
Event Handlers: Event handlers is a type of function or method that run a specific action when a
specific event is triggered. For example, it could be a button that when user click it, it will display
a message, and it will close the message when user click the button again, this is an event
handler.
Trigger Functions: Trigger functions in event-driven programming are a functions that decide
what code to run when there are a specific event occurs, which are used to select which event
handler to use for the event when there is specific event occurred.
Events: Events include mouse, keyboard and user interface, which events need to be triggered in
the program in order to happen, that mean user have to interacts with an object in the program,
Introduction
• A graphical user interface allows the user to interact with the operating system and other
programs using graphical elements such as icons, buttons, and dialog boxes.
• GUIs popularized the use of the mouse.
• GUIs allow the user to point at graphical elements and click the mouse button to activate
them.
• GUI Programs Are Event-Driven
• User determines the order in which things happen
• GUI programs respond to the actions of the user, thus they are event driven.
• The tkinter module is a wrapper around tk, which is a wrapper around tcl, which is what is
used to create windows and graphical user interfaces.
Introduction
• A major task that a GUI designer needs to do is to determine what will happen when a GUI is
invoked
• Every GUI component may generate different kinds of “events” when a user makes access to
it using his mouse or keyboard
• E.g. if a user moves his mouse on top of a button, an event of that button will be generated to
the Windows system
• E.g. if the user further clicks, then another event of that button will be generated (actually it is
the click event)
• For any event generated, the system will first check if there is an event handler, which defines
the action for that event
Introduction
• For a GUI designer, he needs to develop the event handler to determine the action that he
wants Windows to take for that event.
Is there
Any Ye an event Ye
handler s
event? s for that
event?
N N
o o Run
event
handler
GUI Using Python
• Tkinter:
Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
• wxPython:
This is an open-source Python interface for wx Windows
• PyQt
This is also a Python interface for a popular cross-platform Qt GUI library.
• JPython:
JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local
machine
Tkinter Programming
• Tkinter is the standard GUI library for Python.
• Creating a GUI application using Tkinter
Steps
• Import the Tkinter module.
Import tKinter as tk
• Create the GUI application main window.
root = tk.Tk()
• Add one or more of the above-mentioned widgets to the GUI application.
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
• Enter the main event loop to take action against each event triggered by the user.
root.mainloop()
Tkinter widgets
• Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly
called widgets.
Widget Description
Label Used to contain text or images
Button Similar to a Label but provides additional functionality for mouse overs, presses, and releases as well as keyboard activity/events
Canvas Provides ability to draw shapes (lines, ovals, polygons, rectangles); can contain images or bitmaps
Radiobutton Set of buttons of which only one can be "pressed" (similar to HTML radio input)
Checkbutton Set of boxes of which any number can be "checked" (similar to HTML checkbox input)
Entry Single-line text field with which to collect keyboard input (similar to HTML text input)
Frame Pure container for other widgets
Listbox Presents user list of choices to pick from
Menu Actual list of choices "hanging" from a Menubutton that the user can choose from
Menubutton Provides infrastructure to contain menus (pulldown, cascading, etc.)
Message Similar to a Label, but displays multi-line text
Scale Linear "slider" widget providing an exact value at current setting; with defined starting and ending values
Text Multi-line text field with which to collect (or display) text from user (similar to HTML TextArea)
Scrollbar Provides scrolling functionality to supporting widgets, i.e., Text, Canvas, Listbox, and Entry
Toplevel Similar to a Frame, but provides a separate window container
Operation Using Tkinter Widget
Geometry Managers
• The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent
widget.
widget.pack( pack_options )
options
• expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.
• fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal
dimensions: NONE (default), X (fill only horizontally), Y (fill only vertically), or BOTH (fill both
horizontally and vertically).
• side − Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or
RIGHT.
Geometry Managers
• The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget.
widget.grid( grid_options )
options −
• Column/row − The column or row to put widget in; default 0 (leftmost column).
• ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders.
• padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders.
Geometry Managers
• The place() Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget.
widget.place( place_options )
options −
• anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass
directions indicating the corners and sides of widget; default is NW (the upper left corner of widget)
• bordermode − INSIDE (the default) to indicate that other options refer to the parent's inside (ignoring the
parent's border); OUTSIDE otherwise ,height, width − Height and width in pixels.
• relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of
the parent widget.
• relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width
of the parent widget.
• x, y − Horizontal and vertical offset in pixels.
Common Widget Properties
Common attributes such as sizes, colors and fonts are specified.
• Dimensions
• Colors
• Fonts
• Anchors
• Relief styles
• Bitmaps
• Cursors
Label Widgets
• A label is a widget that displays text or images, typically that the user will just view but not otherwise interact
with. Labels are used for such things as identifying controls or other parts of the user interface, providing textual
feedback or results, etc.
• Syntax
tk.Label(parent,text=“message”)
Example:
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Hello World!')
label.grid()
root.mainloop()
Button Widgets
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
Button Widgets
• A button, unlike a frame or label, is very much designed for the user to interact with, and in particular, press to
perform some action. Like labels, they can display text or images, but also have a whole range of new options
used to control their behaviour.
Syntax
button = ttk.Button(parent, text=‘ClickMe', command=submitForm)
Button Widgets
Example:
import tkinter as tk
from tkinter import messagebox
def hello():
msg = messagebox.showinfo( "GUI Event Demo","Button Demo")
root = tk.Tk()
root.geometry("200x200")
b = tk.Button(root, text='Fire Me',command=hello)
b.place(x=50,y=50)
root.mainloop()
Button Widgets
• Button: To add a button in your application, this widget is used.
Syntax :
w=Button(master, text=“caption” option=value)
• Syntax
w = radioButton(master, option=value)
radiobutton
Example: def choice():
root= Tk() if(radio.get()==1):
root.geometry("200x200") root.configure(background='red')
radio=IntVar() elif(radio.get()==2):
rb1=Radiobutton(root,text='Red', variable=radio,width=25,value=1, command=choice) root.configure(background='blue')
rb1.grid(row=0) elif(radio.get()==3):
rb2=Radiobutton(root,text='Blue', variable=radio,width=25,value=2, command=choice) root.configure(background='green')
rb2.grid(row=1)
rb3=Radiobutton(root,text='Green', variable=radio,width=25,value=3, command=choice)
rb3.grid(row=3)
root.mainloop()
Scale
• Scale widget is used to implement the graphical slider to the python application so that the user can slide through
the range of values shown on the slider and select the one among them. We can control the minimum and
maximum values along with the resolution of the scale. It provides an alternative to the Entry widget when the
user is forced to select only one value from the given range of values.
• Syntax
w = Scale(top, options)
Scale
Example:
from tkinter import messagebox
root= Tk()
root.title('Scale Demo')
root.geometry("200x200")
def slide():
msg = messagebox.showinfo( "GUI Event Demo",v.get())
v = DoubleVar()
scale = Scale( root, variable = v, from_ = 1, to = 50, orient = HORIZONTAL)
scale.pack(anchor=CENTER)
btn = Button(root, text="Value", command=slide)
btn.pack(anchor=CENTER)
root.mainloop()
Spinbox
• The Spinbox widget is an alternative to the Entry widget. It provides the range of values to the
user, out of which, the user can select the one.
Syntax
w = Spinbox(top, options)
Spinbox
Example:
from tkinter import *
from tkinter import messagebox
root= Tk()
root.title('Scale Demo')
root.geometry("200x200")
def slide():
msg = messagebox.showinfo( "SpinBox Event Demo",spin.get())
Syntax
w = Menubutton(Top, options)
Menubutton
Example: