0% found this document useful (0 votes)
261 views35 pages

App SRM Unit 5 Notes

Unit-5 notes discusses symbolic programming and the SymPy module in Python. Symbolic programming allows programs to manipulate their own components as data. SymPy is a Python library for symbolic mathematics that can perform algebraic operations symbolically like simplifying expressions, computing derivatives and integrals, and solving equations. It defines numerical types like Rational and Integer and uses mpmath for arbitrary-precision arithmetic. Key methods in SymPy include diff() for differentiation, integrate() for integration, solve() for solving equations, and factor() for factoring expressions.

Uploaded by

Harshit Batra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
261 views35 pages

App SRM Unit 5 Notes

Unit-5 notes discusses symbolic programming and the SymPy module in Python. Symbolic programming allows programs to manipulate their own components as data. SymPy is a Python library for symbolic mathematics that can perform algebraic operations symbolically like simplifying expressions, computing derivatives and integrals, and solving equations. It defines numerical types like Rational and Integer and uses mpmath for arbitrary-precision arithmetic. Key methods in SymPy include diff() for differentiation, integrate() for integration, solve() for solving equations, and factor() for factoring expressions.

Uploaded by

Harshit Batra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Unit-5 notes

Symbolic programming: In computer programming, symbolic programming is


a programming paradigm in which the program can manipulate its own
formulas and program components as if they were plain data.
Through symbolic programming, complex processes can be developed that
build other more intricate processes by combining smaller units of logic or
functionality. Thus, such 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 languages such
as Wolfram Language, LISP and Prolog.
Symbolic programming paradigm is a symbolic computer algebra system. They
use symbolic in the mathematical sense. Some authors consider it as a part of
functional programming but it is very much different from that.
For example, if you do 1.0/3*3 in, say, C, it divides 1.0 by 3 and then multiplies
the result by 3 = (1.0/3)*3. You get 0.9999999999998.
Mathematica (and other symbolic mathematics software, for example
Macsyma/Maxima) treats numbers as symbols... Like, 1/3*3 is not a lot
different from a/b*b until you need the actual result in numeric form. Since
a/b*b is a, 1/3*3 is 1. No computation with actual numeric values needed.

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 as a calculator:SymPy defines following numerical types: Rational and


Integer. The Rational class represents a rational number as a pair of two
Integers, numerator and denominator, so Rational(1, 2) represents 1/2,
Rational(5, 2) 5/2 and so on. The Integer class represents Integer number.
# import everything from sympy module
from sympy import *
a = Rational(5, 8)
print("value of a is :" + str(a))
b = Integer(3.579)
print("value of b is :" + str(b))
SymPy uses mpmath in the background, which makes it possible to perform
computations using arbitrary-precision arithmetic. That way, some special
constants, like exp, pi, oo (Infinity), are treated as symbols and can be evaluated
with arbitrary precision.
# import everything from sympy module
from sympy import *
# you can't get any numerical value
p = pi**3
print("value of p is :" + str(p))
# evalf method evaluates the expression to a floating-point number
q = pi.evalf()
print("value of q is :" + str(q))
# equivalent to e ^ 1 or e ** 1
r = exp(1).evalf()
print("value of r is :" + str(r))
s = (pi + exp(1)).evalf()
print("value of s is :" + str(s))
rslt = oo + 10000
print("value of rslt is :" + str(rslt))
if oo > 9999999 :
print("True")
else:
print("False")
output:value of p is :pi^3
value of q is :3.14159265358979
value of r is :2.71828182845905
value of s is :5.85987448204884
value of rslt is :oo
True
The real power of a symbolic computation system such as SymPy is the ability
to do all sorts of computations symbolically. SymPy can simplify expressions,
compute derivatives, integrals, and limits, solve equations, work with matrices,
and much, much more, and do it all symbolically. Here is a small sampling of
the sort of symbolic power SymPy is capable of, to whet your appetite.
Example : Find derivative, integration, limits, quadratic equation.
# import everything from sympy module
from sympy import *
# make a symbol
x = Symbol('x')
# ake the derivative of sin(x)*e ^ x
ans1 = diff(sin(x)*exp(x), x)
print("derivative of sin(x)*e ^ x : ", ans1)
# Compute (e ^ x * sin(x)+ e ^ x * cos(x))dx
ans2 = integrate(exp(x)*sin(x) + exp(x)*cos(x), x)
print("indefinite integration is : ", ans2)
# Compute definite integral of sin(x ^ 2)dx
# in b / w interval of ? and ?? .
ans3 = integrate(sin(x**2), (x, -oo, oo))
print("definite integration is : ", ans3)
# Find the limit of sin(x) / x given x tends to 0
ans4 = limit(sin(x)/x, x, 0)
print("limit is : ", ans4)
# Solve quadratic equation like, example : x ^ 2?2 = 0
ans5 = solve(x**2 - 2, x)
print("roots are : ", ans5)
output: derivative of sin(x)*e^x : exp(x)*sin(x) + exp(x)*cos(x)
indefinite integration is : exp(x)*sin(x)
definite integration is : sqrt(2)*sqrt(pi)/2
limit is : 1
roots are : [-sqrt(2), sqrt(2)]

sympy.Derivative() method: With the help of sympy.Derivative() method, we


can create an unevaluated derivative of a SymPy expression. It has the same
syntax as diff() method. To evaluate an unevaluated derivative, use the doit()
method.
Syntax: Derivative(expression, reference variable)
Parameters:
expression – A SymPy expression whose unevaluated derivative is found.
reference variable – Variable with respect to which derivative is found.
# import sympy
from sympy import *
x, y = symbols('x y')
expr = x**2 + 2 * y + y**3
print("Expression : {} ".format(expr))
# Use sympy.Derivative() method
expr_diff = Derivative(expr, x)
print("Derivative of expression with respect to x : {}".format(expr_diff))
print("Value of the derivative : {} ".format(expr_diff.doit()))
output: Expression : x**2 + y**3 + 2*y
Derivative of expression with respect to x : Derivative(x**2 + y**3 + 2*y, x)
Value of the derivative : 2*x
Example2:
# import sympy
from sympy import *
x, y = symbols('x y')
expr = y**2 * x**2 + 2 * y*x + x**3 * y**3
print("Expression : {} ".format(expr))
# Use sympy.Derivative() method
expr_diff = Derivative(expr, x, y)
print("Derivative of expression with respect to x : {}".format(expr_diff))
print("Value of the derivative : {} ".format(expr_diff.doit()))
output: Expression : x**3*y**3 + x**2*y**2 + 2*x*y
Derivative of expression with respect to x : Derivative(x**3*y**3 + x**2*y**2
+ 2*x*y, x, y)
Value of the derivative : 9*x**2*y**2 + 4*x*y + 2

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

sympy.factor() method: With the help of sympy.factor() method, we can find


the factors of mathematical expressions in the form of variables by using
sympy.factor() method.
Syntax : sympy.factor(expression)
Return : Return factor of mathematical expression.
Example #1 :
In this example we can see that by using sympy.factor() method, we can find the
factors of mathematical expression with variables. Here we use symbols()
method also to declare a variable as symbol.
# import sympy
from sympy import expand, symbols, factor
x, y = symbols('x y')
gfg_exp = x + y
exp = sympy.expand(gfg_exp**2)
# Use sympy.factor() method
fact = factor(exp)
print(fact)
Output :
(x + y)**2
Example #2 :
# import sympy
from sympy import expand, symbols, factor
x, y, z = symbols('x y z')
gfg_exp = x + y + z
exp = sympy.expand(gfg_exp**2)
# Use sympy.factor() method
fact = factor(exp)
print(fact)
Output :
(x + y + z)**2

sympy.solve() method: With the help of sympy.solve(expression) method, we


can solve the mathematical equations easily and it will return the roots of the
equation that is provided as parameter using sympy.solve() method.
Syntax : sympy.solve(expression)
Return : Return the roots of the equation.
Example #1 :
In this example we can see that by using sympy.solve() method, we can solve
the mathematical expressions and this will return the roots of that equation.
# import sympy
from sympy import *
x, y = symbols('x y')
gfg_exp = x**2 - 4
print("Before Integration : {}".format(gfg_exp))
# Use sympy.integrate() method
intr = solve(gfg_exp, x)
print("After Integration : {}".format(intr))
Output :
Before Integration : x**2 – 4
After Integration : [-2, 2]
Example #2 :
# import sympy
from sympy import *
x, y = symbols('x y')
gfg_exp = x**2 + 36
print("Before Integration : {}".format(gfg_exp))
# Use sympy.integrate() method
intr = solve(gfg_exp, x)
print("After Integration : {}".format(intr))
Output :
Before Integration : x**2 + 36
After Integration : [-6*I, 6*I]

sympy.integrate() method:With the help of sympy.integrate() method, we can


find the integration of mathematical expressions in the form of variables by
using sympy.integrate() method.
Syntax : sympy.integrate(expression, reference variable)
Return : Return integration of mathematical expression.
Example #1 :
In this example we can see that by using sympy.integrate() method, we can find
the integration 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 = sin(x)*exp(x)
print("Before Integration : {}".format(gfg_exp))
# Use sympy.integrate() method
intr = integrate(gfg_exp, x)
print("After Integration : {}".format(intr))
Output :
Before Integration : exp(x)*sin(x)
After Integration : exp(x)*sin(x)/2 – exp(x)*cos(x)/2

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)

sympy.limit() method:With the help of sympy.limit() method, we can find the


limit of any mathematical expression,
e.g.,
(1) \begin{equation*} \lim_{x\to a} f(x) \end{equation*}
Syntax: limit(expression, variable, value)
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.

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

sympy.log() method in Python: With the help of sympy.log() function, we can


simplify the principal branch of the natural logarithm. Logarithms are taken
with the natural base, e. To get a logarithm of a different base b, use log(x, y),
which is essentially short-hand for log(x) / log(y).
Syntax : sympy.log()
Return : Return the simplified mathematical expression.
# import sympy
from sympy import *
# Use sympy.log() method
gfg = log(16, 2)
print(gfg)
Output :
4

Sympy equation() method: In Simpy, the function equation() is used to make


equation of a given circle.
Syntax : equation(x='x', y='y')
Parameters:
x : str or Symbol, optional
y : str or Symbol, optional
Returns : SymPy expression
Example #1:
# import sympy, Point and Circle
from sympy import Point, Circle
# using Circle()
c1 = Circle(Point(0, 0), 5)
c2 = c1.equation()
print(c2)
Output:
x**2 + y**2 – 25

sympy.series() method: 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()
Return : Return a series of functions.

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)

sympy.eye() method:With the help of sympy.eye() method, we can find the


identity matrix by using sympy.eye() method.
Syntax : sympy.eye()
Return : Return an identity matrix.
Example #1 :
In this example, we can see that by using sympy.eye() method, we are able to
find identity matrix having dimension nxn, where n will be pass as a parameter.
# import sympy
from sympy import *
# Use sympy.eye() method
mat = eye(3)
print(mat)
Output :
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])

sympy.zeros() method:With the help of sympy.zeros() method, we can create a


matrix having dimension nxm and filled with zeros by using sympy.zeros()
method.
Syntax : sympy.zeros()
Return : Return a zero matrix.
Example #1 :
In this example, we can see that by using sympy.zero() method, we are able to
create the zero matrix having dimension nxn all filled with zeros, where nxm
will be pass as a parameter.
# import sympy
from sympy import *
# Use sympy.zero() method
mat = zeros(3, 4)
print(mat)
Output :
Matrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]])

sympy.ones() method:With the help of sympy.ones() method, we can create a


matrix having dimension nxm and filled with ones by using sympy.ones()
method.
Syntax : sympy.ones()
Return : Return a ones matrix.

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]])

sympy.diag() method:With the help of sympy.diag() method, we can create a


matrix having dimension nxn and filled with numbers in the diagonal by using
sympy.diag() method.
Syntax : sympy.diag()
Return : Return a new matrix.
Example #1 :
In this example, we can see that by using sympy.diag() method, we are able to
create a matrix having dimension nxn all filled with numbers in a diagonal as
passed in a parameter.
# import sympy
from sympy import *
# Use sympy.diag() method
mat = diag(3, 4)
print(mat)
Output :
Matrix([
[3, 0],
[0, 4]])

sympy.det() method:With the help of sympy.det() method, we can find the


determinant of a matrix by using sympy.det() method.
Syntax : sympy.det()
Return : Return determinant of a matrix.

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

sympy.Matrix().col_insert():With the help of Matrix().col_insert() method, we


can insert a column in a matrix having dimension nxm, where dimension of
inserted column is nx1.
Syntax : Matrix().col_insert()
Return : Return a new matrix.

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]])

sympy.Matrix().row_insert():With the help of Matrix().row_insert() method,


we can insert a row in a matrix having dimension nxm, where dimension of
inserted row is 1xm.
Syntax : Matrix().row_insert()
Return : Return a new matrix.

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]])

sympy.factorial() method:With the help of sympy.factorial(), we can find the


factorial of any number by using sympy.factorial() method.
Syntax : sympy.factorial()
Return : Return factorial of a number.
Example #1 :In this example we can see that by using sympy.factorial(), we are
able to find the factorial of number that is passed as parameter.
# import sympy
from sympy import *
# Using sympy.factorial() method
gfg_exp = factorial(5)
print(gfg_exp)
Output :
120

sympy.simplify() method:With the help of sympy.simplify() method, we can


simplify any mathematical expression.
Syntax: simplify(expression)
Parameters:
expression – It is the mathematical expression which needs to be simplified.
Returns: Returns a simplified mathematical expression corresponding to the
input expression.

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

sympy.Matrix.col() method:With the help of sympy.Matrix().col() method, we


can extract the columns of the matrix.
Syntax : sympy.Matrix().col()
Return : Return the col of a matrix.

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]])

sympy.Matrix.col_del() method:With the help of sympy.Matrix.col_del()


method, we can delete the columns of the matrix.
Syntax : sympy.Matrix().col_del()
Return : Return a new matrix.

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]])

sympy.Matrix.row_del() method:With the help of sympy.Matrix.row_del()


method, we can delete the rows of the matrix.
Syntax : sympy.Matrix().row_del()
Return : Return a new matrix.

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])

sympy.Matrix.eigenvals() method:With the help of sympy.Matrix.eigenvals()


method, we can find the eigen values of the matrix.
Syntax : sympy.Matrix().eigenvals()
Return : Return the eigen values of a matrix.
Example #1 :
In the given example we can see that the sympy.Matrix.eigenvals() method is
used to find the eigen values of a matrix.
# Import all the methods from sympy
from sympy import *
# use the eigenvales() method for matrix
gfg_val = Matrix([[1, 2], [2, 1]]).eigenvals()
print(gfg_val)
Output :
{3: 1, -1: 1}

sympy.Matrix() method:With the help of sympy.Matrix() method, we can make,


rearrange, extract the different rows and columns in a matrix which is created
by sympy.Matrix() method.
Syntax : sympy.Matrix()
Return : Return a matrix.

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]])

sympy.Matrix.row() method:With the help of sympy.Matrix.row() method, we


can extract the rows of the matrix.
Syntax : sympy.Matrix.row()
Return : Return the row of a matrix.

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

sympy.integrate() using limits:With the help of sympy.integrate(expression,


limit) method, we can find the integration of mathematical expressions using
limits in the form of variables by using sympy.integrate(expression, limit)
method.
Syntax : sympy.integrate(expression, reference variable, limit)
Return : Return integration of mathematical expression.

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)

Automata-based programming: Automata-based programming is a computer


programming paradigm that treats sections of the program as finite automata.
Each automaton can take one "step" at a time, and the execution of the program
is broken down into individual steps. The steps communicate with each other by
changing the value of a variable, representing the "state." The control flow of
the program is determined by the variable value.
The "state" variable can be a simple enum data type, but more complex data
structures may be used. A common technique is to create a state transition table,
a two-dimensional array comprising rows representing every possible state, and
columns representing input parameter. The table value where the row and
column meet is the next state the machine should transition to if both conditions
are met.
Finite state machine, Input, Paradigm, Programming terms
An automaton can be represented by a 5-tuple (Q, ∑, δ, q0, F), where −
• Q is a finite set of states. (q0,q1…..qn)(a,b,c)
• ∑ is a finite set of symbols, called the alphabet of the
automaton.(push,pop,delete…..) (1,0)
• δ is the transition function. Fn(q0,a) q1 (a,1)->b
• q0 is the initial state from where any input is processed (q0 ∈ Q). (q0 a)
• F is a set of final state/states of Q (F ⊆ Q). (fo->c)

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.

Finite Automaton can be classified into two types −


• Deterministic Finite Automaton (DFA)
• Non-deterministic Finite Automaton (NDFA / NFA)

Deterministic Finite Automaton (DFA)


In DFA, for each input symbol, one can determine the state to which the
machine will move. Hence, it is called Deterministic Automaton. As it has a
finite number of states, the machine is called Deterministic Finite Machine or
Deterministic Finite Automaton.
Formal Definition of a DFA
A DFA can be represented by a 5-tuple (Q, ∑, δ, q0, F) where −
• Q is a finite set of states.
• ∑ is a finite set of symbols called the alphabet.
• δ is the transition function where δ: Q × ∑ → Q
• q0 is the initial state from where any input is processed (q0 ∈ Q).
• F is a set of final state/states of Q (F ⊆ Q).
Graphical Representation of a DFA
A DFA is represented by digraphs called state diagram.
• The vertices represent the states.
• The arcs labeled with an input alphabet show the transitions.
• The initial state is denoted by an empty single incoming arc.
• The final state is indicated by double circles.
Example
Let a deterministic finite automaton be →
• Q = {a, b, c},
• ∑ = {0, 1},
• q0 = {a},
• F = {c}, and
Transition function δ as shown by the following table –
Present State Next State for Input 0 Next State for Input 1

a a b

b c a

c b c

Non-deterministic Finite Automaton:


In NDFA, for a particular input symbol, the machine can move to any
combination of the states in the machine. In other words, the exact state to
which the machine moves cannot be determined. Hence, it is called Non-
deterministic Automaton. As it has finite number of states, the machine is called
Non-deterministic Finite Machine or Non-deterministic Finite Automaton.
Formal Definition of an NDFA
An NDFA can be represented by a 5-tuple (Q, ∑, δ, q0, F) where −
• Q is a finite set of states.
• ∑ is a finite set of symbols called the alphabets.
• δ is the transition function where δ: Q × ∑ → 2Q
(Here the power set of Q (2Q) has been taken because in case of NDFA, from a
state, transition can occur to any combination of Q states)
• q0 is the initial state from where any input is processed (q0 ∈ Q).
• F is a set of final state/states of Q (F ⊆ Q).
Graphical Representation of an NDFA: (same as DFA)
An NDFA is represented by digraphs called state diagram.
• The vertices represent the states.
• The arcs labeled with an input alphabet show the transitions.
• The initial state is denoted by an empty single incoming arc.
• The final state is indicated by double circles.
Example
Let a non-deterministic finite automaton be →
• Q = {a, b, c}
• ∑ = {0, 1}
• q0 = {a}
• F = {c}
The transition function δ as shown below –
Present State Next State for Input 0 Next State for Input 1

a a, b b

b c a, c

c b, c c

Its graphical representation would be as follows –

Automata is a Python 3 library which implements the structures and algorithms


for finite automata, pushdown automata, and Turing machines.
Automata requires Python 3.4 or newer.
Installing
You can install the latest version of Automata via pip:
pip install automata-lib
The Automaton class is an abstract base class from which all automata
(including Turing machines) inherit. As such, it cannot be instantiated on its
own; you must use a defined subclasses instead (or you may create your own
subclass if you’re feeling adventurous). The Automaton class can be found
under automata/base/automaton.py.
If you wish to subclass Automaton, you can import it like so:
from automata.base.automaton import Automaton

The following methods are common to all Automaton subtypes:


 Automaton.read_input(self, input_str)
Reads an input string into the automaton, returning the automaton’s final
configuration (according to its subtype). If the input is rejected, the method
raises a RejectionException.
 Automaton.read_input_stepwise(self, input_str)
Reads an input string like read_input(), except instead of returning the final
configuration, the method returns a generator. The values yielded by this
generator depend on the automaton’s subtype.
If the string is rejected by the automaton, the method still raises a
RejectionException.
 Automaton.accepts_input(self, input_str)
Reads an input string like read_input(), except it returns a boolean instead of
returning the automaton’s final configuration (or raising an exception). That is,
the method always returns True if the input is accepted, and it always returns
False if the input is rejected.
 Automaton.validate(self)
Checks whether the automaton is actually a valid automaton (according to its
subtype). It returns True if the automaton is valid; otherwise, it will raise the
appropriate exception (e.g. the state transition is missing for a particular
symbol).
This method is automatically called when the automaton is initialized, so it’s
only really useful if a automaton object is modified after instantiation.
 Automaton.copy(self)
Returns a deep copy of the automaton according to its subtype.

class FA(Automaton, metaclass=ABCMeta)


The FA class is an abstract base class from which all finite automata inherit.
The FA class can be found under automata/fa/fa.py.
If you wish to subclass FA, you can import it like so:
from automata.fa.fa import FA
class DFA(FA)
The DFA class is a subclass of FA and represents a deterministic finite
automaton. It can be found under automata/fa/dfa.py.
Every DFA has the following (required) properties:
1. states: a set of the DFA’s valid states, each of which must be represented
as a string
2. input_symbols: a set of the DFA’s valid input symbols, each of which
must also be represented as a string
3. transitions: a dict consisting of the transitions for each state. Each key is a
state name and each value is a dict which maps a symbol (the key) to a state (the
value).
4. initial_state: the name of the initial state for this DFA
5. final_states: a set of final states for this DFA

from automata.fa.dfa import DFA


# DFA which matches all binary strings ending in an odd number of '1's
dfa = DFA(
states={'q0', 'q1', 'q2'},
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(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 PDA(Automaton, metaclass=ABCMeta)


The PDA class is an abstract base class from which all pushdown automata
inherit. It can be found under automata/pda/pda.py.
class DPDA(PDA)
The DPDA class is a subclass of PDA and represents a deterministic finite
automaton. It can be found under automata/pda/dpda.py.
Every DPDA has the following (required) properties:
1. states: a set of the DPDA’s valid states, each of which must be
represented as a string
2. input_symbols: a set of the DPDA’s valid input symbols, each of which
must also be represented as a string
3. stack_symbols: a set of the DPDA’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 DPDA
6. initial_stack_symbol: the name of the initial symbol on the stack for this
DPDA
7. final_states: a set of final states for this DPDA
8. acceptance_mode: a string defining whether this DPDA accepts by
'final_state', 'empty_stack', or 'both'; the default is 'both'
from automata.pda.dpda import DPDA
# DPDA which which matches zero or more 'a's, followed by the same
# number of 'b's (accepting by final state)
dpda = DPDA(
states={'q0', 'q1', 'q2', 'q3'},
input_symbols={'a', 'b'},
stack_symbols={'0', '1'},
transitions={
'q0': {
'a': {'0': ('q1', ('1', '0'))} # transition pushes '1' to stack
},
'q1': {
'a': {'1': ('q1', ('1', '1'))},
'b': {'1': ('q2', '')} # transition pops from stack
},
'q2': {
'b': {'1': ('q2', '')},
'': {'0': ('q3', ('0',))} # transition does not change stack
}
},
initial_state='q0',
initial_stack_symbol='0',
final_states={'q3'},
acceptance_mode='final_state'
)
 DPDA.read_input(self, input_str)
Returns a PDAConfiguration object representing the DPDA’s config. This is
basically a tuple containing the final state the DPDA stopped on, the remaining
input (an empty string) as well as a PDAStack object representing the DPDA’s
stack (if the input is accepted).
dpda.read_input('ab') # returns PDAConfiguration('q3', '', PDAStack(('0')))
dpda.read_input('aab') # raises RejectionException
 DPDA.read_input_stepwise(self, input_str)
Yields PDAConfiguration objects. These are basically tuples containing the
current state, the remaining input and the current stack as a PDAStack object, if
the input is accepted.
dpda.read_input_stepwise('ab')
# yields:
# PDAConfiguration('q0', 'ab', PDAStack(('0')))
# PDAConfiguration('q1', 'a', PDAStack(('0', '1')))
# PDAConfiguration('q3', '', PDAStack(('0')))
 DPDA.accepts_input(self, input_str)
if dpda.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')
 DPDA.validate(self)
dpda.validate() # returns True
 DPDA.copy(self)
dpda.copy() # returns deep copy of dpda

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

GUI programming paradigm:


GUI stands for Graphical User Interface. GUI permits users to use the graphics
to interact with an operating system. In graphical user interface, menus are
provided such as : windows, scrollbars, buttons, wizards, painting pictures,
alternative icons etc. It’s intuitive, simple to find out and reduces psychological
feature load. In GUI, the information is shown or presented to the user in any
form such as: plain text, videos, images, etc.

wxPython module Introduction


Python provides wxpython module which allows us to create high functional
graphical user interface. It is an Open Source module, which means it is free for
anyone to use and the source code is available for anyone to look and modify.
It is implemented as a set of extension modules that wrap the GUI components
of wxWidgets library which is written in C++. It is cross platform GUI toolkit
for python, Phoenix version Phoenix is the improved next-generation wxPython
and it mainly focused on speed, maintainablity and extensibility.
Install using this command:
pip install wxpython

Creating GUI using wxpython:

First import wx module.


Create an object for application class.
Create an object for frame class and other controls are added to frame object so
its layout is maintained using panel .
Then add a Static text object to show Hello World .
Show the frame window by using show method.
Run the app till the window is closed by using main event loop application
object.
Example #1: A simple GUI application which says GEEKS FOR GEEKS using
wxpython.

# 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()

Example #2: Creating Buttons using wx module


# Import wx module
import wx
# creaing application object
app1 = wx.App()
# creating a frame
frame = wx.Frame(None, title ="wxpython app")
pa = wx.Panel(frame)
# Button creation
e = wx.Button(pa, -1, "Button1", pos = (120, 100))
# show it
frame.Show()
# start the event loop
app1.Mainloop()

Example #3: CheckBox using wxpython

# 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()

Example #4: RadioButtons using wxpython

# 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)
# RadioButton creation using wx module
e = wx.RadioButton(pa, -1, "RadioButton1", pos = (120, 100))
e = wx.RadioButton(pa, -1, "radioButton2", pos = (120, 120))
# show it
frame.Show()
# start the event loop
app1.Mainloop()

Introduction to PyQt5:There are so many options provided by Python to


develop GUI application and PyQt5 is one of them. PyQt5 is cross-platform
GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive
desktop application with so much ease because of the tools and simplicity
provided by this library.
A GUI application consists of Front-end and Back-end. PyQt5 has provided a
tool called ‘QtDesigner’ to design the front-end by drag and drop method so
that development can become faster and one can give more time on back-end
stuff.

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

Create your first app –


This is a simple app having a single button in the window. After clicking that
button a message will appear “You clicked me”. Let’s start.
First of all, we need to find QtDesigner to create the front-end part.
– QtDesigner is present at ‘site-packages/pyqt5_tools’
– For finding the location of site-packages write the following python code
using any editor of your choice and then run:
>>> import site
>>> site.getsitepackages()
– Run the application named ‘designer’.
 A window will open:select the ‘Dialog without Button’ option and click
‘Create’
 At the left side of the designer there will be various widgets which can be
dragged and dropped in our window according to our requirement.
 Find and drag-and-drop ‘Push Button’ and ‘Label’.
 Change the text inside the widgets by right clicking it and selecting
‘Change plain text’. Keep the text of the Label blank.
 We have created our front-end layout, just save it at your desired
location.Remember, this file will have .ui as extension.
 We need to convert the .ui file into .py file to get the python form of the
widgets and attach necessary event listeners to them.

Converting .ui file into .py file:


For this we have to go to sitpackages directory in terminal or command prompt
and run the command as shown below. Getting the location of sitepackages is
mentioned previously.
>>> cd “C:\\Users\\……\\Programs\\Python\\Python36-32\\lib\\site-packages”
[Location of sitepackages]
>>> pyuic5 “C:\Users\……\FILENAME.ui”[Exact location of .ui file] -o ”
C:\Users\…….\FILENAME.py” [Location where want to put .py file]
 Finally we will add signals and slot in the python code to make it fully
functional.
widget.signal.connect(slot)
A signal is emitted by widgets after the occurrence of a certain kind of
event like a click, Double click, etc.
A slot is any callable function which will perform some action after the
occurrence of an event.
 Run the app and click the button.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

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)

# adding signal and slot


self.pushButton.clicked.connect(self.showmsg)

def retranslateUi(self, Dialog):


_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "Click"))

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_())

Designing GUI applications Using PyQt in Python:Building GUI


applications using PYQT designer tool is comparatively less time consuming
than code the widgets. It is one of the fastest and easiest ways to create GUIs.
The normal approach is to write the code even for the widgets and for the
functionalities as well. But using Qt-designer, one can simply drag and drop the
widgets, which comes very useful while developing big-scale applications.
Installation of PyQt5 :
For Linux :
sudo apt-get install python3-pyqt5
For Windows :
pip install pyqt5
pip install pyqt5-tools

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!

Jython(JPython) – Introduction and Installation: It’s not hidden that Java is


a powerful and Python is a simple and easy language. To get them both
together, Jython was introduced so it is both powerful and simple. It is a pure
Java implementation of Python. It uses Python’s syntax and Java’s environment.
It allows using features of Python in Java environment or to import Java classes
in Python codes and hence, is very flexible. Jython can run on almost any
platform which provides flexibility in application deployment and it also
provides many libraries with many more APIs.
It is really beneficial for those who create applications in Java and are new to
Python. Python has three implementations:
 Cpython(mostly used)
 Jython
 IronPython

Installation of Jython
Windows
 Download your copy from www.jython.org

 It will be combined as a cross-platform executable JAR file


 If you don’t have Java installed in your system you will need to grab a
copy of it. you can download it from www.java.com and install it.
 Double click on the JAR file and install it with “All” features installed
 Find the jython.bat(windows) or jython.sh(Mac OS) file in the same
folder where you installed Jython
 Place this folder within your PATH environment variable
 After all this has done you will be able to open up the command
prompt, type jython and then hit the “enter” key

Linux

To install Jython in Linux type the below command in the terminal.


sudo apt install jython
After typing this command provide your sudo password and that’s it. Linux will
handle the rest. After installation, check whether Jython is installed correctly or
not. See the below image for checking.

Tkinter:Tkinter is an open-source Python Graphic User Interface (GUI) library


well known for its simplicity. It comes pre-installed in Python, so you don’t
even need to think about installing it. These characteristics make it a strong
position for beginners and intermediates to begin with. Tkinter cannot be used
for larger-scale projects.

Advantages of using Tkinter


 Tkinter is easy and fast to implement as compared to any other GUI
toolkit.
 Tkinter is more flexible and stable.
 Tkinter is included in Python, so nothing extra need to download.
 Tkinter provides a simple syntax.
 Tkinter is really easy to understand and master.
 Tkinter provides three geometry managers: place, pack, and grid. That is
much more powerful and easy to use.

Disadvantages of using Tkinter


 Tkinter does not include advanced widgets.
 It has no similar tool as Qt Designer for Tkinter.
 It doesn’t have a reliable UI.
 Sometime, it is hard to debug in Tkinter.
 It is not purely Pythonic.

You might also like