0% found this document useful (0 votes)
108 views33 pages

HG Notes2

DTA TYP

Uploaded by

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

HG Notes2

DTA TYP

Uploaded by

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

Data structure with python 20CS41P

ppypython

Queue
A queue is a linear structure that allows insertion of elements
from one end and deletion from the other. Thus it follows, First In
First Out(FIFO) methodology. The end which allows deletion is
known as the front of the queue and the other end is known as the
rear end of the queue.

Tree

IV SEM CSE 1
Data structure with python 20CS41P
ppypython
A tree is a non-linear but hierarchical data structure. The topmost element is known as the
root of the tree since the tree is believed to start from the root. The elements at the end of
the tree are known as its leaves. Trees are appropriate for storing data that aren’t linearly
connected to each other but form a hierarchy.

Graph
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are
sometimes also referred to as vertices and the edges are lines or arcs that connect any two
nodes in the graph. A Graph consists of a finite set of vertices(or nodes) and set of Edges
which connect a pair of nodes.

Hashmap
Hash maps are indexed data structures. A hash map makes use of a hash
function to compute an index with a key into an array of buckets or slots.
Its value is mapped to the bucket with the corresponding index. The key is
unique and immutable. In Python, dictionaries are examples of hash
maps.
call the language Python.

IV SEM CSE 2
Data structure with python 20CS41P
ppypython

UNIT 2
ALGORITHM ANALYSIS
Algorithm analysis is the process of evaluating the performance of an
algorithm, usually in terms of its time and space complexity. There are
several ways to analyze the performance of an algorithm, including
asymptotic analysis, which analyzes the behavior of an algorithm as the
size of the input grows indefinitely.
Space complexity refers to the total amount of memory space used by an
algorithm/program, including the space of input values for execution.
Calculate the space occupied by variables in an algorithm/program to
determine space complexity.

IV SEM CSE 3
Data structure with python 20CS41P
ppypython

We have discussed Asymptotic Analysis, and Worst, Average, and Best


Cases of Algorithms. The main idea of asymptotic analysis is to have a
measure of the efficiency of algorithms that don’t depend on machine-
specific constants and don’t require algorithms to be implemented and
time taken by programs to be compared. Asymptotic notations are
mathematical tools to represent the time complexity of algorithms for
asymptotic analysis. Python places a strong emphasis on clean, readable
code. Its syntax is designed to be highly readable, with minimal use of
brackets and a clear layout using indentation and whitespace. By relying
on indentation to define code blocks, Python enables developers to write
code that is not only easy to write but also easy to read and understand.
Asymptotic Notations:
 Asymptotic Notations are mathematical tools used to analyze the
performance of algorithms by understanding how their efficiency
changes as the input size grows.
 These notations provide a concise way to express the behavior of an
algorithm’s time or space complexity as the input size approaches
infinity.
 Rather than comparing algorithms directly, asymptotic analysis focuses
on understanding the relative growth rates of algorithms’ complexities.
 It enables comparisons of algorithms’ efficiency by abstracting away
machine-specific constants and implementation details, focusing instead
on fundamental trends.
 Asymptotic analysis allows for the comparison of algorithms’ space and
time complexities by examining their performance characteristics as the
input size varies.
 By using asymptotic notations, such as Big O, Big Omega, and Big
Theta, we can categorize algorithms based on their worst-case, best-
case, or average-case time or space complexities, providing valuable
insights into their efficiency.

1. Theta Notation (Θ-Notation):


Theta notation encloses the function from above and below. Since it represents the upper
and the lower bound of the running time of an algorithm, it is used for analyzing the
average-case complexity of an algorithm.
.Theta (Average Case) You add the running times for each possible input combination

IV SEM CSE 4
Data structure with python 20CS41P
ppypython

and take the average in the average case.


Let g and f be the function from the set of natural numbers to itself. The function f is said
to be Θ(g), if there are constants c1, c2 > 0 and a natural number n0 such that c1* g(n) ≤
f(n) ≤ c2 * g(n) for all n ≥ n0

2. Big-O Notation (O-notation):


Big-O notation represents the upper bound of the running time of an algorithm. Therefore, it
gives the worst-case complexity of an algorithm.
.It is the most widely used notation for Asymptotic analysis.
.It specifies the upper bound of a function.
.The maximum time required by an algorithm or the worst-case time complexity.
.It returns the highest possible output value(big-O) for a given input.
.Big-O(Worst Case) It is defined as the condition that allows an algorithm to complete statement
execution in the longest amount of time possible.

If f(n) describes the running time of an algorithm, f(n) is O(g(n)) if there exist a positive constant
C and n0 such that, 0 ≤ f(n) ≤ cg(n) for all n ≥ n0
It returns the highest possible output value (big-O)for a given input.
The execution time serves as an upper bound on the algorithm’s time complexity.

3. Omega Notation (Ω-Notation):


Omega notation represents the lower bound of the running time of an algorithm. Thus, it
provides the best case complexity of an algorithm.
The execution time serves as a lower bound on the algorithm’s time complexity.
It is defined as the condition that allows an algorithm to complete statement
execution in the shortest amount of time.
Let g and f be the function from the set of natural numbers to itself. The function f is said to be
Ω(g), if there is a constant c > 0 and a natural number n0 such that c*g(n) ≤ f(n) for all n ≥ n0

IV SEM CSE 5
Data structure with python 20CS41P
ppypython

IV SEM CSE 6
Data structure with python 20CS41P
ppypython

UNIT 3
Algorithm Design Strategies
Types of Brute Force Algorithm in Data Structures
1. Optimizing: In this case, the best solution is found. To find the best solution, it may
either find all the possible solutions to find the best solution or if the value of the
best solution is known, it stops finding when the best solution is found. For
example: Finding the best path for the traveling salesman problem. Here the best
path means that traveling all the cities and the cost of travelling should be minimal.
2. Satisficing: It stops finding the solution as soon as the satisfactory solution is found.
For example, finding the traveling salesman path within 10% of optimal.

Bubble Sort Algorithm

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order. This algorithm is not suitable for
large data sets as its average and worst-case time complexity are quite high.
 We sort the array using multiple passes. After the first pass, the maximum element
goes to end (its correct position). Same way, after second pass, the second largest
element goes to second last position and so on.
 In every pass, we process only those elements that have already not moved to
correct position. After k passes, the largest k elements must have been moved to the
last k positions.
 In a pass, we consider remaining elements and compare all adjacent and swap if
larger element is before a smaller element. If we keep doing this, we get the largest
(among the remaining elements) at its correct position.

IV SEM CSE 7
Data structure with python 20CS41P
ppypython

Advantages of Bubble Sort


 Simplicity: Easy to understand and implement.
 Minimal code: Requires minimal lines of code for implementation.
 Suitable for small datasets: Works well for small-sized arrays or lists.
 Stable: Elements with equal values retain their relative order.
Disadvantages of Bubble Sort Algorithm
 The main disadvantage is the amount of time it takes. It is highly inefficient for large data
sets, with a running time of O(n2).
 Furthermore, the presence of turtles can significantly slow the sort.
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly
selecting the smallest (or largest) element from the unsorted portion and swapping it with
the first unsorted element. This process continues until the entire array is sorted.
1. First we find the smallest element and swap it with the first element. This way we get the
smallest element at its correct position.
2. Then we find the smallest among remaining elements (or second smallest) and swap it
with the second element.
3. We keep doing this until we get all elements moved to correct position.

IV SEM CSE 8
Data structure with python 20CS41P
ppypython

Advantages of Selection Sort


 Easy to understand and implement, making it ideal for teaching basic sorting concepts.
 Requires only a constant O(1) extra memory space.
 It requires less number of swaps (or memory writes) compared to many other standard
algorithms. Only cycle sort beats it in terms of memory writes. Therefore it can be simple
algorithm choice when memory writes are costly.

Disadvantages of the Selection Sort


 Selection sort has a time complexity of O(n^2) makes it slower compared to algorithms
like Quick Sort or Merge Sort.
 Does not maintain the relative order of equal elements which means it is not stable.
Linear Search Algorithm
Last Updated : 28 Oct, 2024



Given an array, arr of n integers, and an integer element x, find whether element x is present
in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn’t exist.
Input: arr[] = [1, 2, 3, 4], x = 3
Output: 2
Explanation: There is one test case with array as [1, 2, 3 4] and element to be searched as 3.
Since 3 is present at index 2, the output is 2.
Input: arr[] = [10, 8, 30, 4, 5], x = 5
Output: 4
Explanation: For array [1, 2, 3, 4, 5], the element to be searched is 5 and it is at index 4. So,
the output is 4.
Input: arr[] = [10, 8, 30], x = 6
Output: -1
Explanation: The element to be searched is 6 and its not present, so we return -1.

IV SEM CSE 9
Data structure with python 20CS41P
ppypython
Time and Space Complexity of Linear Search Algorithm:
Time Complexity:
 Best Case: In the best case, the key might be present at the first index. So the best case
complexity is O(1)
 Worst Case: In the worst case, the key might be present at the last index i.e., opposite to
the end from which the search has started in the list. So the worst-case complexity is O(N)
where N is the size of the list.
 Average Case: O(N)
Auxiliary Space: O(1) as except for the variable to iterate through the list, no other variable
is used.
Applications of Linear Search Algorithm:
 Unsorted Lists: When we have an unsorted array or list, linear search is most commonly
used to find any element in the collection.
 Small Data Sets: Linear Search is preferred over binary search when we have small data
sets with
 Searching Linked Lists: In linked list implementations, linear search is commonly used
to find elements within the list. Each node is checked sequentially until the desired
element is found.
 Simple Implementation: Linear Search is much easier to understand and implement as
compared to Binary Search or Ternary Search.
Advantages of Linear Search Algorithm:
 Linear search can be used irrespective of whether the array is sorted or not. It can be used
on arrays of any data type.
 Does not require any additional memory.
 It is a well-suited algorithm for small datasets.
Disadvantages of Linear Search Algorithm:
 Linear search has a time complexity of O(N), which in turn makes it slow for large
datasets.
 Not suitable for large arrays.

IV SEM CSE 10
Data structure with python 20CS41P
ppypython

UNIT 4
Divide and Conquer
Divide and Conquer Algorithm is a problem-solving technique used to solve problems
by dividing the main problem into subproblems, solving them individually and then
merging them to find solution to the original problem. In this article, we are going to
discuss how Divide and Conquer Algorithm is helpful and how we can use it to solve
problems.

Divide and Conquer Algorithm Definition:


Divide and Conquer Algorithm involves breaking a larger problem into
smaller subproblems, solving them independently, and then combining
their solutions to solve the original problem. The basic idea is to
recursively divide the problem into smaller subproblems until they become
simple enough to be solved directly. Once the solutions to the subproblems
are obtained, they are then combined to produce the overall solution.
1. Divide:
 Break down the original problem into smaller subproblems.

 Each subproblem should represent a part of the overall problem.

 The goal is to divide the problem until no further division is possible.

2. Conquer:
 Solve each of the smaller subproblems individually.

 If a subproblem is small enough (often referred to as the “base case”),


we solve it directly without further recursion.
 The goal is to find solutions for these subproblems independently.

IV SEM CSE 11
Data structure with python 20CS41P
ppypython

3. Merge:
 Combine the sub-problems to get the final solution of the whole
problem.
 Once the smaller subproblems are solved, we recursively combine their
solutions to get the solution of larger problem.
 The goal is to formulate a solution for the original problem by merging
the results from the subproblems.

Characteristics of Divide and Conquer Algorithm:


Divide and Conquer Algorithm involves breaking down a problem into
smaller, more manageable parts, solving each part individually, and then
combining the solutions to solve the original problem. The characteristics
of Divide and Conquer Algorithm are:
 Dividing the Problem: The first step is to break the problem into
smaller, more manageable subproblems. This division can be done
recursively until the subproblems become simple enough to solve
directly.
 Independence of Subproblems: Each subproblem should be
independent of the others, meaning that solving one subproblem does
not depend on the solution of another. This allows for parallel
processing or concurrent execution of subproblems, which can lead to
efficiency gains.
 Conquering Each Subproblem: Once divided, the subproblems are
solved individually. This may involve applying the same divide and
conquer approach recursively until the subproblems become simple
enough to solve directly, or it may involve applying a different
algorithm or technique.
 Combining Solutions: After solving the subproblems, their solutions
are combined to obtain the solution to the original problem. This
combination step should be relatively efficient and straightforward, as
the solutions to the subproblems should be designed to fit together
seamlessly.
Merge sort is a sorting algorithm that follows the divide-and-
conquer approach. It works by recursively dividing the input array into
smaller subarrays and sorting those subarrays then merging them back
together to obtain the sorted array.
In simple terms, we can say that the process of merge sort is to divide
the array into two halves, sort each half, and then merge the sorted

IV SEM CSE 12
Data structure with python 20CS41P
ppypython
halves back together. This process is repeated until the entire array is
sorted.

Advantages of Merge Sort:


 Stability : Merge sort is a stable sorting algorithm, which means it
maintains the relative order of equal elements in the input array.
 Guaranteed worst-case performance: Merge sort has a worst-case
time complexity of O(N logN) , which means it performs well even on
large datasets.
 Simple to implement: The divide-and-conquer approach is
straightforward.
 Naturally Parallel : We independently merge subarrays that makes it
suitable for parallel processing.
Disadvantages of Merge Sort:
 Space complexity: Merge sort requires additional memory to store the
merged sub-arrays during the sorting process.
 Not in-place: Merge sort is not an in-place sorting algorithm, which
means it requires additional memory to store the sorted data. This can
be a disadvantage in applications where memory usage is a concern.
 Slower than QuickSort in general. QuickSort is more cache friendly
because it works in-place.
Quick Sort
Quick Sort is a sorting algorithm based on the Divide and Conquer that
picks an element as a pivot and partitions the given array around the
picked pivot by placing the pivot in its correct position in the sorted array.

IV SEM CSE 13
Data structure with python 20CS41P
ppypython

How does QuickSort Algorithm work?


QuickSort works on the principle of divide and conquer, breaking down
the problem into smaller sub-problems.
There are mainly three steps in the algorithm:
1. Choose a Pivot: Select an element from the array as the pivot. The
choice of pivot can vary (e.g., first element, last element, random
element, or median).
2. Partition the Array: Rearrange the array around the pivot. After
partitioning, all elements smaller than the pivot will be on its left, and
all elements greater than the pivot will be on its right. The pivot is then
in its correct position, and we obtain the index of the pivot.
3. Recursively Call: Recursively apply the same process to the two
partitioned sub-arrays (left and right of the pivot).
4. Base Case: The recursion stops when there is only one element left in
the sub-array, as a single element is already sorted.

Choice of Pivot
There are many different choices for picking pivots.
 Always pick the first (or last) element as a pivot . The below
implementation picks the last element as pivot. The problem with this
approach is it ends up in the worst case when array is already sorted.
 Pick a random element as a pivot . This is a preferred approach because
it does not have a pattern for which the worst case happens.
IV SEM CSE 14
Data structure with python 20CS41P
ppypython

 Pick the median element is pivot. This is an ideal approach in terms of


time complexity as we can find median in linear time and the partition
function will always divide the input array into two halves. But it takes
more time on average as median finding has high constants.

Illustration of QuickSort Algorithm


In the previous step, we looked at how the partitioning process rearranges the array
based on the chosen pivot. Next, we apply the same method recursively to the smaller
sub-arrays on the left and right of the pivot. Each time, we select new pivots and
partition the arrays again. This process continues until only one element is left, which
is always sorted. Once every element is in its correct position, the entire array is
sorted.
Below image illustrates, how the recursive method calls for the smaller sub-arrays on
the left and right of the pivot:

hat offer a
Binary Search Algorithm – Iterative and Recursive Implementation

Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly


dividing the search interval in half. The idea of binary search is to use the information
that the array is sorted and reduce the time complexity to O(log N).
Binary Search Algorithm

IV SEM CSE 15
Data structure with python 20CS41P
ppypython

wide
Dynamic Programming (DP) Introduction

Dynamic Programming is a commonly used algorithmic technique used to optimize


recursive solutions when same subproblems are called again.
 The core idea behind DP is to store solutions to subproblems so that each is solved only
once.
 To solve DP problems, we first write a recursive solution in a way that there are
overlapping subproblems in the recursion tree (the recursive function is called with
same parameters multiple times)
 To make sure that a recursive value is computed only once (to improve time taken by
algorithm), we store results of the recursive calls.
 There are two ways to store the results, one is top down (or memoization) and other is
bottom up (or tabulation).

range of

IV SEM CSE 16
Data structure with python 20CS41P
ppypython

program to Print Fibonacci Series

Ever wondered about the cool math behind the Fibonacci series? This simple pattern
has a remarkable presence in nature, from the arrangement of leaves on plants to the
spirals of seashells. We’re diving into this Fibonacci Series sequence. It’s not just
math, it’s in art, nature, and more! Let’s discover the secrets of the Fibonacci
series together.
What is the Fibonacci Series?
The Fibonacci series is the sequence where each number is the sum of the previous
two numbers of the sequence. The first two numbers of the Fibonacci series are 0 and
1 and are used to generate the Fibonacci series.

unctionaities. These

How to Find the Nth term of Fibonacci Series?


In mathematical terms, the number at the nth position can be represented by:
Fn = Fn-1 + Fn-2

where, F0 = 0 and F1 = 1.
For example, Fibonacci series 10 terms are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Please refer Different Ways to Find Nth Fibonacci Number for details.
modules and packages help simplify complex tasks by providing pre-built functionalities,
saving developers time and effort.
Program to print first N terms of Fibonacci Series:
Given a number n, our task is to print first n terms of the Fibonacci Series.
Input : n = 5
Output : 0 1 1 2 3

Input n = 1Output : 0
Python’s standard library includes modules and packages for regular expressions, GUI
IV SEM CSE 17
Data structure with python 20CS41P
ppypython
programming, networking, data processing, and much more. This vast ecosystem ensures that
developers have access to a wide array of tools without the need for external dependencies. It
streamlines software development and ensures compatibility across different versions of
Python.
By leveraging the functionalities provided by the standard library, developers can
significantly boost their productivity and reduce development time.

2.Cross-Platform Compatibility
Python’s cross-platform compatibility allows it to run seamlessly on different operating
systems such as Windows, macOS, and Linux. Developers can write their code once and
deploy it on multiple platforms, saving time and effort in application development.
Cross-platform compatibility is crucial in modern software development, as it enables
applications to reach a broader audience across various devices and operating systems.
Python’s ability to run on multiple platforms makes it a versatile choice for developers who
want to build applications that work everywhere.

3. Dynamic Typing and Dynamic Binding


Python is a dynamically-typed language, which means that the type of a variable is
determined at runtime. Unlike statically-typed languages, such as C++ or Java, Python does
not require explicit type declarations. This dynamic typing feature results in faster
development time and increases code flexibility.
Dynamic binding, another key feature of Python, allows variables to be bound to different
objects at runtime. This flexibility contributes to the creation of reusable code and reduces
code redundancy. Developers can dynamically bind variables to different objects based on
specific conditions or changing requirements, making their code more adaptable and agile.

4.Strong Community Support


Python enjoys a vibrant and supportive community of developers worldwide. This
community provides various resources, including forums, online communities, and open-
source projects. The Python community strongly believes in knowledge sharing and mutual
support.
The active and friendly nature of the Python community makes it an ideal environment for
both beginners and experienced developers. Beginners can seek guidance and assistance,
while experienced developers can engage in discussions, share insights, and collaborate on
open- source projects. The strong community support fosters learning, mentoring, and
problem- solving, making Python a favorable choice for developers seeking growth and
support.

5. Object-Oriented Programming (OOP) Capabilities

IV SEM CSE 18
Data structure with python 20CS41P
ppypython

Python supports object-oriented programming (OOP) principles, such as encapsulation,


inheritance, and polymorphism. OOP enables developers to organize their code into reusable
and independent modules or components, making it easier to manage complex applications.
Python’s syntax and standard library provide intuitive and convenient ways to implement
OOP concepts.
In Python, developers can define classes, create objects, inherit properties and methods from
parent classes, and utilize polymorphism to write more flexible and maintainable code. By
leveraging Python’s OOP capabilities, developers can design modular and scalable
applications with ease.

6.Wide Range of Libraries and Frameworks


Python boasts a vast ecosystem of third-party libraries and frameworks. These libraries and
frameworks provide developers with access to pre-built code and functionalities, reducing
development time and increasing productivity.
For web development, Python offers popular frameworks like Django and Flask, which
simplify the process of building feature-rich web applications. In the field of data science,
Python provides powerful libraries like NumPy and Pandas for data manipulation and
analysis. When it comes to machine learning, Python offers libraries like TensorFlow and
PyTorch, which enable developers to create and train machine learning models efficiently.
Python’s extensive range of libraries and frameworks empowers developers to specialize in
their domains and build applications with a high degree of customization and functionality.

7. Versatility
Python’s versatility is one of its key strengths. It can be used for a wide range of applications,
including web development, data analysis, machine learning, scripting, and more. This
versatility allows developers to use a single language for diverse projects, simplifying their
workflow and reducing the learning curve associated with switching between different
languages.
Furthermore, using a single language like Python for different projects offers several benefits.
It facilitates code reuse, eases maintenance, and simplifies debugging across various
applications. Python’s versatility promotes efficiency and consistency in software
development.

8. Read-Evaluate-Print Loop (REPL) Environment


Python offers an interactive shell or Read-Evaluate-Print Loop (REPL) environment,
enabling developers to experiment with code snippets quickly. The REPL environment
allows developers to execute code and immediately see the output, facilitating rapid
prototyping and experimentation.
Python’s REPL environment plays a vital role in debugging and development, as it enables
developers to test code snippets, assess results, and refine their code iteratively. This real-
time feedback mechanism boosts productivity and accelerates the development process.

IV SEM CSE 19
Data structure with python 20CS41P
ppypython

Applications of python: Python is used in many application


domains. Here's a sampling.

 The Python Package Index lists thousands of third party modules for Python.

Web and Internet Development


Python offers many choices for web development:

 Frameworks such as Django and Pyramid.


 Micro-frameworks such as Flask and Bottle.
 Advanced content management systems such as Plone and django CMS.
Python's standard library supports many Internet protocols:

 HTML and XML


 JSON
 E-mail processing.

 Support for FTP, IMAP, and other Internet protocols.


 Easy-to-use socket interface.
And the Package Index has yet more libraries:

 Requests, a powerful HTTP client library.


 Beautiful Soup, an HTML parser that can handle all sorts of oddball HTML.
 Feedparser for parsing RSS/Atom feeds.

 Paramiko, implementing the SSH2 protocol.


 Twisted Python, a framework for asynchronous network programming.

Scientific and Numeric


Python is widely used in scientific and numeric computing:

 SciPy is a collection of packages for mathematics, science, and engineering.


 Pandas is a data analysis and modeling library.
 IPython is a powerful interactive shell that features easy editing and recording of
a work session, and supports visualizations and parallel computing.
 The Software Carpentry Course teaches basic skills for scientific computing,
running bootcamps and providing open-access teaching materials.

IV SEM CSE 20
Data structure with python 20CS41P
ppypython

Education
Python is a superb language for teaching programming, both at the introductory level and in
more advanced courses.

 Books such as How to Think Like a Computer Scientist, Python Programming: An


Introduction to Computer Science, and Practical Programming.
 The Education Special Interest Group is a good place to discuss teaching issues.

Desktop GUIs
The Tk GUI library is included with most binary distributions of Python.

Some toolkits that are usable on several platforms are available separately:

 wxWidgets
 Kivy, for writing multitouch applications.
 Qt via pyqt or pyside
Platform-specific toolkits are also available:

 GTK+
 Microsoft Foundation Classes through the win32 extensions

Software Development
Python is often used as a support language for software developers, for build control and
management, testing, and in many other ways.

 SCons for build control.


 Buildbot and Apache Gump for automated continuous compilation and testing.

 Roundup or Trac for bug tracking and project management.

Business Applications
Python is also used to build ERP and e-commerce systems:

 Odoo is an all-in-one management software that offers a range of business


applications that form a complete suite of enterprise management applications.
 Tryton is a three-tier high-level general purpose application platfo

Python IDE:
IDLE

IV SEM CSE 21
Data structure with python 20CS41P
ppypython

Python Software Foundation License

PyCharm
Proprietary software

Spyder
MIT License

Thonny
MIT License

Atom
MIT License

PyDev
Eclipse Public License

Visual Studio
Proprietary software

PyScripter
MIT License

Wing IDE
Proprietary software

IV SEM CSE 22
Data structure with python 20CS41P
ppypython

12 more

Python Interpreter: A python interpreter isa computer program that converts


each high-level program statement into machine code. An interpreter translates the
command that you write out into code that the computer can understand. However, to better
understand this definition, we must explain what high-level and low-level languages are.
Python compilation: The source code in python is saved as a .
py file
which is then compiled into a format known as byte code, byte code is then
converted to machine code. After the compilation, the code is stored in
. pyc files
and is regenerated when the source is updated. This process is known as
compilation.

Indentation: Indentation refers to the spaces at the beginning of a code line.


Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Comments: Comments can be used to explain Python code.


Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Types of comments:

There are three types of comments in Python:


 Single line Comments
 Multiline Comments
 String Literals
 Docstring Comments

IV SEM CSE 23
Data structure with python 20CS41P
ppypython

Character set: A character set is a set of valid characters


acceptable by a programming language in scripting. In this case,
we are talking about the Python programming language. So, the
Python character set is a valid set of characters recognized by the
Python language. These are the characters we can use during
writing a script in Python. Python supports all ASCII / Unicode
characters that include:
 Alphabets: All capital (A-Z) and small (a-z) alphabets.
 Digits: All digits 0-9.
 Special Symbols: Python supports all kind of special
symbols
like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] \ .
 White Spaces: White spaces like tab space, blank
space, newline, and carriage return.
 Other: All ASCII and UNICODE characters are
supported by Python that constitutes the Python

TOKENS: Tokens or lexical units are the smallest fractions in the


python programme. A token is a set of one or more characters having a
meaning together. There are 5 types of tokens in python which are listed
below:

1. Keywords

2. Identifiers

3. Literals

4. Operators

5. Punctuators

1. Keywords

A keyword is a reserved word in a computer language that has a specific


meaning. Python keywords form the vocabulary of the python language.
Keywords aren’t allowed to be used as identifiers. They are used to define
the Python language’s “Syntax” or “Structure.”

There are as in all 33 keywords used in Python programming language


version 3.7. Here are a few of them:

IV SEM CSE 24
Data structure with python 20CS41P
ppypython

 and, not, or: logical Operators

 as: To create an alias

 assert: For debugging

 break: To break out of a loop

 if: To create a conditional statement

 while: To create a while loop

2. Identifiers

Just as identity refers to a characteristic that distinguishes a person, the


same principle is a python identifier, a token in python. In Python, an
identifier is a name given to a Class, Function, or Variable. It aids in
distinguishing one entity from others.

Characteristics of Python Identifier

 The initial letter of the identifier should be any letter or underscore (_).

 Upper and lower case letters have distinct characteristics.

 Except for the initial letter, any digit from 0 to 9 can be part of the identification.

 It shouldn’t be used as a keyword

 Except for the underscore (_), an identifier cannot contain any special characters.

 Identifiers can be as long as you want them to be.

 Case matters when it comes to identifier names. Myself and myself, for
example, are not the same thing.

3. Operators

Operators are tokens that, when applied to variables and other objects in
an expression, cause a computation or action to occur. Operands are the
variables and objects to which the computation is applied. There are 7
different operators.

i) Arithmetic Operators

It performs all the mathematical calculations. Here are a few of them:

IV SEM CSE 25
Data structure with python 20CS41P
ppypython
 ( + ) Operands on either right and left sides of the operator are added.

IV SEM CSE 26
Data structure with python 20CS41P
ppypython

 ( – ) Subtract the right-hand operand from the left-hand operand with the
subtraction operator.

 (✖️) operator – Multiplies both sides of the operator’s operands.

 (➗) the left-hand operand by the right-hand operand with the division operator.

 (%) a percentage divides the left-hand operand by the right-hand operand and
returns the remainder with the modulus operator.

ii) Relational Operators

A relational operator is a type of operator that examines the relationship


between two operands. Some of the relational operators are:

 (== ) Check if two operands’ values are equal.

 (!= )Check if two operands’ values are not equal.

 (>) Check if two operands’ values are not identical (same as the!= operator).

iii) Assignment Operators

The assignment operators are employed to allocate a value to a variable.


A few examples are:

 (+=)It adds the right side input to the left side input and then assigns the
result to the left side input.

 (-= )Augmented assignment operator- It takes the right side operand and
subtracts it from the left side operand, then assigns the result to the left side
operand.

iv) Logical Operators

The logical operators compare two boolean expressions and yield a


boolean result. Like

 The logical AND operator makes a condition true if both operands are true or non-zero.

 The logical OR operator returns true if one of the two operands is true or non-zero.

v) Bitwise Operators

The bitwise operator manipulates individual bits in one or more bit


patterns or binary numbers. For example, If a binary XOR operator (^) is

IV SEM CSE 27
Data structure with python 20CS41P
ppypython
set in one input value but not both, it copies the matching binary 1 to the
result.

IV SEM CSE 28
Data structure with python 20CS41P
ppypython

vi) Membership Operators

The membership operator checks for membership in successions, such as


a string, list, or tuple. Like in a membership operator that fetches a
variable and if the variable is found in the supplied sequence, evaluate to
true; otherwise, evaluate to false.

vii) Identity Operators

When comparing the memory locations of two objects, identity operators


are used. If two variables point to separate objects, it does not return true;
otherwise, it returns false.

4. Literals

Literals, tokens in Python, are data elements with a fixed value. Literals
return a value for an object of the specified type. Python supports a
variety of literals:

 String Literals

 Numeric Literals. These are further of three types, integer, float, and complex literals.

 Boolean Literals

 Literal Collection

Lists, tuples, dictionaries, and sets are all examples of literal collections in Python.

 A list is a collection of elements enclosed in square brackets and separated


by commas. These variables can be of any data type, and their values can be
altered.

 Tuple: A comma-separated list of elements or values in round brackets is also


known as a tuple. Values can be of any data type, but they cannot be
modified.

 Dictionary: It’s an unsorted collection of key-value pairs.

 The “set” is an unordered collection of objects enclosed in curly braces.

5. Punctuators

Punctuators are tokens in python employed to put the grammar and


structure of syntax into practice. Punctuators are symbols that are used to
IV SEM CSE 29
Data structure with python 20CS41P
ppypython
structure programming sentences in a computer language. Some
commonly used punctuators are: ‘, ‘ ,#, \ ,(
) ,{ },[ ] ,@ ,: , =

IV SEM CSE 30
Data structure with python 20CS41P
ppypython

UNIT 2
BASIC I/O PERATIONS ,DATA TYPES,OPERATORS
INPUT():
Developers often have a need to interact with users, either to
get data or to provide some sort of result. Most programs
today use a dialog box as a way of asking the user to provide
some type of input. While Python provides us with two inbuilt
functions to read the input from the keyboard.
 input ( prompt )
 raw_input ( prompt )

input (): This function first takes the input from the user and
converts it into a string. The type of the returned object always
will be <class ‘str’>. It does not evaluate the expression it just
returns the complete statement as String. For example, Python
provides a built-in function called input which takes the input
from the user. When the input function is called it stops the
program and waits for the user’s input. When the user presses
enter, the program resumes and returns what the user typed.
Syntax:
inp =
input('STATEMENT')

Example:
1. >>> name = input('What is your name?\n') # \n --->
newline
---> It causes a line
break
>>> What is your
name? Ram
>>>

print(name)
Ram

# ---> comment in python


Output-print(),formatting output:
In Python, there are several ways to present the output of a
program. Data can be printed in a human-readable form, or

IV SEM CSE 31
Data structure with python 20CS41P
ppypython

written to a file for future use, or even in some other specified


form. Users often want more control over the formatting of
output than simply printing space-separated values.
Output Formatting in Python
There are several ways to format output using String Method in
Python.
 Using String Modulo Operator(%)

IV SEM CSE 32
PYTHON PROGRAMMING 20CS31P

Using Format Method



 Using The String Method
 Python’s Format Conversion Rule
Formatting Output using String Modulo Operator(%)
The Modulo % operator can also be used for string formatting. It
interprets the left argument much like a printf()-style format as
in C language strings to be applied to the right argument. In
Python, there is no printf() function but the functionality of the
ancient printf is contained in Python. To this purpose, the
modulo operator % is overloaded by the string class to perform
string formatting. Therefore, it is often called a string modulo
(or sometimes even called modulus) operator. The string modulo
operator ( %

String literals:

III SEM CSE 33

You might also like