You are on page 1of 237

Data Science

Python : Tokens
Can someone give a simple example for data,
information, knowledge and wisdom?
Data is a given fact or a set of qualitative or quantitative variables of a certain issue. These bits of pieces
values are still raw, and is insignificant unless they are collected and arranges in a certain manner which
will now give you information. Information then is a collection of data, which can be used to answer a
certain question or describe a concept.

Well knowledge and wisdom, are bit different from data and information, since knowledge is the
awareness or the conscious understanding of information or a concept. Thus, knowledge is more on the
intellectual or cognitive ability of a being to possess and interpret information.

While wisdom is usually defined as the application of knowledge. Wisdom is the used of knowledge to
formulate a judgment or to make sense of a certain situation or concept. It is also used for formulate
ideas, and the creation of new things.
Data: notice that they are raw and insignificant.
Ages of employees: 25; 29; 45; 23; 60; 51; 35 …
Names of employees: Ben; Anna: Mark; Kathy; Rose;
Jack; Jane …
Information: now we arrange the data to make sense
and create information.
Ages of Employees: Ben is 25 yrs old; Anna is 29 yrs
old; Mark is 45 yrs old; Kathy is 35 yrs old; Rose is 60
yrs old; while Jack is 51 yrs old…
Knowledge: so now we already have the knowledge of the ages of our employees,
so now we can connect that with our other knowledge, so we may have wisdom on
this situation.

Other knowledge: (for examples sake lets assume that we conducted a survey and
found out that:) Young people have still a lot to learn, and are inexperienced, and
are available for learning; and 35 yrs old is still young; And that older folks possess
a lot of knowledge regarding work processes; and has a lot of experience; and that
most of old folks today prefer to retire early; and say we would out that the usual
retirement age is 60, yet some employees would retire early at the age of 55.
So now we create Wisdom:

1. Our employees Ben, Anna, and Kathy are still young and they are prospective leaders of the firm.

2. They might want to earn a degree in a University and let’s offer them promotion to encourage them.

3. We know that Rose is retiring this year, so we might as well train someone to replace her in her
position. That might be Ben, Anna or Kathy, or Mark since he has more experience and has more
knowledge in our business processes already.

4. And since Jack is 51 yrs old already, we might want to prepare for his retirement. That will mean that
we might loss one or two employees in at least 4 years now.

Shall we hire more employees? (Further knowledge acquired) yes we might need more employees since
our business is growing and we need more manpower
Object Identity
In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function,
is used to identify the object identifier.
We assigned the b = a, a and b both point to the same object. When we checked by the
id() function it returned the same number. We reassign a to 500; then it referred to the
new object identifier.
Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the
digit (0-9), and underscore character(_).
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
Variable names can be a group of both the letters and digits, but they have to begin with
a letter or an underscore.
It is recommended to use lowercase letters for the variable name. Amit and amit both
are two different variables
Local Variables

Local variables, on the other hand, are variables declared inside a function. These
variables are known to have local scope. This means they can be accessed only within
the function in which they are declared.
In our code, we declared a function called printName(). Within that function, we defined
a variable called name. Because we declared this variable within a function, it is a local
variable.

At the end of our code, we called our function using printName(). In response, the
program executed the printName() function.

The name variable in this example is local to the printName() function. Therefore, we
cannot access that variable outside of our function
Global Variables

It is possible for a program to use the same variable name for both a local and a global variable. In
such a scenario, the local variable will be read in local scope, and the global variable will be read in
global scope.
First, we assigned the global variable score in our code. Then, in our calculateScore() function, we
created a local variable with the same name.

The value of our local score variable in the calculateScore() function is 10. So, when we call our
calculateScore() function, the message Final Score: 10 is printed to the console.

However, outside of our calculateScore() function, the value of the score variable is 5. This is
because we set the value of the score variable in global scope to 5. So, when we print out Initial
Score: , followed by the value of the score variable, the program displays the value 5.
Global variables are variables declared outside a function. Local variables are variables declared
inside a function.

While global variables cannot be directly changed in a function, you can use the global keyword to
create a function that will change the value of a global variable
Non local Variables

Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
there is a nested inner() function. We use nonlocal keywords to create a nonlocal
variable. The inner() function is defined in the scope of another function outer().
Python nonlocal keyword is used to reference a variable in the nearest scope.
The nonlocal keyword won’t work on local or global variables and therefore must be used
to reference variables in another scopes except the global and local one.
The nonlocal keyword is used in nested functions to reference a variable in the parent
function.
Internal working of Python

•Python is an object-oriented programming language like Java.


•Python is called an interpreted language.
• Python uses code modules that are interchangeable instead of a single long list
of instructions that was standard for functional programming languages.
•The standard implementation of python is called “cpython”.
•Python doesn’t convert its code into machine code, something that hardware can
understand.
• It actually converts it into something called byte code.
• So within python, compilation happens, but it’s just not into a machine language.
•It is into byte code (.pyc or .pyo) and this byte code can’t be understood by the
CPU.
•So we need an interpreter called the python virtual machine to execute the byte
codes
Internal working of Python
Python source code goes through the following to generate an
executable code

 
 
•Step 1: The python compiler reads a python source code or instruction. Then it verifies
that the instruction is well-formatted, i.e. it checks the syntax of each line. If it
encounters an error, it immediately halts the translation and shows an error message.
•Step 2: If there is no error, i.e. if the python instruction or source code is well-
formatted then the compiler translates it into its equivalent form in an intermediate
language called “Byte code”.
•Step 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python
interpreter. PVM converts the python byte code into machine-executable code. If an
error occurs during this interpretation then the conversion is halted with an error
message.
Interpreted Languages

• When you write a program in C/C++, you have to compile it.


• Compilation involves translating your human understandable code to machine understandable
code, or Machine Code.
• Machine code is the base level form of instructions that can be directly executed by the CPU.
Upon successful compilation, your code generates an executable file.
• Executing this file runs the operations in your code step by step.
• For the most part, Python is an interpreted language and not a compiled one, although
compilation is a step.
• Python code, written in .py file is first compiled to what is called bytecode which is stored
with a .pyc or .pyo format.
• Instead of translating source code to machine code like C++, Python code it translated to
bytecode.
• This bytecode is a low-level set of instructions that can be executed by an interpreter. In
most PCs, Python interpreter is installed at /usr/local/bin/python3.8.
• Instead of executing the instructions on CPU, bytecode instructions are executed on a Virtual
Machine.
Why Interpreted?

• One popular advantage of interpreted languages is that they are platform-


independent.
• As long as the Python bytecode and the Virtual Machine have the same version,
Python bytecode can be executed on any platform (Windows, MacOS, etc).

• Dynamic typing is another advantage.


• In static-typed languages like C++, you have to declare the variable type and any
discrepancy like adding a string and an integer is checked during compile time.
• In strongly typed languages like Python, it is the job of the interpreter to check the
validity of the variable types and operations performed.
What exactly is Garbage Collection?

• In older programming languages, memory allocation was quite manual.


• Many times when you use variables that are no longer in use or referenced anywhere
else in the program, they need to be cleaned from the memory.
• Garbage Collector does that for you. It automatically frees up space without you doing
anything. The memory management works in two ways —
• In a simplified way, it keeps track of the number of references to an object. When that
number goes down to zero, it deletes that object. This is called reference counting.
This cannot be disabled in Python.
• In cases where object references itself or two objects refer each other, a process
called generation garbage collection helps. This is something traditional reference
counting cannot take care of.
kernel

• The kernel is the server that enables Python programmers to run cells within
Notebook.
• You typically see the kernel commands in a separate command or terminal window.
• Each entry shows the time the kernel executed the task, which application the
command executed, the task it performed, and any resources affected.
• In most cases, you don’t need to do anything with this window, but viewing it can be
helpful when you run into problems because you often see error messages that can
help you resolve an issue.
•Interrupt: Causes the kernel to stop performing the current task without actually shutting the
kernel down. You can use this option when you want to do something like stop processing a large
dataset.
•Restart: Stops the kernel and starts it again. This option causes you to lose all the variable data.
However, in some cases, this is precisely what you need to do when the environment has become
dirty with old data.
•Restart & Clear Output: Stops the kernel, starts it again, and clears all the existing cell outputs.
•Restart & Run All: Stops the kernel, starts it again, and then runs every cell starting from the top
cell and ending with the last cell. When Notebook reaches the bottom, it selects the last cell but
doesn’t insert a new one.
•Reconnect: Recreates the connection to the kernel. In some cases, environmental or other issues
could cause the application to lose its connection, so you use this option to reestablish the connection
without loss of variable data.
•Shutdown: Shuts the kernel down. You may perform this step in preparation for using a different
kernel.
•Change Kernel: Selects a different kernel from the list of kernels you have installed. For example,
you may want to test an application using various Python versions to ensure that it runs on all of
them.
Python Data Types

Number stores numeric values.


The integer, float, and complex values belong to a Python Numbers data-type.
Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular
class.
Python creates Number objects when a number is assigned to a variable.
List
Python Lists are similar to arrays in C.
However, the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
We can use slice [:] operators to access the data of the list.
The concatenation operator (+) and repetition operator (*) works with the list in the
same way as they were working with the strings.
Tuple
A tuple is similar to the list in many ways.
Like lists, tuples also contain the collection of the items of different data types. The items
of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items
of a tuple.
Dictionary
Dictionary is an unordered set of a key-value pair of items.
It is like an associative array or a hash table where each key stores a specific value.
Key can hold any primitive data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly
braces {}.

Creating a dictionary is as simple as placing items inside curly braces {} separated by


commas.

An item has a key and a corresponding value that is expressed as a pair (key: value).

While the values can be of any data type and can repeat, keys must be of immutable type
(string, number or tuple with immutable elements) and must be unique.
Dictionaries

Dictionaries are mutable. We can add new items or change the value of existing items
using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is not
present, a new (key: value) pair is added to the dictionary.
We can remove a particular item in a dictionary by using the pop() method. This method
removes an item with the provided key and returns the value.

The popitem() method can be used to remove and return an arbitrary (key, value) item
pair from the dictionary. All the items can be removed at once, using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary
itself.
Dictionary Methods
Set
Python Set is the unordered collection of the data type.
It is iterable, mutable(can modify after creation), and has unique elements.
In set, the order of the elements is undefined; it may return the changed sequence
of the element.
The set is created by using a built-in function set(), or a sequence of elements is
passed in the curly braces and separated by the comma.
It can contain various types of values.
A set is an unordered collection of items. Every set element is unique (no duplicates)
and must be immutable (cannot be changed).

However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.
Frozen Set

The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on
a data structure known as a hash table. Since sets are unordered, we cannot access
items using indexes like we do in lists.
Frozen sets in Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied. It
can be done with frozenset() method in Python.

While elements of a set can be modified at any time, elements of the frozen set remain
the same after creation.

If no parameters are passed, it returns an empty frozenset.


Removing elements from a set

A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set
unchanged if the element is not present in the set.
On the other hand, the remove() function will raise an error in such a condition (if
element is not present in the set).
Modifying a set in Python

Sets are mutable. However, since they are unordered, indexing has no meaning.

We cannot access or change an element of a set using indexing or slicing. Set data type
does not support it.

We can add a single element using the add() method, and multiple elements using the
update() method. The update() method can take tuples, lists, strings or other sets as its
argument. In all cases, duplicates are avoided.
Sets

A set is created by placing all the items (elements) inside curly braces {}, separated by
comma, or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries
as its elements.
List
Tuple
Set
Dictionary
Introduction to for Loop in Python

In Python, the for loop is often used to iterate over iterable objects such as lists, tuples,
or strings.
Traversal is the process of iterating across a series. If we have a section of code that we
would like to repeat a certain number of times, we employ for loops.
The for-loop is usually used on an iterable object such as a list or the in-built range
function.
The for statement in Python traverses through the elements of a series, running the
block of code each time.
The for statement is in opposition to the "while" loop, which is employed whenever a
condition requires to be verified each repetition or when a piece of code is to be repeated
indefinitely.
On each iteration, the value is the parameter that gets the element's value within the
iterable sequence.
If an expression statement is present in a sequence, it is processed first. The iterating
variable iterating_variable is then allocated to the first element in the sequence.
After that, the intended block is run. The statement block is performed until the whole
sequence is completed, and each element in the sequence is allocated to
iterating_variable.
The for loop's material is distinguished from the rest of the program using indentation.
The range() Function

The "range" function appears so frequently in for loops, we might mistakenly believe the
range is a component of the syntax of for loop.
It isn't: it's a Python built-in method that provides a series that follows a specified
pattern , fulfilling the criteria of giving a series for the for expression to run over.
There is no necessity to count because for can act straight on sequences most of the
time.
Another method of iterating through every item is to use an index offset within the
sequence
The len() built-in method that returns the total number of items in the list or tuple and
the built-in function range(), which returns the exact sequence to iterate over.
Print()
• We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).

• We can also define the start, stop and step size as range(start, stop, step_size).
• Step_size defaults to 1 if not provided.

• The range object is "lazy" in a sense because it doesn't generate every number that it
"contains" when we create it. However, it is not an iterator since it supports in, len
and __getitem__ operations.

• This function does not store all the values in memory; it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.

• To force this function to output all the items, we can use the function list().
Using else Statement with for Loop

Python allows you to connect an else expression with a loop expression.

When the else clause is combined with a for loop, it is performed after the circuit has finished iterating
over the list.

The following instance shows how to use an otherwise statement in conjunction with a for expression
to find students' marks from the record.
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.


Nested For Loop

A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type,
such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice
versa.

The outer loop can contain more than one inner loop. There is no limitation on the chaining of
loops.

In the nested loop, the number of iterations will be equal to the number of iterations in the outer
loop multiplied by the iterations in the inner loop.

In each iteration of the outer loop inner loop execute all its iteration. For each iteration of an
outer loop the inner loop re-start and completes its execution before the outer loop can continue
to its next iteration.

Nested loops are typically used for working with multidimensional data structures, such as
printing two-dimensional arrays, iterating a list that contains a nested list.
Patterns
The basic functionality of all the techniques is the same, although the syntax and
the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop
command.
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted
when execution is completed.
Use if Else in For Loop to create this pattern
Use If Else with in For Loop to print odd values
Continue Statement
It returns the control to the beginning of the loop.

String = “Python loops” Use continue to achieve this pattern in For Loop
Try with omitting 0 ,p ,t
Break Statement :It stops the execution of the loop when the break
statement is reached

String = “Python loops” Use break to achieve this pattern in For Loop
Try with omitting L
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.
Python Strings

• Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes.
• The computer does not understand the characters; internally, it stores manipulated
character as the combination of the 0's and 1's.

• Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.

• In Python, strings can be created by enclosing the character or the sequence of


characters in the quotes.
• Python allows us to use single quotes, double quotes, or triple quotes to create the
string.
String Indexing
Colon to Extract Substring
strings are immutable. We cannot delete or remove the characters from the
string.  But we can delete the entire string using the del keyword.
They said, "Hello what's going on?"- the given statement can be written in single
quotes or double quotes but it will raise the Syntax Error as it contains both single
and double-quotes.
The backslash(/) symbol denotes the escape sequence. The backslash can be
followed by a special character and it interpreted differently. The single quotes
inside the string must be escaped. We can apply the same as in the double quotes.
The format() method

The format() method is the most flexible and useful method in formatting
strings.
The curly braces {} are used as the placeholder in the string and replaced by
the format() method argument.
Python String Formatting Using % Operator

Python allows us to use the format specifiers used in C's printf statement.
The format specifiers in Python are treated in the same way as they are treated in C.
However, Python provides an additional operator %, which is used as an interface
between the format specifiers and their values.
In other words, we can say that it binds the format specifiers to the values.
Difference between Pass and Continue
Functions in python

• A function is a collection of related assertions that performs a mathematical, analytical,


or evaluative operation.
• Python functions are simple to define and essential to intermediate-level programming.
The exact criteria hold to function names as they do to variable names.
• The goal is to group up certain often performed actions and define a function.
• Rather than rewriting the same code block over and over for varied input variables, we
may call the function and repurpose the code included within it with different variables.
• The functions are broad of two types, user-defined and built-in functions.
• It aids in keeping the software non-repetitive, and well-organized
Key Points

•The beginning of a function header is indicated by a keyword called def.


•Name of the function is the function's name that we can use to separate it from others.
We will use this name to call the function later in the program. The same criteria apply to
naming functions as to naming variables in Python.
•We pass arguments to the defined function using parameters. They are optional,
though.
•The function header is terminated by a colon (:).
•We can use a documentation string called docstring in the short form to explain the
purpose of the function.
•The body of the function is made up of several valid Python statements. The indentation
depth of the whole code block must be the same.
•We can use a return expression to return a value from a defined function.
Key Points

A function is defined by using the def keyword and giving it a name, specifying the
arguments that must be passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in
the program.
Pass by Reference vs. Value

In the Python programming language, all arguments are supplied by reference. It implies
that if we modify the value of an argument within a function, the change is also reflected
in the calling function.
Function Arguments

Function Arguments
The following are the types of arguments that we can use to call a function:
1.Default arguments
2.Keyword arguments
3.Required arguments
4.Variable-length arguments
Default Arguments
A default argument is a kind of parameter that takes as input a default value if no value
is supplied for the argument when the function is called. Default arguments are
demonstrated in the following instance.
Keyword Arguments

The arguments in a function called are connected to keyword arguments.


If we provide keyword arguments while calling a function, the user uses the parameter
label to identify which parameters value it is.
Since the Python interpreter will connect the keywords given to link the values with its
parameters, we can omit some arguments or arrange them out of order.
Required Arguments

The arguments given to a function while calling in a pre-defined positional sequence are
required arguments.
The count of required arguments in the method call must be equal to the count of
arguments provided while defining the function.
We must send two arguments to the function function() in the correct order, or it will
return a syntax error.
Variable-Length Arguments

We can use special characters in Python functions to pass as many arguments as we


want in a function. There are two types of characters that we can use for this purpose:
1.*args -These are Non-Keyword Arguments
2.**kwargs - These are Keyword Arguments.
The Anonymous Functions

These types of Python functions are anonymous since we do not declare them, as we
declare usual functions, using the def keyword. We can use the lambda keyword to
define the short, single output, anonymous functions.
Lambda expressions can accept an unlimited number of arguments; however, they only
return one value as the result of the function. They can't have numerous expressions or
instructions in them. Since lambda needs an expression, an anonymous function cannot
be directly called to print.
Lambda functions contain their unique local domain, meaning they can only reference
variables in their argument list and the global domain name.
Although lambda expressions seem to be a one-line representation of a function, they
are not like inline expressions in C and C++, which pass function stack allocations at
execution for efficiency concerns.
Scope and Lifetime of Variables

The scope of a variable refers to the domain of a program wherever it is declared.


A function's arguments and variables are not accessible outside the defined function. As
a result, they only have a local domain.
The period of a variable's existence in RAM is referred to as its lifetime. Variables within
a function have the same lifespan as the function itself.
When we get out of the function, they are removed. As a result, a function does not
retain a variable's value from earlier executions.
Python Function within Another Function

• Functions are considered first-class objects in Python. In a programming language,


first-class objects are treated the same wherever they are used.
• They can be used in conditional expressions, as arguments, and saved in built-in data
structures. If a programming language handles functions as first-class entities, it is
said to implement first-class functions.
• Python supports the notion of First Class functions.
• Inner or nested function refers to a function defined within another defined function.
Inner functions can access the parameters of the outer scope.
• Inner functions are constructed to cover them from the changes that happen outside
the function.
• Many developers regard this process as encapsulation.
Is Python call by reference or call by value

• Python utilizes a system, which is known as “Call by Object Reference” or “Call by


assignment”.
• In the event that you pass arguments like whole numbers, strings or tuples to a
function, the passing is like call-by-value because you can not change the value of the
immutable objects being passed to the function.
• Whereas passing mutable objects can be considered as call by reference because when
their values are changed inside the function, then it will also be reflected outside the
function.
• In python, each variable to which we assign a value/container is treated as an object.
When we are assigning a value to a variable, we are actually binding a name to an
object.
Default Arguments
Required Arguments
Keyword Arguments
Variable Length Arguments
ASCII: ASCII is an acronym that stands for American Standard Code for Information
Interchange. A specific numerical value is given to different characters and symbols for
computers to store and manipulate in ASCII.
It is case sensitive. The same character, having different formats (upper case and lower
case), has a different value. For example, The ASCII value of "A" is 65 while the ASCII
value of "a" is 97.
Recursion in Python

Recursion is one of an important concept of programming to solve problems.


Every beginner encounters with the recursion even the experience
developers' use recursion. If you are not familiar with recursion, it is function
that is called itself.
The term Recursion can be defined as the process of defining something in
terms of itself. In simple words, it is a process in which a function calls itself
directly or indirectly.
Advantages of using recursion
A complicated function can be split down into smaller sub-problems
utilizing recursion.
Sequence creation is simpler through recursion than utilizing any nested
iteration.
Recursive functions render the code look simple and effective.
Disadvantages of using recursion
A lot of memory and time is taken through recursive calls which makes it
expensive for use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.
• Our recursion ends when the number
reduces to 1. This is called the base
condition.

• Every recursive function must have a


base condition that stops the recursion
or else the function calls itself infinitely.

• The Python interpreter limits the depths


of recursion to help avoid infinite
recursions, resulting in stack overflows.

• By default, the maximum depth of


recursion is 1000. If the limit is crossed,
it results in RecursionError
Use of Recursion in Python

Quite often, people wonder why should we use recursion when loops exist.
Everything can be coded without recursion.
The difference iteration and recursion is there is no sequential end to recursive code.
It tests on a base condition and can go on as long as that is satisfied. Recursion in
python is used when problems can be broken into simpler parts for easier
computation and more readable code.

For example, if you want to search for a student in a school, there would be two
ways to do so.
You could gather all the students in an auditorium and then search for her one by
one.
A more straightforward method would divide the school into sections until the
smallest section could be made to find the student, i.e., it would make more sense to
first search for the grade she is in, then the class, and then you'll be able to find her
location much more easily.
Although recursion is found to give results faster in some cases when properly
optimized, it can also add to memory usage.
Thus, recursion should be used only when needed.
Recursive function in Python has two parts:

(a) Base Case - This helps us to terminate the recursive function. It is a simple
case that can be answered directly and doesn't use recursion. If satisfied, it returns
the final computable answer. If this is omitted, the function will run till infinity.

Python interpreter limits the number of recursive calls for a function to 1000 by
giving a recursion error.

(b) General (Recursive) Case - This case uses recursion and is called unless the
base condition is satisfied.
A recursive function makes use of a call stack.
Every time the recursive function gets called,
that function gets added to the top of this stack.
Imagine opening up an onion and you place
every layer you peel near it.
So, each layer, peeled, would be placed at the
top of this peel stack. Now compare this to a
recursive function. Peeling each layer would be
a recursive function call.
When the first layer is peeled, the first peel()
would be added at the top of the stack, then the
next would be added above it and so on, until
the process is completed.
a) Tail Recursion - A recursive call is said to be tail-recursive
if it is the last statement to be executed inside the
function.
Example of a Tail Recursive Call
The following function prints natural numbers from n in
descending order.
It is done by traversing digits from n to 1 and returning
each digit at a call.
In this example, the position of the print statement holds
utmost significance.
The base case would be 0, where no value would be
returned to the call.
In the first invocation of the function, the print statement
causes 5 to be displayed on the screen and disp(4) is added
at the top of the stack. In the next invocation, 4 is printed
and disp(5) is added to the stack.
Similarly, 3, 2, and 1 are printed in the following
invocations. In the last call, the value of n becomes 0, and
thus the base case is satisfied, causing recursion to
terminate.
Example of a Call That is Not Tail-Recursive

The following function is used to print natural numbers up


to n in ascending order.
Compared to the previous example, the print statement
occurs after the recursive call in this function.
So, the print statements come into play only during the
unwinding phase.
At consecutive invocations of the function, disp(5), disp (4),
disp(3), disp(2), disp (1) are added to the top of the stack,
respectively.
When we encounter disp(0), the terminating condition is
satisfied, returning the function. At this point, the
unwinding phase begins.
The calls return in reverse order, with disp(1) returning
first, followed by the rest.
Thus, the print statement of disp(1) occurs before. So, the
values are printed in ascending order.
When to Use Recursion?
Problem Statement
Is this the Right Way?
Recursion Needs to be Implemented
Needs to have a Base Condition
Suppose that you need to calculate
a sum of a sequence e.g., from 1
to 100.
How to Approach
With Recursion
Without Recursion
Program that recursively prints the pattern: 10 5 0 5 10
Program that recursively prints the pattern: 10 5 0 5 10
Flow Chart
Create a program that takes a given string and returns a new string without any
space or tab (/t) characters. For example, Hello World would become HelloWorld
Create a program that takes a given string and returns a new string without any
space or tab (/t) characters. For example, Hello World would become HelloWorld
How to Approach?
Create a recursive program that takes a given array and returns the same array with
elements in reverse order. For example, 1, 2, 3, 4 would become 4, 3, 2, 1.
Power in Recursion
What is a Matrix in Python?

• A matrix in Python is a rectangular Numpy array.


• This array has to be two-dimensional.
• It contains data stored in the array's rows and columns.
• In a Python matrix, the horizontal series of items are referred to as "rows," while the
vertical series of items are referred to as "columns."
• The rows and columns are stacked over each other just like a nested list. If a matrix
contains r number of rows and c number of columns, where r and c are positive
integers, then r x c determines the order of this matrix object.
• We can store strings, integers, and objects of other data types in a matrix. Data is
stored in the stacks of rows and columns in a matrix.
• The matrix is a crucial data structure for calculations in mathematics and science. In
Python, we consider a list of lists or a nested list as a matrix since Python doesn't
include any built-in type for a matrix object.
numpy.array() in Python

• The homogeneous multidimensional array is the main object of NumPy.


• It is basically a table of elements which are all of the same type and indexed by a
tuple of positive integers. The dimensions are called axis in NumPy.
• The NumPy's array class is known as ndarray or alias array.
• The numpy.array is not the same as the standard Python library class array.array.
• The array.array handles only one-dimensional arrays and provides less functionality.
Parameters
numpy.reshape() in Python

The numpy.reshape() function is available in NumPy package.


As the name suggests, reshape means 'changes in shape’.
The numpy.reshape() function helps us to get a new shape to an array without changing
its data.
Sometimes, we need to reshape the data from wide to long. So in this situation, we have
to reshape the array using reshape() function.
Syntax
1.numpy.reshape(arr, new_shape, order='C')  
Array Objects
The N-dimensional array (ndarray)
To print duplicate element in an array
To print duplicate element in an array
Code:
Print the array elements in reverse order
To Create Matrix
Sum of two Matrix
Code

You might also like