App SRM Unit 5 Notes
App SRM Unit 5 Notes
Getting started with SymPy module: Sympy is a Python library for symbolic
mathematics. It aims to become a full-featured computer algebra system (CAS)
while keeping the code as simple as possible in order to be comprehensible and
easily extensible. SymPy is written entirely in Python.
SymPy only depends on mpmath, a pure Python library for arbitrary floating
point arithmetic, making it easy to use.
sympy.diff() method: With the help of sympy.diff() method, we can find the
differentiation of mathematical expressions in the form of variables by using
sympy.diff() method.
Syntax : sympy.diff(expression, reference variable)
Return : Return differentiation of mathematical expression.
Example:In this example we can see that by using sympy.diff() method, we can
find the differentiation of mathematical expression with variables. Here we use
symbols() method also to declare a variable as symbol.
# import sympy
from sympy import * x, y = symbols('x y')
gfg_exp = x + y
exp = sympy.expand(gfg_exp**2)
print("Before Differentiation : {}".format(exp))
# Use sympy.diff() method
dif = diff(exp, x)
print("After Differentiation : {}".format(dif))
Output :
Before Differentiation : x**2 + 2*x*y + y**2
After Differentiation : 2*x + 2*y
Example #2 :
# import sympy
from sympy import * x, y = symbols('x y')
gfg_exp = sin(x)*tan(x)
print("Before Integration : {}".format(gfg_exp))
# Use sympy.integrate() method
intr = integrate(gfg_exp, x)
print("After Integration : {}".format(intr))
Output :
Before Integration : sin(x)*tan(x)
After Integration : -log(sin(x) – 1)/2 + log(sin(x) + 1)/2 – sin(x)
Example #1:
# import sympy
from sympy import *
x = symbols('x')
expr = sin(x)/x;
print("Expression : {}".format(expr))
# Use sympy.limit() method
limit_expr = limit(expr, x, 0)
print("Limit of the expression tends to 0 : {}".format(limit_expr))
Output:
Expression : sin(x)/x
Limit of the expression tends to 0 : 1
Example #1 :
In this example we can see that by using sympy.series() method, we are able to
find the series of some trigonometric functions.
# import sympy
from sympy import *
x, y = symbols('x y')
# Use sympy.series() method
gfg = cos(x).series()
print(gfg)
Output :
1 – x**2/2 + x**4/24 + O(x**6)
Example #1 :
In this example, we can see that by using sympy.ones() method, we are able to
create the ones matrix having dimension nxn all filled with ones, where nxm
will be pass as a parameter.
# import sympy
from sympy import *
# Use sympy.ones() method
mat = ones(3, 4)
print(mat)
Output :
Matrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
Example #1 :
In this example, we can see that by using sympy.det() method, we are able to
find the determinant of a matrix.
# import sympy
from sympy import *
# Use sympy.det() method
mat = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])
d = mat.det()
print(d)
Output :
-1
Example #1 :
In this example, we are able to insert a column in a matrix by using
Matrix().col_insert() method.
# Import all the methods from sympy
from sympy import *
# Make a matrix
gfg_mat = Matrix([[1, 2], [2, 1]])
# use the col_insert() method for matrix
new_mat = gfg_mat.col_insert(1, Matrix([[3], [4]]))
print(new_mat)
Output :
Matrix([[1, 3, 2], [2, 4, 1]])
Example #1 :
In this example, we are able to insert a row in a matrix by using
Matrix().row_insert() method.
# Import all the methods from sympy
from sympy import *
# Make a matrix
gfg_mat = Matrix([[1, 2], [2, 1]])
# use the row_insert() method for matrix
new_mat = gfg_mat.row_insert(1, Matrix([[3, 4]]))
print(new_mat)
Output :
Matrix([[1, 2], [3, 4], [2, 1]])
Example #1:
In this example we can see that by using sympy.lambdify() method, we can
simplify any mathematical expression.
# import sympy
from sympy import *
x = symbols('x')
expr = sin(x)**2 + cos(x)**2
print("Before Simplification : {}".format(expr))
# Use sympy.simplify() method
smpl = simplify(expr)
print("After Simplification : {}".format(smpl))
Output:
Before Simplification : sin(x)**2 + cos(x)**2
After Simplification : 1
Example #1 :
In the given example we can see that the sympy.Matrix.col() method is used to
extract the columns of a matrix.
# Import all the methods from sympy
from sympy import *
# use the col() method for matrix
gfg_val = Matrix([[1, 2], [2, 1]]).col(1)
print(gfg_val)
Output :\
Matrix([[2], [1]])
Example #1 :
In the given example we can see that the sympy.Matrix.col_del() method is used
to delete the column of a matrix and return a new matrix.
# Import all the methods from sympy
from sympy import *
# use the col_del() method for matrix
gfg_val = Matrix([[1, 2], [2, 1]]).col_del(1)
print(gfg_val)
Output :
Matrix([[1], [2]])
Example #1 :
In the given example we can see that the sympy.Matrix.row_del() method is
used to delete the row of a matrix and return a new matrix.
# Import all the methods from sympy
from sympy import *
# use the row_del() method for matrix
gfg_val = Matrix([[1, 2], [2, 1]]).col_row(1)
print(gfg_val)
Output :
Matrix([1, 2])
Example #1 :
In this example, we can see that by using sympy.Matrix() method, we can create
a matrix or can extract the rows and columns.
# Import all the methods from sympy
from sympy import *
# use the Matirx() method to create a matrix
gfg_val = Matrix([[1, sqrt(2)], [sqrt(2), 1]])
print(gfg_val)
Output :
Matrix([[1, sqrt(2)], [sqrt(2), 1]])
Example #1 :
In the given example we can see that the sympy.Matrix().row() method is used
to extract the rows of a matrix.
# Import all the methods from sympy
from sympy import *
# use the row() method for matrix
gfg_val = Matrix([[1, 2], [2, 1]]).row(1)
print(gfg_val)
Output :
[2, 1]
sympy.expand() method:With the help of sympy.expand() method, we can
expand the mathematical expressions in the form of variables by using
sympy.expand() method.
Syntax : sympy.expand(expression)
Return : Return mathematical expression.
Example #1 :
In this example we can see that by using sympy.expand() method, we can get
the mathematical expression with variables. Here we use symbols() method also
to declare a variable as symbol.
# import sympy
from sympy import expand, symbols
x, y = symbols('x y')
gfg_exp = x + y
# Use sympy.expand() method
exp = sympy.expand(gfg_exp**2)
print(exp)
Output :
x**2 + 2*x*y + y**2
Example #1 :
In this example we can see that by using sympy.integrate(expression, limits)
method, we can find the integration of mathematical expression using limits
with variables. Here we use symbols() method also to declare a variable as
symbol.
# import sympy
from sympy import *
x, y = symbols('x y')
gfg_exp = cos(x)
print("Before Integration : {}".format(gfg_exp))
# Use sympy.integrate() method
intr = integrate(gfg_exp, (x, -oo, oo))
print("After Integration : {}".format(intr))
Output :
Before Integration : cos(x)
After Integration : AccumBounds(-2, 2)
Related Terminologies:
Alphabet
• Definition − An alphabet is any finite set of symbols. 1/0
• Example − ∑ = {a, b, c, d} is an alphabet set where ‘a’, ‘b’, ‘c’, and ‘d’
are symbols. (1,0)
String
• Definition − A string is a finite sequence of symbols taken from ∑.
1111000101010
• Example − ‘cabcad’ is a valid string on the alphabet set ∑ = {a, b, c, d}
Length of a String
• Definition − It is the number of symbols present in a string. (Denoted by
|S|).
• Examples −
o If S = ‘cabcad’, |S|= 6
o If |S|= 0, it is called an empty string (Denoted by λ or ε)
Kleene Star
• Definition − The Kleene star, ∑*, is a unary operator on a set of symbols
or strings, ∑, that gives the infinite set of all possible strings of all possible
lengths over ∑ including λ.
• Representation − ∑* = ∑0 ∪ ∑1 ∪ ∑2 ∪……. where ∑p is the set of all
possible strings of length p.
• Example − If ∑ = {a, b}, ∑* = {λ, a, b, aa, ab, ba, bb,………..}
Kleene Closure / Plus
• Definition − The set ∑+ is the infinite set of all possible strings of all
possible lengths over ∑ excluding λ.
• Representation − ∑+ = ∑1 ∪ ∑2 ∪ ∑3 ∪…….
∑+ = ∑* − { λ }
• Example − If ∑ = { a, b } , ∑+ = { a, b, aa, ab, ba, bb,………..}
Language
• Definition − A language is a subset of ∑* for some alphabet ∑. It can be
finite or infinite.
• Example − If the language takes all possible strings of length 2 over ∑ =
{a, b}, then L = { ab, aa, ba, bb }
Finite automata: Finite automata, also known as state machines or FSM (finite-
state machines), are a mathematical model of computing used in the design of
computer programs and sequential logic circuits. In general, a finite automaton
(singular) is a machine that transitions from one state to another. It reacts with a
predefined sequence of behaviors when it encounters a certain event.
For example, a subway station turnstile is an example of a finite state machine.
When a passenger deposits the required fare into the machine, the machine
changes from one predefined state (locked) to another (unlocked), permitting
the passenger to enter.
a a b
b c a
c b c
a a, b b
b c a, c
c b, c c
DFA.read_input(self, input_str)
Returns the final state the DFA stopped on, if the input is accepted.
dfa.read_input('01') # returns 'q1'
dfa.read_input('011') # raises RejectionException
DFA.read_input_stepwise(self, input_str)
Yields each state reached as the DFA reads characters from the input string, if
the input is accepted.
dfa.read_input_stepwise('0111')
# yields:
# 'q0'
# 'q0'
# 'q1'
# 'q2'
# 'q1'
DFA.accepts_input(self, input_str)
if dfa.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')
DFA.validate(self)
dfa.validate() # returns True
DFA.copy(self)
dfa.copy() # returns deep copy of dfa
DFA.minify(self)
Creates a minimal DFA which accepts the same inputs as the old one.
Unreachable states are removed and equivalent states are merged.
minimal_dfa = dfa.minify()
DFA.from_nfa(cls, nfa)
Creates a DFA that is equivalent to the given NFA.
from automata.fa.dfa import DFA
from automata.fa.nfa import NFA
dfa = DFA.from_nfa(nfa) # returns an equivalent DFA
class NFA(FA)
The NFA class is a subclass of FA and represents a nondeterministic finite
automaton. It can be found under automata/fa/nfa.py.
Every NFA has the same five DFA properties: state, input_symbols, transitions,
initial_state, and final_states. However, the structure of the transitions object
has been modified slightly to accommodate the fact that a single state can have
more than one transition for the same symbol. Therefore, instead of mapping a
symbol to one end state in each sub-dict, each symbol is mapped to a set of end
states.
from automata.fa.nfa import NFA
# NFA which matches strings beginning with 'a', ending with 'a', and containing
# no consecutive 'b's
nfa = NFA(
states={'q0', 'q1', 'q2'},
input_symbols={'a', 'b'},
transitions={
'q0': {'a': {'q1'}},
# Use '' as the key name for empty string (lambda/epsilon) transitions
'q1': {'a': {'q1'}, '': {'q2'}},
'q2': {'b': {'q0'}}
},
initial_state='q0',
final_states={'q1'}
)
NFA.read_input(self, input_str)
Returns a set of final states the FA stopped on, if the input is accepted.
nfa.read_input('aba') # returns {'q1', 'q2'}
nfa.read_input('abba') # raises RejectionException
NFA.read_input_stepwise(self, input_str)
Yields each set of states reached as the NFA reads characters from the input
string, if the input is accepted.
nfa.read_input_stepwise('aba')
# yields:
# {'q0'}
# {'q1', 'q2'}
# {'q0'}
# {'q1', 'q2'}
NFA.accepts_input(self, input_str)
if nfa.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')
NFA.validate(self)
nfa.validate() # returns True
NFA.copy(self)
nfa.copy() # returns deep copy of nfa
NFA.from_dfa(cls, dfa)
Creates an NFA that is equivalent to the given DFA.
from automata.fa.nfa import NFA
from automata.fa.dfa import DFA
nfa = NFA.from_dfa(dfa) # returns an equivalent NFA
class NPDA(PDA)
The NPDA class is a subclass of PDA and represents a nondeterministic
pushdown automaton. It can be found under automata/pda/npda.py.
Every NPDA has the following (required) properties:
1. states: a set of the NPDA’s valid states, each of which must be
represented as a string
2. input_symbols: a set of the NPDA’s valid input symbols, each of which
must also be represented as a string
3. stack_symbols: a set of the NPDA’s valid stack symbols
4. transitions: a dict consisting of the transitions for each state; see the
example below for the exact syntax
5. initial_state: the name of the initial state for this NPDA
6. initial_stack_symbol: the name of the initial symbol on the stack for this
NPDA
7. final_states: a set of final states for this NPDA
8. acceptance_mode: a string defining whether this NPDA accepts by
'final_state', 'empty_stack', or 'both'; the default is 'both'
from automata.pda.npda import NPDA
# NPDA which matches palindromes consisting of 'a's and 'b's
# (accepting by final state)
# q0 reads the first half of the word, q1 the other half, q2 accepts.
# But we have to guess when to switch.
npda = NPDA(
states={'q0', 'q1', 'q2'},
input_symbols={'a', 'b'},
stack_symbols={'A', 'B', '#'},
transitions={
'q0': {
'': {
'#': {('q2', '#')},
},
'a': {
'#': {('q0', ('A', '#'))},
'A': {
('q0', ('A', 'A')),
('q1', ''),
},
'B': {('q0', ('A', 'B'))},
},
'b': {
'#': {('q0', ('B', '#'))},
'A': {('q0', ('B', 'A'))},
'B': {
('q0', ('B', 'B')),
('q1', ''),
},
},
},
'q1': {
'': {'#': {('q2', '#')}},
'a': {'A': {('q1', '')}},
'b': {'B': {('q1', '')}},
},
},
initial_state='q0',
initial_stack_symbol='#',
final_states={'q2'},
acceptance_mode='final_state'
)
NPDA.read_input(self, input_str)
Returns a set of PDAConfigurations representing all of the NPDA’s
configurations. Each of these is basically a tuple containing the final state the
NPDA stopped on, the remaining input (an empty string) as well as a PDAStack
object representing the NPDA’s stack (if the input is accepted).
npda.read_input("aaaa") # returns {PDAConfiguration('q2', '', PDAStack('#',))}
npda.read_input('ab') # raises RejectionException
NPDA.read_input_stepwise(self, input_str)
Yields sets of PDAConfiguration object. Each of these is basically a tuple
containing the current state, the remaining input and the current stack as a
PDAStack object, if the input is accepted.
npda.read_input_stepwise('aa')
# yields:
# {PDAConfiguration('q0', 'aa', PDAStack('#',))}
# {PDAConfiguration('q0', 'a', PDAStack('#', 'A')), PDAConfiguration('q2', 'aa',
PDAStack('#',))}
# {PDAConfiguration('q0', '', PDAStack('#', 'A', 'A')), PDAConfiguration('q1', '',
PDAStack('#',))}
# {PDAConfiguration('q2', '', PDAStack('#',))}
NPDA.accepts_input(self, input_str)
if npda.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')
NPDA.validate(self)
npda.validate() # returns True
NPDA.copy(self)
npda.copy() # returns deep copy of npda
# import wx module
import wx
# creaing application object
app1 = wx.App()
# creating a frame
frame = wx.Frame(None, title ="GFG")
pa = wx.Panel(frame)
# Adding a text to the frame object
text1 = wx.StaticText(pa, label ="GEEKS FOR GEEKS", pos =(100, 50))
# show it
frame.Show()
# start the event loop
app1.Mainloop()
# importing wx module
import wx
# creaing application object
app1 = wx.App()
# creating a frame
frame = wx.Frame(None, title ="wxpython app")
pa = wx.Panel(frame)
# Checkbox creation using wx module
e = wx.CheckBox(pa, -1, "CheckBox1", pos = (120, 100))
e = wx.CheckBox(pa, -1, "CheckBox2", pos = (120, 120))
# show it
frame.Show()
# start the event loop
app1.Mainloop()
# importing wx module
import wx
Installation:
First, we need to install PyQt5 library. For this, type the following command in
the terminal or command prompt:
pip install pyqt5
If successfully installed one can verify it by running the code:
>>>import PyQt5
PyQt5 provides lots of tools and QtDesigner is one of them. For this run this
command:
pip install PyQt5-tools
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(150, 70, 93, 28))
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(130, 149, 151, 31))
self.label.setText("")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def showmsg(self):
# slot
self.label.setText("You clicked me")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Dialog()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Let’s create a signup form using the QT designer tool. No code is required for
creating forms, buttons, text boxes, etc! It is rather drag and drop environment.
So, using PyQt is a lot simpler than Tkinter.
QT Designer will be located at MyPythonInstallationDir\Lib\site-
packages\pyqt5-tools, and is named designer.exe (on Windows OS).
Open Qt Designer, then select Main Window and click Create. Set your
preferred size of the window by dragging the edges of the window.
To create the layout of Singup form, following widgets are needed :
Three text edit boxes.
One button.
Four Text Labels (SignId Banner, UserName label, Password and
Confirm Password label).
One has to find those widgets in Widget Tool Box. Just drag and drop the
required widgets onto the Main Window or the window working on.
To change the appearance of the window or the widget, just right click on the
widget and click Change StyleSheet.
To get preview of the window, press Ctrl + R .
Save the file :
The file will be saved with .ui extension. To convert this file (.ui extension) to
Python file (.py extension), follow these steps :
Open terminal and navigate to the folder where the layout.ui file is
present.
To convert into Python file, type pyuic5 -x layout.ui -o layout.py on
terminal.
Run layout.py using python!
Installation of Jython
Windows
Download your copy from www.jython.org
Linux