0% found this document useful (0 votes)
446 views192 pages

PST Book - Unit 1 - 5

1. An algorithm is a step-by-step procedure to solve a problem. It must be finite, clear, effective, independent of programming code, and take inputs to produce outputs. 2. The basic building blocks of algorithms are statements, control flow structures like sequence, selection, and iteration, and functions. Pseudo code and flowcharts are common notations used to describe algorithms. 3. Some key algorithm development methods include listing inputs/outputs, describing processing steps, and testing with sample data. Common algorithms were provided for adding numbers, finding averages and largest numbers.
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)
446 views192 pages

PST Book - Unit 1 - 5

1. An algorithm is a step-by-step procedure to solve a problem. It must be finite, clear, effective, independent of programming code, and take inputs to produce outputs. 2. The basic building blocks of algorithms are statements, control flow structures like sequence, selection, and iteration, and functions. Pseudo code and flowcharts are common notations used to describe algorithms. 3. Some key algorithm development methods include listing inputs/outputs, describing processing steps, and testing with sample data. Common algorithms were provided for adding numbers, finding averages and largest numbers.
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/ 192

Unit I 1.

UNIT 1

INTRODUCTION TO COMPTER PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, control flow, functions),


notation (pseudo code, flow chart), algorithmic problem solving for socio economic
conditions in global perspectives, simple strategies for developing algorithms
(iteration, recursion), the efficiency of algorithms.

An algorithm is a step by step procedure of solving a problem. The word


“algorithm” is derived from the name of the 9th century Persian mathematician Al-
Khwarizmi.

An algorithm is defined as a collection of unambiguous instructions which are


executed in a specific sequence to produce an output in a finite amount of time for a
given set of input data.

An algorithm can be written in English or in any standard representation.

An algorithm must possess the following properties

1. Finiteness: An algorithm must be executed finite number of times.

2. Definiteness: Each step of the algorithm must be accurate and clear.

3. Effectiveness: Each step must be effective, in the sense that it should be


primitive (easily convertible into a program statement) and can be performed
exactly in a finite amount of time.

4. Independent: The algorithm must be independent of any programming code.

5. Input/output: Each algorithm must take zero or more quantities as input data
and give out one or more output values.
1.2 Introduction to Computer Problem Solving

Methods for Developing an Algorithm

• List the data needed to solve the problem (input) and know what is the end result
(output).

• Describe the various step to process the input to get the desired output. Break down
the complex processes into simpler statements.

• Finally test the algorithm with different data sets.

Example: Algorithm for Addition of two numbers:

Step1: Start

Step 2: Get two numbers a and b as input

Step 3: Add the numbers a & b and store the result in c

Step 4: Print c

Step 5: Stop.

The above algorithm is to add two numbers a and b. The numbers are the input
provided by the user .After adding the result is stored in a variable c and it is printed.

Building Blocks of Algorithm: The basic building blocks of an algorithm are


Statements, Control flow and Functions.

Statements: Statement may be a single action in a computer.

In a computer statements might include some of the following actions

• input data-information given to the program


• process data-perform operation on a given input
• output data-processed result

Control flow: The process of executing the statements in the given sequence is
called as control flow.
Unit I 1.3

The three ways in executing the control flow are

• Sequence
• Selection
• Iteration
Sequence

The given set of instructions executed consecutively is called sequence execution.

Example: Algorithm to find the average of three numbers, the algorithm is as follows

Step 1: Start

Step 2: Get three numbers a, b, c as input

Step 3: Find the sum of a, b and c

Step 4: Divide the sum by 3

Step 5: Store the result in variable d

Step 6: Print d

Step 7: Stop

The above algorithm is to find the average of three numbers a, b and c.The numbers are
the input provided by the user .After adding the total is divided by 3 and the result is
stored in a variable d and it is printed.

Selection

A selection statement is transferring the program control to a specific part of the program
based upon the condition.

If the condition is true, one part of the program will be executed, otherwise the other part
of the program will be executed.

Example: Algorithm to find the Largest of two numbers, the algorithm is as follows
1.4 Introduction to Computer Problem Solving

Step1: Start

Step 2: Get two numbers a and b as input

Step 3: IF a>b THEN

Step 4: PRINT “A is Large”

Step 5: ELSE PRINT “B is Large”

Step 6: ENDIF

Step 7: Stop

The above algorithm is to find the Largest of two numbers a and b.The numbers are the
input provided by the user .The number a and b are compared, If a is larger Print “A is
Large” or if b is larger print “B is Large”.

Iteration

Iteration is a type of execution where a certain set of statements are executed again
and again based upon condition. This type of execution is also called as looping or
repetition.

Example: Algorithm to print all natural numbers up to n, the algorithm is as follows

Step 1: Start

Step 2: Get the value of n.

Step 3: Initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 7

Step 5: Print i value and increment i value by 1

Step 6: Go to step 4

Step 7: Stop

The above algorithm is to print all natural numbers up to n .The user provides the
input. The first value, i is initialized. A loop is initialized. The first value is printed and
Unit I 1.5

the number is incremented. The i value is checked with n,the user input. The numbers are
printed until the value is less than the user input value.

Functions

Function is a sub program which consists of block of instructions that performs a


particular task. For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.

Benefits of Using Functions

• Reduction in line of code


• code reuse
• Better readability
• Information hiding
• Easy to debug and test
• Improved maintainability

Example: Algorithm for addition of two numbers using function Main function ()

Step 1: Start
Step 2: Call the function add ()
Step 3: Stop

The above algorithm is to call the function add. This function is called as Main function
or calling function.

Sub function add ()

Step 1: Function start


Step 2: Get two numbers as input and store it in to a and b
Step 3: Add the numbers a & b and store the result in c
Step 4: Print c
Step 5: Return.
1.6 Introduction to Computer Problem Solving

The above algorithm is called as the called function which is to add two numbers a and
b.The numbers are the input provided by the user .After adding the result is stored in a
variable c and it is printed.

NOTATIONS

Pseudo Code

Pseudo –False.

Code- Set of Instructions.

Pseudo code means a short, readable set of instructions written in English to explain an
algorithm.

Rules for writing Pseudo code

• Write one statement per line


• Capitalize keywords.
• Indent to hierarchy.
• Keep statements language independent.
Common keywords used in writing a Pseudo code

Comment: //
Start: BEGIN
Stop: END
Input: INPUT, GET, READ
Calculate: COMPUTE, CALCULATE, ADD, SUBTRACT, INITIALIZE
Output: OUTPUT, PRINT, DISPLAY
Selection: IF, ELSE, ENDIF
Iteration: WHILE, ENDWHILE, FOR, ENDFOR

Example: Pseudo code to Add two numbers


BEGIN
GET a, b
Unit I 1.7

ADD c=a+b
PRINT c
END

Advantages:

• Pseudo code is program independent.


• It is easily understandable by layman.
• There is no Standard syntax.
• Pseudo code cannot be compiled or executed.
• It is easy to translate pseudo code into a programming language.
• It can be easily modified as compared to flowchart.

Disadvantages:

• It is not visual.
• We do not get a picture of the design.
• There is no standardized style or format.
• For a beginner, it is more difficult to follow the logic or write pseudo code as
compared to flowchart.

Flow Chart

Flow chart is defined as the graphical or diagrammatical representation of the process of


solving a problem. It represents the steps of a process in a sequential order.

Rules:

• The flowchart should be clear, neat and easy to follow.


• The flowchart must have a logical start and finish.
• Only one flow line should come out from a process symbol
• Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol
• Only one flow line is used with a terminal symbol.
1.8 Introduction to Computer Problem Solving

• Within standard symbols, write briefly and precisely.


• Intersection of flow lines should be avoided.

Fig 1.1 Symbols used in Flow chart

Advantages:

• Flowcharts help in communicating the logic of a program in a better way.


• The problems can be analyzed effectively with the help of flowchart.
• Flowcharts serve as good program documentation.
• The flowchart is a blue print for the programmer to code efficiently.
• Flowcharts help in debugging process.
Unit I 1.9

Disadvantages:

• The flowcharts are complex and clumsy when the program is large or complicated.
• Altering or modifying the flowcharts may require re-drawing completely.
• The cost and time taken to draw a flowchart for larger applications are expensive.

Example: Add two numbers

Fig 1.2 Flowchart for adding two numbers

The above flowchart is to add two numbers Number1 and Number2.The numbers are the
input provided by the user .After adding the result is stored in a variable Sum and it is
printed.

Example: Print odd numbers from 1 to 100


1.10 Introduction to Computer Problem Solving

Fig 1.3 Flowchart to Print odd numbers from 1 to 100

The above flowchart is to print all odd numbers up to 100. The first value, i is initialized
as zero. A loop is initialized. The modulo of first value is calculated if the result is not
equal to zero then the number is printed and the number is incremented. The i value is
checked with the limit, 100. The numbers are printed until the value is less than the input
value.

Example: Find the largest of two numbers

Fig 1.4 Flowchart to find the largest of two numbers


Unit I 1.11

The above flowchart is to find the Largest of two numbers NO1 and NO2.The numbers
are the input provided by the user .The number NO1 and NO2 are compared, If NO1 is
larger, the number NO1 is printed or if NO2 is larger, the number NO2 is printed

Example: Add two numbers using Function

Fig 1.5a Flowchart of a calling function

Fig 1.5b Flowchart of a Sub function to add two numbers


1.12 Introduction to Computer Problem Solving

The flowchart 1.5a is to call the function add. This function is called as Main
function or calling function. The flowchart1.5b is called as the called function which is
to add two numbers a and b.The numbers are the input provided by the user .After
adding the result is stored in a variable c and it is printed.

Types of Flowcharts

• Process Flowchart
• Data Flowchart
• Business Process Modeling Diagram

Difference between Algorithm, Flowchart and Pseudo code

Algorithm Flowchart Pseudo code


An algorithm is a step by It is a graphical It is a language representation
step procedure to solve a representation of algorithm of algorithm.
problem.
User needs knowledge to User does not need User does not need knowledge
write algorithm. knowledge of program to of program language to
draw or understand understand or write a pseudo
flowchart code.

Algorithmic Problem Solving For Socio Economic Conditions in Global


Perspectives: People today have to strive hard to maintain

Providing Food for Everybody

Step 1: Start
Step 2: Estimation of people below poverty line.
Step 3: Recommendation about the type and quantity of food from the food committee
Step 4: Decide the cost
Step 5: Generation of Revenue to meet the food demand
Step 6: Provide food through public distribution system at all levels.
Step 7: Get Feedback from beneficiaries as well as public
Step 8: Go to step 2
Step 9: Stop
Unit I 1.13

Process A Process B

Process C

Process D Process E

Process F

Process G

Fig 1.6 Flowchart for providing food for Everybody

Process A: The number of people below poverty line in each village is estimated
and the total of people in each district is calculated.

Process B: The food committee will recommend the type of food to be provided
and also the quantity of food.

Process C: From the above inputs, the overall cost is calculated.

Process D: The Finance committee decides how to generate the revenue needed.

Process E: Revenue is generated by implementing Tax, Educational Cess, Import /


Export duties etc.

Process F: The distribution of food is carried out through public distribution


system.

Process G: Feedback is provided by the public and beneficiaries which again is an


input to the process to improve the quality of the food provision
1.14 Introduction to Computer Problem Solving

Simple Strategies for Developing Algorithms (Iteration, Recursion)

Iterations:

A sequence of statements is executed until a specified condition is true is called


iterations.

1. For loop

2. While loop

Example: Print n Natural numbers using FOR Loop

Algorithm Pseudo code


Step 1: Start BEGIN
Step 2: Get the value of n. GET n
Step 3: Initialize i=1 INITIALIZE i=1
Step 4: if (i<=n) go to step 5 else go to step 7 FOR (i<=n) DO
Step 5: Print i value and increment i value by 1 PRINT i
Step 6: Go to step 4 i=i+1
Step 7: Stop ENDFOR
END

Example: Print n Natural numbers using WHILE Loop

Algorithm Pseudo code


Step 1: Start BEGIN
Step 2: Get the value of n. GET n
Step 3: Initialize i=1 INITIALIZE i=1
Step 4: if (i<=n) go to step 5 else go to step 7 WHILE(i<=n) DO
Step 5: Print i value and increment i value by 1 PRINT i
Step 6: Go to step 4 i=i+1
Step 7: Stop ENDWHILE
END
Unit I 1.15

Fig 1.8 Flowchart to print n Natural numbers using WHILE Loop

The above flowchart is to print all natural numbers up to n .The user provides the
input value n. The first value, i is initialized as one. A loop is initialized. The i value is
checked with n, the user input. The numbers are printed until the value is less than the
user input value. When the condition becomes false the loop terminates.

Recursions:

A function that calls itself is known as recursion.

Recursion is a process by which a function calls itself repeatedly until some specified
condition has been satisfied.

Example: Factorial
1.16 Introduction to Computer Problem Solving

Algorithm Pseudo code


Main Function() Main Function()
Step1: Start BEGIN
Step2: Get n GET n
Step3: call factorial(n) CALL factorial(n)
Step4: print fact PRINT fact
Step5: Stop END
Sub function factorial(n) Sub function factorial(n)
Step1: if(n==1) then fact=1 return fact IF(n==1) THEN
Step2: else fact=n*factorial(n-1) and return fact fact=1 RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

Fig 1.9 a) Flowchart of a calling function b) Flowchart of a Sub function to find


factorial of a given number

The flowchart 1.9a is to call the function factorial. This function is called as Main
function or calling function. The flowchart1.5b is called as the called function which is
to find the factorial of the number passed from the main function. The loop exists until
Unit I 1.17

the n value becomes one. Factorial is a recursive function where the function itself is
called again and again.

Difference between Iteration and Recursion

Property Iteration Recursion


A set of instructions repeatedly
Definition executed. Function calls itself.
Application For loops. For functions.
When the termination condition for Through base case, where there
Termination the iterator ceases to be satisfied. will be no function call.
Used when time complexity needs Used when code size needs to be
to be balanced against an expanded small, and time complexity is
Usage code size. not an issue.
Code Size Larger Code Size. Smaller code size

Time Complexity Relatively lower time complexity Very high time complexity.

Efficiency of Algorithms: Analysis of an Algorithm

The following are some of the factors which helps in an analyzing an algorithm

• Efficiency
• Simplicity
• Generality
• Range of Growth
• Computing order of growth

The most important factor of all these is efficiency.

Efficiency or Performance Analysis

1. Amount of time required to execute an algorithm(Time Complexity)

2. Amount of storage required by an algorithm(Space Complexity)


1.18 Introduction to Computer Problem Solving

Time Complexity

• Time complexity of an algorithm is the total time required by the algorithm to run.
• To compute time we require two components – Variable part and fixed part.
• Variable Part - Run time
• Fixed Part - Compile time
Time complexity can be represented as a numerical function T(n), where T(n) can be
measured as the number of steps, provided each step consumes constant time.

Calculation of Time Complexity

We use step count method to calculate the time complexity of an algorithm.

For example
int sum(int a[],int n)
{
Int sum=0
For (int i=0;i<n;i++)
{
Sum=sum+a[i]
}
Return sum
}

Instruction Step count


int sum(int a[],int n) 0
{ 0
Int sum=0 1
For (int i=0;i<n;i++) n+1
{
Sum=sum+a[i] N
} 0
Return sum 1
} 0
Total steps=1+n+1+n+1=2n+3
Unit I 1.19

Space Complexity: Space complexity of an algorithm is the amount of memory space


required by the algorithm to run.

Reason for estimating space before running the program

• To know if the memory is sufficient

• The program must be of lesser size in a multiuser system ,since there will be
multiple copies of the same program

To compute the space we require two components – Variable space and fixed
space.

Space complexity S(P) = C + SP,

Where C is a Constant, that is the fixed space and it denotes the amount of space
taken by instructions, simple variables, constants and identifiers.

And SP is the variable space is a space dependent upon instance characteristics.

Space complexity can also be represented as the sum of instruction space, Data
space and Environment stack space.

Instruction space: The memory space required for storing the compiled
instructions. It depends on the Compiler used, compiler options and the target computer

Data space: The amount of memory space used by Constants, variables, arrays,
structures and other data structures.

Environment stack space: When we use a function, we will require a stack to


store the return address of the main function (Calling function). This space is the
environment stack space.

Calculation of Space complexity

Type Size
bool, char, unsigned char, signed char, int8 1 byte
int16, short, unsigned short 2 bytes
float, int32, int, unsigned int, long, unsigned long 4 bytes
double, int64, long double 8 bytes
1.20 Introduction to Computer Problem Solving

Examples:

int c= a+b

return c

In the above example, variables a, b, and c are all integer types, so they will take up 4
bytes each, so total memory requirement will be (4(3) + 4) = 20 bytes, the additional 4
bytes is for return value. Since this space requirement is fixed for the above example, it
is called Constant Space Complexity.

int sum(int a[],int n)

Int sum=0

For (int i=0;i<n;i++)

Sum=sum+a[i]

Return sum

• In the above example, 4*n bytes of space is required for the array a[] elements.

• 4 bytes each for sum, n, i and the return value.

Hence the total memory requirement will be (4n + 12), which is increasing linearly with
the increase in the input value n, hence it is called as Linear Space Complexity.

Case Studies

• Networked Healthcare
• Clean Water for All
• Generating Energy at Low Costs
• Smart Cities
Unit II 2.1

UNIT II

DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode; values and types: int, float, boolean, string,
and list; variables, expressions, statements, tuple assignment, precedence of
operators, comments; modules and functions, function definition and use, flow of
execution, parameters and arguments; Algorithms: exchange the values of two
variables, circulate the values of n variables, distance between two points.

Python interpreter and interactive mode; values and types: int, float,
boolean, string, and list; variables, expressions, statements, tuple assignment,
precedence of operators, comments; Modules and functions, function definition and
use, flow of execution, parameters and arguments.

Algorithms: exchange the values of two variables, circulate the values of n


variables, distance between two points.

2.1 PYTHON INTERPRETER

Interpreter: Executes a program written in a high-level language by translating


it one line at a time.

Compiler: Translate a program written in a high-level language into a low-level


language entire program at a time.

Compiler Interpreter

Entire program is taken as input Single instruction is taken as input

Compiler generates Intermediate Object Interpreter does not generate Intermediate


Code. Object Code.

Conditional Control Statements are executed Conditional Control Statements are


faster. Executed slowly.
2.2 Data Expressions, Statements

Compiler Interpreter

It occupies more Memory since Object Code It occupies less memory.


is Generated.

No need to compile the program every time. Need to convert higher level program into
lower level program every time.

Errors are displayed after checking the It displays the error for every instruction
entire program is checked interpreted (if any)

Example : C Compiler Example : PYTHON

2.1.1 Modes of Python Interpreter

Basically, there are two modes in Python Interpreter they are

1. Interactive mode

2. Script mode

2.1.1.1 Interactive mode

 In the Interactive Mode, as the name suggests it allows us to interact with OS.
 Interpreter displays the result(s) immediatelywhen the Python statement(s) are
typed.

Advantages:

 In interactive mode it is good enough to learn experiment or explore.


 It is convenient for beginners to work and for testing smallpieces of code.
Drawback:
 The statements cannot be saved and when we want to re-run once again we have
to retype all the statements .
 In interactive mode, the interpreter displays the result as:
>>> 2 + 5
>>> 7
Unit II 2.3

The chevron, >>>, is the prompt indicated by the interpreter that it is ready to
enter your code. If you type 2 + 3, the interpreter replies 5.

>>> print (“Sathyabama Welcomes You “) >>>Sathyabama Welcomes You

This is an example of a print statement. It displays a result on the screen. In this case, the
result is the words.

2.1.1.2 Script mode

 In script mode, python program is typed in a file and then the content of the file is
executed with the help of interpreter.
 Scripts are saved to disk with the extension .pyfor future use.
 Save the code with sample .pyand run the interpreter in script mode to execute
the script.

Interactive mode Script Mode


A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt .
The code Can’t be saved and edited. The Code can be saved and edited.
If we want to test with the piece of code, If the codes are clear , we can use script
then we can use interactive mode. mode.
The statements cannot be saved for further The statements can be saved for further use
use and we have to retype all the and we no need to retype all the statements
statements to re-run them. to re-run them.
2.4 Data Expressions, Statements

2.2 VALUES AND TYPES

2.2.1 Value

Value consist be any letter, number or string.

Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data
types)

2.2.2 Types

Every value in Python has a data type.

It is a set of values, and the allowable operations on those values.

Data Types

Numbers Boolean Sequences Set Dictionaries

Integer Float Complex Strings List Tuple

2.2.2.1 Numbers

 Numerical Values are stored in Number data type.


 This data type belongs to immutable type [i.e. values/items cannot be changed].
 It supports integers, floating point numbers and complex numbers. They are
defined as
Unit II 2.5

Integers Long Float Complex


They are represented
They are called as
in the form of a+bi,
integers or int which They are called as long They consists of a
where a represents
can be either a integers they can be decimal point
the real part of a
positive or negative represented in the form separating a integer
complex number and
number without of octal or hexadecimal and fractional parts
b represents the
decimal value
imaginary part
Eg.211071 Eg.2110715667L Eg.2110.71 Eg.Square root of -1

2.2.2.2 Boolean

 Objects of Boolean type may have one of two values, True or False
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

2.2.2.3 Sequence

 A sequence is a collection of ordered items, indexed by positive integers.


 It is a combination of both mutable(value can be changed) and immutable(values
cannot be changed) data types.

There are three types of sequence data type available in Python, they are

1. Strings
2. Lists
3. Tuples

 A String in Python consists of a series or sequence of characters - letters,


numbers, and special characters.
 Strings are marked by quotes
 single quotes (' ') Eg, ‘Sathyabama Welcomes You’
2.6 Data Expressions, Statements

 double quotes (" ") Eg, “Sathyabama Welcomes You“


 triple quotes(""" """) Eg, """'Sathyabama Welcomes You """
 Subscript (index) is used to access individual character in a string.
 Characters can be accessed using indexing and slicing operations.
 Strings are immutable i.e. the contents of the string cannot be changed
after it is created.
Indexing

String A W E L C O M E
Positive Index 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1

 Positive indexing is used to access the string from the beginning.


 Negative subscript is used to access the string from the end.
 Subscript 0 or –ven(where n is length of the string) displays the first element.
 Example: A[0] or A[-7] will display “W”
 Subscript 1 or –ve (n-1) displays the second element.
Operations on Strings

i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship

Operations Example Description


Creating a String >>> s=”Sathyabama Creating a String with list of
Welcome You” characters
Indexing >>> print(s[2]) Printing the element at position 2
t
>>>print(s[6]) Printing the element at position 6
b
Unit II 2.7

Operations Example Description


Slicing (Ending >>> print(s[3: ]) Displays the items from position 3 till
position -1) hyabama Welcomes You last.

Slice operator used >>> print(s[:10]) Slice from start and extracts five
to extract part of a Sathyabama characters.
data type

Concatenation >>>print(s+”All”) Used to concatenate two strings


Sathyabama Welcomes You
All

Repetition >>>print(s*2) Repeats the no. of times the same


Sathyabama Welcomes string.
YouSathyabama Welcomes
You

Membership >>> s=”Sathyabama Used to check whether particular


Operator (in, not in) Welcomes You” character is present in the defined
>>>”a” in s string. Returns true if present else
returns false.
True
>>>”A” not in s
True
Lists

 It is an ordered sequence of items. Values in the list are called elements /items.
 It can be written as a list of comma-separated items (values) between
squarebrackets [ ].
 Items in the lists can be of different data types.
2.8 Data Expressions, Statements

Operations Example Description


Creating a list >>> Creating a list with
list1=[“Python”,7.34,150,”Programming” different data types
]
>>>list2=[“Language”,6.75,9]
Indexing >>> print(list1[2]) Printing the element
150 present at position 2 in
>>>print(list2[2]) list1
9 Printing the element
present at position 2 in
list2
Slicing (Ending >>> print(list1[1:3]) Displays the items from
position -1) [7.34,150] position 1 till 2nd
Slice operator >>> print(list1[1:]) Displays the items from
used to extract [7.34,150,”Programming”] position 1 till last item.
part of a data type
Concatenation >>>print(list1+list2) Used to concatenate items
[“Python”,7.34,150,”Programming”,“Lan from two lists
guage,6.75,9]
Updating the list >>>list2[2]=45 Updating the list item to
>>>print(list2) the specified index value
[“Language”,6.75,45]
Inserting an >>>list2.insert(1,”Interesting”) Inserts an element in the
element in the list >>>print(list2) specified index
[“Programming”,”Interesting”,6.75,45]
Deleting an >>>list2.remove(6.75) Removes the specified
element >>>print(list2) element directly
[“Programming”,”Interesting”,45]

2.2.2.4 Tuple

 A tuple is same as list, the set of elements is enclosed inparenthesesinstead of


square brackets.
 It is an immutable list.i.e. once a tuple has been created, you can't addelements to
a tuple or remove elements from the tuple.
Unit II 2.9

Benefits of Tuple:

 Tuples are faster than lists.


 Tuple are preferred when the data should be prevented from changes.
 It can be used as keys in dictionaries, while lists can't.
Operations Example Description
Creating a >>> t=(“Python”,7.34,150,”hello”) Creating a tuple
tuple with different
data types
Indexing >>> print(t[2]) Printing the
150 element present
at position 2
>>>print(t[0])
Printing the
Python element present
at position 0
Slicing >>> print(t[1:3]) Displays the
(Ending (7.34,150) items from
position -1) position 1 till
2nd
Concatenation >>>print(t+”ram”) Adds items to
(“Python”,7.34,150,”hello”,”ram”) the end of the
tuple

Repetition >>>print(t*2) Repeats the no.


(“Python”,7.34,150,”hello”,“Python”,7.34,150,”hello”) of times the
same tuple

2.3 VARIABLES

 A variable is named memory location allows us to store a value, which can be


used later.
 Variable names should be meaningful. It can be of any length.
 It does not support blank space between variable names.
 In Python variables need not be declared explicitly, like other languages
depending on the values assigned the variable is created.
2.10 Data Expressions, Statements

2.3.1 Assigning value to a variable

Value should be given on the right side of assignment operator(=) and variable on left
side.

>>>counter=45

print(counter)

45

Assigning a single value to several variables simultaneously:

>>>bag=pencil=pen=100

>>>print(bag)

100

>>>print(pen)

100

Assigning multiple values to multiple variables:

>>>a,b,c=4,6,”ram”

>>>print(b)

>>>print(c)

ram

2.4 EXPRESSIONS

 Combination of values, variables, and operators are known as expressions.


Example for expressions
Unit II 2.11

>>>55

55

>>>a=7

>>>b=8

>>>a+b+5

20

>>>z=(“hello”+”friend”)

print(z)

hellofriend

2.5 STATEMENTS

-Instructions that a Python interpreter can execute are called statements.

-A statement is a unit of code like creating a variable or displaying a value.

>>> n = 17

>>>print(n)

Here, The first line is an assignment statement that gives a value to n. The second line is
a print statement that displays the value of n.

2.6 TUPLE ASSIGNMENT

 A single assignment statement can be used to assign all the elements in a tuple.
 Python has a very powerful tuple assignmentfeature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
right of the assignment.
 The left side indicates tuple variables; the right side indicates tuple values.
 Each value is assigned to its respective variable.
2.12 Data Expressions, Statements

 Before assigning all the expressions on the right side are evaluated. This makes
tuple assignment quite versatile.
 The number of variables on the left and the number of values on the right should
be equal.

>>>(a,b,c,d)=(4,5,6)

ValueError: need more than 3 values to


unpack

Example

With conventional assignment statements we can swap the values of two


variables using a temporary variable. For example, to swap a and b: swap.py when u run
the program the output is shown below

a=5;b=4 Output

print(“Before Swapping”
Before Swapping
print(a,b)
54
temp=a

a=b

Tuple assignment solves this problem neatly:

(a,b)=(b,a)

One way to think of tuple assignment is as tuple packing/unpacking.

In tuple packing, the values on the left are ‘packed’ together in a tuple:
Unit II 2.13

>>>b=(“ram”,25,”30000”) #tuple packing

In tuple unpacking, the values in a tuple on the right are ‘un packed’ into the
variables/names on the right:

>>>b=(“ram”,25,”30000”) #tuple packing

>>>(name,age,salary) = b #tuple unpacking

>>>name

ram

>>>age

25

>>>salary

‘30000’

The right side can be any kind of sequence (string, list, tuple)

Example:

-To split an email address in to user name and a domain

>>>mailid=’[email protected]

>>>name,domain=mailid.split(‘@’)

>>>print(name)

ram

>>>print(domain)

abc.org
2.14 Data Expressions, Statements

2.7 PRECEDENCE OF OPERATORS

 Operators are the constructs which can manipulate the value of operands.
 Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
2.7.1 Types of Operators

-Python language supports the following types of operators

• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operator
• Logical Operator
• Bitwise Operator
• Membership Operator
• Identity Operators

When an expression contains more than one operator, the order of evaluation depends on
the order of operations.

Operator Description
** Exponentiation ( raise to the power)
~+- Complementary , unary minus and plus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>><< Right and left bitwise shift
& Bitwise ‘AND’
^| Bitwise exclusive ‘OR’ and regular ‘OR’
<= <>>= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
isis not Identity operators
in not in Membership operators
not or and Logical operators
Unit II 2.15

- For mathematical operators, Python follows mathematical convention.

- PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,


Subtraction)is the acronym which helps to remember the rules:

 Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (5-1) is 8, and (2+1)**(5-2) is 27.
 Parentheses make an expression easier to read, as in (minute * 100) / 60, doesn’t
change the result but it is easier to read.
 Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and
2*3**2 is 18, not 36.
 Multiplication and Division have higher precedence than Addition and
Subtraction. So 3*3-1 is 8, not 6, and 8+4/2 is 10, not 6.
 When the operators have same precedence it is evaluated from left to right
(except exponentiation).

Example :

a=7-12/3+3*2-1 a=2*4+4%5-3/2+6
a=? a=2*4+4%5-3/2+6
a=7-12/3+3*2-1 a=8+4%5-3/2+6
a= 7-4+3*2-1 a=8+4-3/2+6
a=7-4+6-1 a=8+4-1+6
a=3+6-1 a=12-1+6
a=9-1 a=11+6
a=8 a=17
Given a=2,b=12,c=1 evaluate a=2,b=12,c=1
d=a<b>c(Substitute the values for a,b,c) d=a<b>c-1
d=2<12>1(returns 1 since 2 is less than 12 ) d=2<12>1-1
d=1>1(returns 0 since 1 is not greater than 1 ) d=2<12>0
d=1>1 d=1>0
d=0 d=1
2.16 Data Expressions, Statements

2.8 COMMENTS

 A comment line begins with a hash sign (#).


 Interpreter ignores anything written after # symbol.
Example:

percentage = (minute * 100) / 60 # calculating percentage of an hour

Multiple-line cannot be commented in Python , every line has to be comment


individually as follows :

Example:

# This is a comment.
# This is also a commentline .
# Every line has to be commented individually.

2.9 MODULES AND FUNCTIONS

 A module is a file which consists of Python definitions, functions, statements and


instructions.
 A standard library of Python is extended as modules.
 In order to use these modules in a program, programmer needs to import the
module.
 Once the module is imported, it can be referred or used by functions or variables
in our code.
 Python supports large number of standard modules.
 Standard modules can be imported similar as we import our user-defined
modules.
 Every module contains many functions.
 The syntax for accessing the function sis given below which is referred as
dot notation.
Unit II 2.17

Syntax:

importmodule_name

module_name.function_name(variable)

There are four ways to import a module in a program

i. import
ii. from import
iii. import with renaming
iv. import all

import - Most commonly used way to From import – It is used to import the
import the resource directly resource from another package or module
Example: Example:
import math from math import pi
x=math.pi x=pi
print(“The value of pi is”,x) print(“The value of pi is”,x)
Output: Output:
The value of pi is 3.141592653589793 The value of pi is 3.141592653589793

import with renaming – We can import a import all – We can import all definitions
module by renaming for our convenience from a module using *
Example: Example:
import math as m from math import *
x=m.pi x=pi
print(“The value of pi is”,x) print(“The value of pi is”,x)
Output: Output:
The value of pi is 3.141592653589793 The value of pi is 3.141592653589793
2.18 Data Expressions, Statements

Built-in Modules are,

1.math

2.random

math – mathematical functions:

Function Description

math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal to x

math.floor(x) Return the floor of x, the largest integer less than or equal to x.

math.factorial(x) Return x factorial.

math.gcd(x,y) Return the greatest common divisor of the integers a and b

math.sqrt(x) Return the square root of x

math.log(x) Return the natural logarithm of x

math.log10(x) returns the base-10 logarithms

math.log2(x) Return the base-2 logarithm of x.

math.sin(x) returns sin of x radians

math.cos(x) returns cosine of x radians

math.tan(x) returns tangent of x radians

math.pi Returns the mathematical constant π = 3.141592

math.e Returns the mathematical constant e = 2.718281


Unit II 2.19

Example:

import math
print('The Floor and Ceiling value of 23.56 are: ' + str(math.ceil(23.56)) + ', ' +
str(math.floor(23.56)))
print('Absolute value of -96 and 56 are: ' + str(math.fabs(-96)) + ', ' + str(math.fabs(56)))
print('Factorial of 4 is : ' + str(math.factorial(4))
print('The GCD of 24 and 56 : ' + str(math.gcd(24, 56)))
print('The value of 5^8: ' + str(math.pow(5, 8)))
print('Square root of 400: ' + str(math.sqrt(400)))
print('The value of 5^e: ' + str(math.exp(5)))
print('The value of Log(625), base 5: ' + str(math.log(625, 5)))
print('The value of Log(1024), base 2: ' + str(math.log2(1024)))
print('The value of Log(1024), base 10: ' + str(math.log10(1024)))
print('The value of Sin(60 degree): ' + str(math.sin(math.radians(60))))
print('The value of cos(pi): ' + str(math.cos(math.pi)))
print('The value of tan(90 degree): ' + str(math.tan(math.pi/2)))
print('The angle of sin(0.8660254037844386): ' +
str(math.degrees(math.asin(0.8660254037844386))))

Output:
The Floor and Ceiling value of 23.56 are: 24, 23
Absolute value of -96 and 56 are: 96.0, 56.0
Factorial of 4 is 24
The GCD of 24 and 56 : 8
The value of 5^8: 390625.0
Square root of 400: 20.0
The value of 5^e: 148.4131591025766
The value of Log(625), base 5: 4.0
The value of Log(1024), base 2: 10.0
The value of Log(1024), base 10: 3.010299956639812
The value of Sin(60 degree): 0.8660254037844386
The value of cos(pi): -1.0
The value of tan(90 degree): 1.633123935319537e+16
The angle of sin(0.8660254037844386): 59.99999999999999
2.20 Data Expressions, Statements

random-Generate pseudo-random numbers

Function Description
random.randrange() To print a random number in a given range.
random.randrange(start, stop[, step]) To generate a random integer number within a
given range.
random.uniform(start, end) To generate a floating point number within a
given range.

Example:

import random
print("Generate random integer number within a given range in Python ")
#random.randrange() with only one argument
print("Random number between 0 and 10 : ", random.randrange(10))
print("Generate random integer number within a given range")
print(random.randrange(10, 50, 5))
print(random.randrange(10, 50, 5))
print("floating point within given range")
print(random.uniform(10.5, 25.5))
Output:

Generate random integer number within a given range in Python


Random number between 0 and 10 : 7
Generate random integer number within a given range
20
35
floating point within given range
16.76682097326141

2.9.1 Function

Function is a sub program which consists of set of commands used to


perform a selected task. A larger program is split into small blocks known as function.
Unit II 2.21

Advantages of Using Function

 When the program is too complex to solve and coding is lengthy they are divided
into small parts. Each part is separately coded and combined into single program.
Each subprogram is called as function.
 When the program is divided into subprograms it is easier to Debug, Test and
maintain.
 Function provides code re-usability; it avoids rewriting same code again and
again in a program.
 It reduces the program length.

2.9.1.1 Type of functions

Functions can be classified into two categories:

i) user defined function


ii) Built in function

i) Built in functions

 Built in functions are already created and stored in python.


 It cannot be changed by the programmer but can be accessed by the programmer.

ii) User defined functions

 The functions that programmers create according to their requirement and need
are called user defined functions.
 User defined functions can be combined to form module; it can be used in other
programs by importing them.

Advantages of user defined functions

 Time saving because large project can be split into small functions according to
their functionalities and can be coded parallel.
 Code re-usability - If repeated code occurs in a program, function can be used to
include those codes and execute when needed by calling that function.
2.22 Data Expressions, Statements

Built in Function Description Example Output


max(int,int) Returns largest element >>>max(2,4) 4
min(int,int) Returns smallest >>>min(3,5) 3
element
len(String) Returns the length of >>>len(“Welcome”) 7
an object
range(start,end,step) Returns range of given >>>range(3,8,1) [3,4,5,6,7]
values
round(float) Returns rounded >>>round(6.7) 7.0
integer of the given >>>round(6.4) 6.0
number
pow(a,b) Returns the power of >>>pow(2,3) 8
given number
type(object) Returns the data type >>>type(6.5) <type ‘float’>
of the object to which
it belongs
variable=tuple([list]) To create tuple of >>>t=tuple([4,6.0,7]) (4, 6.0, 7)
items from list
print(object) displays the given >>>print("good good morning
object morning")
input(String) reads and returns the >>>input("Enter name:") Enter name :
given string Ram

Function definition: (Sub program)

Syntax :

deffun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2

statement n
return[expression]

def – Keyword used to define user defined function

fun_name – Name given to a function which should be meaningful


Unit II 2.23

Parameter1,Parameter2 …. Parameter n – arguments inside parenthesis ends with colon


(:)

Add the program statements inside the function to be executed

End with optional return statement

Example :

defmy_add(a,b):

c=a+b

return c

Function Calling: (Main Function)

 Once a function is defined, we can call it from another function, program or even
the Python prompt.
 To call a function type the function name with appropriate arguments.
Example:

x=5 y=4 my_add(x,y)

FLOW OF EXECUTION

 It is the order in which statements are executed.


 Always the execution begins at the first statement of the program.
 Statements are executed in order, from top to bottom one at a time.
 Function definitions do not alter the flow of execution of the program, but
statements inside the function are not executed until the function is called.
 Function calls are like a bypass in the flow of execution. Instead of going to the
next statement, the flow jumps to the first line of the called function, executes all
the statements there, and then comes back to pick up where it left off.
Function Prototypes

i. Function without arguments and without return type


2.24 Data Expressions, Statements

ii. Function with arguments and without return type


iii. Function without arguments and with return type
iv. Function with arguments and with return type

Function without arguments and without return type

 In this type no argument is passed in the function call and no output is returned to
the main function
 The sub function will read the input values perform the operation and print the
result in the same block
Example :

def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()

Output :

entera7
enterb14
21

Function with arguments and without return type

 Arguments are passed in the function call no output is returned to the main
function the output is printed in the sub function itself
Unit II 2.25

Example :

def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)

Output :

entera7
enterb14
21

Function without arguments and with return type

 In this type no argument is passed in the function call but output is returned to the
main function
Example :

def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)
2.26 Data Expressions, Statements

Output :

entera5
enterb14
19

Function with arguments and with return type

 In this type arguments are passed in the function call and output is returned to the
main function
Example :

def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)

Output :

entera5
enterb14
19

PARAMETERS AND ARGUMENTS

Parameters

 Parameters are the value(s) provided in the parenthesis in the function header.
 These are the values required by the function to perform the task.
Unit II 2.27

 If there is more than one parameters are required for the function they are listed
by separating by comma.
Example: defmy_add(a,b):

Arguments

 The value(s) provided in function call/invoke statement are called arguments.


 List of arguments should be supplied in same way as parameters are listed.
 Bounding of parameters to arguments is done 1:1, and so there should be same
number and type of arguments as mentioned in parameter list.
Example:my_add(x,y)

Return Statement

The return statement is used to exit a function and go back to the place from where it was
called.

If the return statement has no arguments, then it will not return any values. But exits
from function.

Syntax:

return[expression]

Example:

defmy_add(a,b):

c=a+b return c

x=5 y=4 print(my_add(x,y))

Output:

9
2.28 Data Expressions, Statements

Arguments Types

i) Required Arguments
ii) Keyword Arguments
iii) Default Arguments
iv) Variable length Arguments

Required Arguments

The number of arguments in the function call should exactly match with the
function definition.

Example

defmy_details( name, age ):

print("Name: ", name)

print("Age ", age)

return my_details("ram",46)

Output

Name: ram

Age 46

Keyword Arguments

Even though the arguments are used in out of order ,Python interpreter is able to
match the values with the help of keyword arguments.
Unit II 2.29

Example

defmy_details( name, age ):

print("Name: ", name)

print("Age ", age)

return my_details(age=46,name="ram")

Output

Name: ram

Age 46

Default Arguments: If a value is not provided in the function call for that argument a
default value is assumed.

Example

defmy_details( name, age=46 ):

print("Name: ", name)

print("Age ", age)

return

my_details(name="ram")

Output

Name: ram

Age 46
2.30 Data Expressions, Statements

Variable length Argument

While defining the function a variable length arguments can be defined by using *
symbol before parameter.

Example

defmy_details(*name ):
print(*name)
my_details("ram","sara","laks")

Output

ram saralaks

ALGORITHMS

EXCHANGE THE VALUES FOR TWO VARIABLES

There are three different algorithms available for exchanging the values of two variables.

1. Exchange with TemporaryVariable


2. Exchange without Temporary Variable using Exclusive OR
3. Exchange without Temporary Variable using arithmetic operation

Algorithm for Exchanging Two Variables using a Temporary (Third) Variable

Step 1: Start
Step 2: Read the values of first number and second number
Step 3: Assign the value of first Number with temporary variable ‘temp’
Step 4: Assign the value of first number to second number
Step 5: Reassign the second number value to temporary variable
Step 6: PRINT the swapped value
Step 7 : Stop
Unit II 2.31

Algorithm for Exchanging Two Variables without using a Temporary Variable


using Exclusive OR

Step 1: Start
Step 2: Read the value of variable1,variable2
Step 3: Perform Exclusive OR variable1 and variable2 and assign it to varaiable1
(varaible1=variable1^variable2)
Step 4: Perform Exclusive OR variable2 and variable1 and assign it to varaiable2
(varaible2=variable2^variable1)
Step 5: Perform Exclusive OR variable1 and variable2 and assign it to varaiable1
(varaible1=variable1^variable2)

Step 6: PRINT the exchanged value of variable1 and variable2


Step 7: Stop

Algorithm for Exchanging Two Variables without using a Temporary Variable


using Arithmetic Operation

Step 1: Start
Step 2: Read the value of variable1,variable2
Step 3: Assign the value of variable1 with added value of variable1 + variable2
(variable1= variable1 + variable2)

Step 4: Assign the value of variable2 with subtracted value of variable1 - variable2
(variable2= variable1 - variable2)
Step 5: Assign the value of variable1 with subtracted value of variable1 - variable2
(variable1= variable1 - variable2)
Step 6: PRINT the exchanged value of variable1 and variable2
Step 7: Stop
2.32 Data Expressions, Statements

Algorithm for Circulating the Values of‘ N’ Variables

Step 1: Start
Step 2: Define a list named list1[]
Step 3 : Read the input ‘n’ value to rotate the values

Step 4 : Perform the following step till

list2= list1[n:]+list1[:n] # using slice operator

Step 5 : Print the rotated values

Algorithm for Finding Distance Between Two Points

Step 1: Start

Step 2 : Import the module math

Step 3: Define a function with distance with four coordinates and call the function

Step 4: Calculate the difference of the ‘x’ coordinates as ‘xdiff’

Step 5: Calculate the difference of the ‘y’ coordinates as ‘ydiff’

Step 6: Calculate the sum of ‘x’ and ‘y’ coordinates

C=(xdiff**2)+(ydiff**2)

Step 7: Calculate the square root of ‘C’

Step 8: Print the difference between two points

Step 9: Stop
Unit II 2.33

QUESTIONS

Part A:

1. What is an interpreter?
2. List the difference between interpreter and compiler.
3. What are the two modes of python?
4. List the features of python.
5. List out the difference between interactive and script mode
6. What is value in python?

7. What is an identifier? List the rules to name identifier.


8. What is a keyword?
9. How to get data types in compile time and runtime?
10. What is indexing and types of indexing?
11. List out the operations on strings.
12. Mention the uses of slicing.
13. Explain below operations with the example
i)Concatenation (ii)Repetition
14. Give the difference between list and tuple.
15. Differentiate Membership and Identity operators.
16. Compose the importance of indentation in python.
17. Evaluate the expression by applying the value of a=5,b=3,c=8 and d=4and find
the result (i) (a+b)*c/d a+b*c/d
18. Define function and its uses.
19. Give the various data types in Python
20. Write a python program to assign and access the variables.
21. Discover the difference between logical and bitwise operator.
2.34 Data Expressions, Statements

22. Give the reserved words in Python.


23. Give the operator precedence in python.
24. Define the scope and lifetime of a variable in python.
25. Point out the uses of default arguments in python
26. Generalize the uses of python module.
27. Demonstrate how a function calls another function. Justify your answer.

28. List the syntax for function call with and without arguments.
29. What are the two parts of function definition? Give the syntax.
30. Give the syntax for variable length arguments.

Part B

1. Explain in detail about various data types in Python with an example program.

2. Explain the different types of operators in python with an example program.

3. Discuss the need and importance of function in python.

4. Explain in details about function prototypes in python.

5. Discuss about the various type of arguments in python.

6. Explain the flow of execution in user defined function with example.

7. Illustrate a program to display different data types using variables and literal
constants.

8. Show how an input and output function is performed in python with an example.

9. Explain in detail about the various operators in python with suitable examples.

10. Discuss the difference between tuples and list

11. Discuss the various operations that can be performed on a tuple and Lists
(minimum 5)with an example program

12. What is a membership and identity operator?


Unit II 2.35

13. Write a program to perform addition, subtraction, multiplication, integer division,


floor division and modulo division on two integer and float.

14. Write a program to convert degree Fahrenheit to Celsius

15. Discuss the need and importance of function in python.

16. Illustrate a program to exchange the value of two variables with temporary
variables

17. Briefly discuss in detail about function prototyping in python. With suitable
example program

18. Analyze the difference between local and global variables.

19. Explain with an example program to circulate the values of n variables

20. Analyze with a program to find out the distance between two points using python.

21. Do the Case study and perform the following operation in tuples i) Maxima
ii)Minima iii)sum of two tuples iv) duplicate a tuple v)slicing operator vi)
obtaining a list from a tuple vii) Compare two tuples viii)printing two tuples of
different data types

22. Write a program to find out the square root of two numbers.
Unit III 3.1

UNIT III

CONTROL FLOW, FUNCTIONS

Conditional statements: Boolean values and operators, conditional (if), alternative


(if-else), chained conditional (if-elif-else); Iterative statements: while, for, break,
continue, pass, Applying for critical conditions.
Algorithms: square root, gcd, exponentiation, sum an array of numbers, factorial
computation-Sine function computation-Generation of the Fibonacci sequence-
Reversing the digits of an integer.

Boolean Values

Boolean: Boolean data type has two possible values. They are 0 and 1. 0
represents False 1 represents True. True and False are keyword.

Boolean expressions

A Boolean expression is an expression that is either true or false. The following


examples use the operator ==, which compares two operands and produces True if they
are equal and False otherwise:

>>> 7 == 7

True

>>> 9 == 8

False

Here, True and False are special values that belongs to the data type bool; they
are not strings:

>>> type(True)

<class 'bool'>
3.2 Control Flow, Functions

>>> type(False)

<class 'bool'>

Operators: Operators are the constructs that can manipulate the value of operands.
Consider below the expression

10 + 8 = 18. Here, 10 and 8 are called operands and ‘+ ‘is called operator.

Types of operators

Python language supports the following types of operators.

1. Arithmetic Operators
2. Comparison (Relational) Operators

3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic operators

These operators performs mathematical operations like addition, subtraction,


multiplication etc.

Operator Description Example


a=5,b=15
+ Addition Adds values on either side of the operator. a + b = 20
- Subtraction Subtracts right side operand from left side a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 75
/ Division Divides left side operand by right side operand b / a = 3.0
% Modulus Divides left side operand by right side operand b%a=0
and returns remainder
Unit III 3.3

** Exponent Performs exponential (power) calculation on a**b = 5 to the


operators power 15
(30517578125)
// Floor Division - The division of operands where 9//2=4
the result is the quotient in which the digits after
the decimal point are removed

Comparison (relational) operators

Comparison operators compares values in either sides of them and returns either True or
False according to the condition. They also called as Relational operators.

Operator Description Example


a=5,b=15

If the values of two operands are equal, then the (a == b) is not


== condition becomes true. True.
If values of two operands are not equal, then
!= condition becomes true. (a!=b) is True

If the value of left operand is greater than the value (a > b) is not
> of right operand, then condition becomes true. True

If the value of left operand is less than the value of


< operand, then condition becomes true. (a < b) is True
If the value of left operand is greater than or equal
to the value of right operand, then condition (a >= b) is not
>= becomes true. True
If the value of left operand is less than or equal to
the value of right operand, then condition becomes (a <= b) is
<= true. True

Assignment Operators

Assignment operators assigns value to variables. The equals sign ‘=’ is known as
the assignment operator in Python. The purpose of the assignment operator is to take the
3.4 Control Flow, Functions

value from the right hand side of the operator (RHS value), and store it in the variable on
the left hand side (LHS value).

Operator Description Example

= Assigns values from right side c = a + b assigns


operands to left side operand
value of a + b to c

+= Add AND It adds right operand to the left c += a is equivalent


operand and
to c = c + a
assign the result to left operand

-= Subtract AND It subtracts right operand from the c -= a is equivalent


left operand and assign the result to
to c = c – a
left operand

*= Multiply AND It multiplies right operand with the c *= a is equivalent to c = c


left operand and assign the result to *a
left operand

/= Divide AND It divides left operand with the right c /= a is equivalent


operand and assign the result to left
to c = c / a
operand

%= Modulus AND It takes modulus using two operands c %= a is equivalent to


and assign the result to left operand
c=c%a

**= Exponent AND Performs exponential (power) c **= a is equivalent to


calculation operators and assign
c = c ** a
value to the left operand

//= Floor Division It performs floor division on c //= a is


operators and assign value to the left
equivalent to
operand
c = c // a

Logical Operators: The following logical operators supported by Python.


Assume variable ‘x’ holds 12 and variable ‘y’ holds 15 then
Unit III 3.5

Operator Description Example

and Logical If both the operands are true then condition (x and y) is
AND becomes true. true.

If any of the two operands are non-zero then (x or y) is


or Logical OR condition becomes true. true.

not Logical Not(x and y)


NOT Used to reverse the logical state of its operand. is false.

Bitwise Operators

Let a = 10 (0000 1010 in binary) and b = 4 (0000 0100 in binary)

Operator Description Example


& Binary Operator copies a bit to the result if it (a & b) (means 0000 0000)
AND exists in both operands
| Binary OR It copies a bit if it exists in either (a | b) = 14 (means 0000
operand. 1110)
^ Binary It copies the bit if it is set in one (a ^ b) = 14 (means 0000
XOR operand but not both. 1110)
~ Binary It is unary and has the effect of (~a ) = -11 (means 111 0101
Ones 'flipping' bits. in 2's complement form due
Complement to a signed binary number.
<< Binary The left operands value is moved left a << 2 = 40 (means 0010
Left Shift by the number of bits specified by the 1000)
right operand.
>> Binary The left operands value is moved a >> 2 = 2 (means 0000
Right Shift right by the number of bits specified 0010)
by the right operand.

Membership operators: Used to check a value or a variable is present in the specified


sequence of string, list, tuple and dictionary. To check particular element is available in
the list or not. The Operators are in and not in.
3.6 Control Flow, Functions

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results


specified sequence and false otherwise. in a 1 if x is a member
of sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and false results in a 1 if x is not
otherwise. a member of sequence
y.

Example

x = [5,3,6,4,1]

>>> 5 in x

True

>>> 5 not in x

False

Conditional (If)

The if statement has a logical expression by which data is matched and a decision is
made based on the outcome of the comparison.

Syntax

if <expression>:
<body>
Unit III 3.7

Flowchart

Example
numb = 3
if numb > 0:
print(numb, "is a positive number")
print("This is printed each time.")
numb = -1
if numb > 0:
print(numb, "is a positive number.")
print("This is also printed each time.")

Output

3 is a positive number.
This is printed each time.

The Boolean expression after if is called the condition. If it is true, then the indented
statement gets executed. If not, nothing happens.

Alternative execution (if… else)

A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
3.8 Control Flow, Functions

Syntax

if <test_expression>:
<body_1>
else:
<body_2>

Flowchart

Example

# Program checks the given number is positive or negative

number = 3

if number >= 0:

print("Value is Positive or Zero")

else:

print("Value is Negative")

Output

Value is Positive or Zero

Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches.
Unit III 3.9

Syntax

if<test_expression_1>: <body1>
elif <test_expression_2>: <body2>
elif <test_expression_3>: <body3>
else: <bodyN>

Flowchart

Example

# In this program, we check if the number is positive or

# negative or zero and

# display an appropriate message

num = 3.4

# Try these two variations as well

# num = 0

# num = -4.5

if num > 0:
3.10 Control Flow, Functions

print("Positive Number")

elif num == 0:

print("Zero")

else:

print("Negative Number")

Output

Positive Number

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is
no limit on the number of elif statements. If there is an else clause, it has to be at the end,
but there doesn’t have to be one.

if choice == 'a':

draw_a()

elif choice == 'b':

draw_b()

elif choice == 'c':

draw_c()

else:

draw d()

Each condition is checked in order. If the first is false, the next is checked, and so on. If
one of them is true, the corresponding branch executes, and the statement ends. Even if
more than one condition is true, only the first true branch executes.

Nested Conditionals: One conditional if can also be nested within another. Any
number of conditions can be nested inside one another. In the below syntax, if the outer
Unit III 3.11

if loop condition is true it checks inner if condition1. If both the conditions are true
statement1 gets executed otherwise statement2 gets executed and if the condition is false
statement3 gets executed.

Syntax

if <test_condition>:
if<test_condition1>:
statement1
else:
statement2
else:
statement3

Flowchart

Example

m=eval(input("Enter the value of m:"))

if(m==0):

print("The number is zero")

else:

if(m>0):

print("The number is Positive")

else:

print("The number is Negative")


3.12 Control Flow, Functions

Output

Enter the value of m: 10

The number is Positive

Iteration Statements

While Loop

While loop statement in Python is used to repeatedly execute set of statements as long as
the given condition is True. In while loop, the test_expression is first checked. The body
of the loop is entered only if the test_expression is True. After first iteration, the test
expression is checked again, this process continues until the test_expression becomes
False. In Python, the body of the while loop is determined through indentation. The
statements inside while starts with indentation and the first unindented line denotes the
end of loop.

Syntax
while <test_expression>:
<body>

Flowchart

The following program fragment prints the squares of all integers from 1 to 10. Here one
can replace the "while" loop by the for ... in range(...) loop:
Unit III 3.13

Example

i=1

while i <= 10:

print(i ** 2)

i += 1

Output

16

25

36

49

81

100

In this example, the variable ‘i’ inside the loop iterates from 1 to 10. Such a variable
whose value changes with each new loop iteration is called a counter. Note that after
executing this fragment the value of the variable ‘i’ is defined and is equal to 11, because
when i == 11 the condition i <= 10 is False for the first time.

The for statement

Python’s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence.
3.14 Control Flow, Functions

Syntax
for val in sequence:

Body of for

Flowchart

Example

# Program to find the sum of all numbers stored in a list

# List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum

sum = 0

# iterate over the list

for val in numbers:

sum = sum+val

print("The sum is:", sum)


Unit III 3.15

Output

The sum is: 48

Break : The break statement terminates the loop containing it. Control of the program
flows to the statement immediately after the body of the loop. If break statement is inside
a nested loop (loop inside another loop), break will terminate the innermost loop.The
working of break statement in for loop and while loop is shown below.

Example

# Prints out 0,1,2,3,4

count = 0

while True:

print(count)

count += 1

if count >= 5:

break
3.16 Control Flow, Functions

Output

Continue

The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration. The
working of continue statement in for and while loop is shown below.

Example

# Prints out only odd numbers - 1,3,5,7,9

for x in range(10):

# Check if x is even

if x % 2 == 0:

continue

print(x)

Output

9
Unit III 3.17

Pass

The pass statement does nothing. It can be used when a statement is required
syntactically but the program requires no action.

Example

>>> while True:

... pass # Busy-wait for keyboard interrupt (Ctrl+C)

...

This is commonly used for creating minimal classes:

>>> class MyEmptyClass:

... pass

...

Another place pass can be used is as a place-holder for a function or conditional body
when you are working on new code, allowing you to keep thinking at a more abstract
level. The pass is silently ignored:

>>> def initlog(*args):

... pass # Remember to implement this!


3.18 Control Flow, Functions

Algorithms

Square Root

Problem statement

Write an algorithm to find out square root of a given number n.

Algorithm development

Example

2*2 = 4

3*3 = 9

4*4 = 16

5*5= 25

...

...

It shows that

m*m = n; (1)

We don’t know the value of square root of n. so we make Initial guess for m. Always
take initial guess value is lesser than n. Because always square root value is lesser than
the given number.

One of the systematic approach to find out square root is:

1. Choose a number ‘m’ lesser than ‘n’.

2. Square the ‘m’ and if it is greater than ‘n’ decrease ‘m’ by 1 and repeat step 2. Else
goto step3.

3. When the square of ‘m’ is lesser than ‘n’ start increasing ‘m’ by 0.1 till ‘m’ value is
greater than ‘n’. At this point again decreasing value of ‘m’ by 0.01 and so on till
compute square root value with desired accuracy.
Unit III 3.19

In this approach number of iterations it requires is depends on value of Initial guess. So


in this approach we need to do changes to improve the performance.

For example find out square root of 36.

Initial guess value is 9.

9*9 = 81 greater than 36.

We know from equation (1) that the 9 should divide into 36 to give a quotient of 9 if it is
truly square root of 36. But it gives 4

The square root of 36 is lies between too big value of 9 and too small value of 4. Taking
the average of 9 and 4 is:

(9+4)/2= 6.5

This new estimate value again greater than 36, equal to or lesser than 36.

6.5*6.5 = 42.25 greater than 36.

Dividing new value by 36,

36/6.5 = 5.53.

5.53*5.53= 30.5809 lesser than 36.

Again take average between 6.5 and 5.53 and find out new estimate value of square root.
Continue this process till compute good square root value with desired accuracy.

In general, New square root value is (Initial guess value + n/Initial guess value)/2.
Repeat this step with new square root value till compute actual square root.

Let us take Initial guess value is n/2. Because Square root n is not more than n/2.

g2 (Initial Guess value) =n/2; g1=g2;

g2(New square root value) = (g1+n/g1)/2 ;

Terminate this algorithm when the differences between g1 and g2 becomes lesser than
some fixed error (eg. 0.0001 might be an acceptable error).
3.20 Control Flow, Functions

Algorithm description

1. Start the process

2. Read the value of given number n.

3. Initial guess value of square root g2 is n/2;

4. Repeat

4.1) Assign value of g2 to g1.

4.2) Calculate better square root value g2, by using averaging formula(g1+n/g1)/2.

Until absolute value of difference between g1 and g2 is lesser than 0.0001

5. Assign g2 to sqroot.

6. Write the value of sqroot.

7. Stop the process

Pseudo Code

Procedure squareroot

Input: n(Given Number) : Integer;

Output: sqroot (Square root value of n): Real;

var g1(previous square root value), g2(current square root value): Real;

begin

read(n); g2=n/2;

do

g1=g2;

g2=(g1+ n/g1)/2;

while (abs(g2-g1)< 0.0001);


Unit III 3.21

sqroot = g2;

write(sqroot);

end

Program

n=eval(input("Enter Number to find Square root: "))

root=n/2

for i in range(10):

root=(root+n/root)/2

print(root)

Output

Enter Number to find Square roor: 64

8.0

Exponentiation

Problem Description: The program takes a base and a power and finds the power of the
base using recursion.

Problem Solution

1. Take the base and exponential value from the user.


2. Pass the numbers as arguments to a recursive function to find the power of the
number.
3. Give the base condition that if the exponential power is equal to 1, return the base
number.
4. If the exponential power isn’t equal to 1, return the base number multiplied with the
power function called recursively with the arguments as the base and power minus 1.
5. Print the final result.
6. Exit.
3.22 Control Flow, Functions

Program

def power(base,exp):

if(exp==1):

return(base)

else:

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value:"))

result=power(base,exp)

print("Result:",result)

Output

Enter base: 2

Enter exponential value:3

Result: 8

Sum an Array of Numbers

Problem statement

Design an algorithm to make a sum of a given set of “n” numbers and print the result.

Algorithm development

Assumption: set of numbers(“n”>=0) Consider given set of numbers 125,65,87,43

Now, we have to add all the numbers and find sum value.

sum = 125 + 65 + 87 + 43
Unit III 3.23

In above expression will add all the four numbers and added value will be store into
variable sum.

Then generally,

sum = number1 + number2 + number3 + …….+ numbern. (1)

Here n(set of numbers) is 4. But in computer can add two numbers at a time. In this way
first two numbers will be added first. i.e.,

sum = number1 + number2 (2)

number1 = 125;

number2 = 65;

sum = 125 + 65;

Now current sum value is: sum = 190;

In the second step add the third number with the added value of the first two numbers
(sum).

sum = sum + number3 (3)

sum = 190 + 87;

Now current sum value is: sum = 177;

Similarly, sum = sum + number4 (4)

Now the current value of sum is : sum = 43;

In general,

sum = number1 + number2

sum = sum + number3

...

sum = sum + numbern


3.24 Control Flow, Functions

In the ith step

sum = sum + number i+1

We need to develop an algorithm to sum a set of “n” numbers.(n>=0). If it is zero the


sum value is zero, then we can generate first sum directly by

sum = 0;

because of this we need to change expression (2)

sum = sum + number1

Algorithm description

Step 1: Start the process.

Step 2: Read set of numbers (n).

Step 3: Initialize sum variable with value zero (sum = 0).

Step 4: Repeat till “n” numbers

(i) Read number.

(ii) Calculate sum = sum + number.

Step 5: Print the value of sum.

Step 6: Stop the process.

Pseudo code

Procedure summation

Input: n,number : integer

Output: sum : integer

Var i:integer

begin
Unit III 3.25

write(“enter total number of values”);

read(n);

i =1;

sum = 0;

while i<=n do

begin

i= i+1;

read (number)

sum = sum + number;

end

write(“sum of numbers is”, sum);

end

Program

n=eval(input("Enter n"))

i=1

sum=0

while(i<=n):

sum=sum+i

i=i+1

print(“The Sum is :”, sum)


3.26 Control Flow, Functions

Output

Enter n 10

The Sum is: 55

Factorial Computation

Problem statement

Design an algorithm to calculate factorial for given number.

Algorithm development

Assumption: given number n>=0

By definition n! = 1*2*3……n-1*n;

0! = 1;

1! = 1*0!;

2! = 2*1!;

3! = 3*2!;

In general n! = n * (n-1)!

For example, to calculate the value of 4!

4! = 4 *3! (Before that we need to find out 3!)

3! = 3*2! (Before that we need to find out 2!)

2!= 2*1! (Before that we need to find out 1!)


Unit III 3.27

1! = 1*0! (Before that we need to find out 0!)

0! = 1

So, we have start with 0!. By definition 0! = 1;

We are taking ”fact” variable to store factorial value of given number. Initially, the
value of fact is 0!.

So, fact = 1.

fact =fact*1;

fact = fact*2;

fact = fact*3;

fact = fact*4;

Total number of multiplication(product) count is 4

Algorithm description

Step 1: Start the process.

Step 2: Read the number (n).

Step 3: Initialize fact variable with value one (fact = 1) and productcount = 1.

Step 4: Repeat till “n” number of products

i. fact = fact * productcount;

ii. productcount = productcount + 1;

Step 5: Print the value of factorial.

Step 6: Stop the process.


3.28 Control Flow, Functions

Pseudo code

Procedure factorial

Input: n: integer

Output: fact: integer

Var i,productcount:integer

begin

write(“enter number to find out factorial”);

read(n);

fact=1;

productcount=1;

while productcount<=n

do

begin

fact = fact * productcount;

productcount = productcount + 1;

end

write(“Factorial of given numbers is”, fact);

end

Program

n=eval(input("enter n"))

i=1
Unit III 3.29

fact=1

while(i<=n):

fact=fact*i

i=i+1

print(fact)

output

enter n

120

Sine Function Computation

Problem statement

Design an algorithm to evaluate the function sin(x), as defined by the expression

x1 x 3 x 5 x 7
sin x = + _ + ...
1! 3! 5! 7!

Algorithm Development

Looking at the sin expression we can see that the powers and the factorials form the
sequence 1,3,5,7,….This can be generated by a sequence starting with 1 and
incrementing by 2 every time.

Every single term can be represented in general by

xi x x x x x
= × × × × ... ×
i! 1 2 3 4 i
3.30 Control Flow, Functions

These terms can be generated by using the value of previous term. For generating,

x3 x × x × x x2 x
= = ×
3! 3 × 2 × 1 3 × 2 1!

x5 x × x × x × x × x x 2 x3
= = ×
5! 5 × 4 × 3 ×2 × 1 5 × 4 3!

x7 x × x × x × x × x × x × x x 2 x5
= = ×
7! 7 × 6 × 5 × 4 × 3 × 2 ×1 7 × 6 5!

Each of these terms to be used to find the successive term can be generally specified as,

x2
for i = 3,5, 7,...
i(i − 1)

Therefore, to generate consecutive terms of the sine series,

x2
i th term = × previous term
i(i − 1)

For alternate sign, (-) is multiplied with the term.

Initial conditions are set according to the value of first term as follows:

tsin = x

term = x

i=1

The ith term and summation can be generated iteratively using the following statements:

i = i+2

term = - term*x*x/(i*(i-1)) tsin = tsin + term

Considerations

1. The input value x should be in the specified range, -1≤ x ≤ 1


Unit III 3.31

2. An error value is fixed as constant to terminate the iteration if the current term is
less than the error value.

Algorithm

1. Set up the initial conditions for the first term, as they cannot be calculated
iteratively.

2. While the absolute value of the current term is greater than the current term do

a) Identify the i value

b) Generate i th term value

c) Add current term with the appropriate sine value to the accumulated sum for
sine function.

Pseudocode

procedure sine function

Input : x : real

Output : tsinx : real

const error =1.0 e -6

var x,term :real;

var j,x2 : integer;

begin

term = x;

tsinx =x;

j =3;

x2 = x * x;

while abs(term) > error


3.32 Control Flow, Functions

begin

j = j + 2;

term = - (term * x2 / j * (j-1))

tsin : = tsin + term;

end

sin = tsin;

end

Program

import math

def sin(x,n):

sine = 0

for i in range(n):

sign = (-1)**i

pi=22/7

y=x*(pi/180)

sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign

return sine

x=int(input("Enter the value of x in degrees:"))

n=int(input("Enter the number of terms:"))

print(round(sin(x,n),2))

Output

Enter the value of x in degrees: 30


Unit III 3.33

Enter the number of terms: 10

0.5

Enter the value of x in degrees: 45

Enter the number of terms:15

0.71

Generation of Fibonacci Sequence

Problem statement

Generate and print the first n terms of the Fibonacci sequence, where n ≥ 1. The first few
terms are 0,1,1,2,3,5,8,13,21,…

Each term after the first two terms are obtained from the sum of two immediate
predecessors.

Algorithm development

New term = preceding term + term before the preceding term

A general procedure:

Variables used:

a = Term before the previous term

b = Previous term

c= new term

Now, a = 0; First Fibonacci number

b = 1; Second Fibonacci number

c = a + b ; Third Fibonacci number

To continue with next terms, we can reuse the variables a and b as follows:
3.34 Control Flow, Functions

a=0; First Fibonacci number

b=1; Second Fibonacci number

c=a+b; Third Fibonacci number

a = b;

b = c;

As we have only two active terms, we can reduce three terms [a,b,c] to two terms [a and
b]. This can be done by generating two terms at a time. The first four steps would
become,

a = 0; First Fibonacci number

b = 1; Second Fibonacci number

a = a + b ; Third Fibonacci number

b = a + b; Fourth Fibonacci number

Initialize i = 2; In every iteration two terms are generated and printed with the final
condition for iteration as (i<n), to ensure we print only n terms in the series.

Algorithm

1. Read the number of terms to be generated, n.


2. Assign first two Fibonacci numbers to a as 0 and b as 1.
3. Initialize count =2.
4. While less than n terms generated,
a. Write two terms as a and b.
b. Generate next term by a = a + b.
c. Generated another term by b = a + b.
d. Update count by count + 2.
5. If n is even write the last two generated terms, else write only the last but one term.
Unit III 3.35

Pseudocode

Procedure Fibonacci Var a {Fibonacci number variable},

b {Fibonacci number variable},

i{number of Fibonacci number generated },

n{ number of Fibonacci number to be generated }: integer;

begin {generate each Fibonacci number from the sum of its two predecessors}

a : =0;

b : =1;

i: = 2;

writeln („Enter n the number of Fibonacci numbers to be generated‟);

readln (n);

while i<n do

begin

writeln (a,b);

a :=a+b;

b:=a+b;

i :=i+2;

end

if i=n

then writeln (a,b)

else wrietln (a)

end
3.36 Control Flow, Functions

Program

a=0

b=1

m=eval(input("Enter the number of terms: "))

print("Fibonacci Series: ")

print(a,b)

for i in range(1,m,1):

c=a+b

print(c)

a=b

b=c

Output

Enter the number of terms: 6

Fibonacci Series:

01

8
Unit III 3.37

Reversing the Digits of an Integer

Problem

Design an algorithm that accepts a positive integer and reverses the digits in the integer.

Algorithm development

Digit reversing is used in computing for fast information retrieval. Let us take an
example

Input: 576894

Output expected: 498675

Here 576894 can written as

5*10 5 +7*10 4 +6*10 3+8 *10 2 +9*10 1+4

Least Significant value (LSB) - 4

Most Significant value (MSB) -5

To reverse it we have to extract the Least Significant value (LSB) from the number i.e., 4
first. This is accomplished by modulo division.

576894 mod 10 ◊ 4 (mod gives the remainder of division)

Followed by removing the next digit from the right hand side is 9.To extract 9 from the
number, we have to reduce the original number 576894 to 57689.This is done by integer
division of the number by 10.

576894 div 10 ◊ 57689

These two steps have to be done repeatedly until the number is greater than zero.

r = n mod 10 (576894 mod 10 gives 4)

n= n div 10 (576894 div 10 gives 57689)


3.38 Control Flow, Functions

The reversed number can be obtained at this stage by shifting the LSB one time left by
multiplying with 10.

49 = 4*10+9

Then the reversed number can be computed by

reverse = previous value of reverse*10 + remainder

where reverse = 0 initially

step 1: r = n mod 10

step 2: reverse =reverse*10 +r step 3: n= n div 10

These steps has to be repeated iteratively until n is equal to zero.

Number (n) remainder (r) reversed number (reverse) number (n)

576894 4 0*10+4 =4 57689


57689 9 4 *10+9 =49 5768
5768 8 49*10+8=498 576
576 6 498*10+6=4986 57
57 7 4986*10+7=49867 5
5 5 49867*10+5=498675 0

Algorithm description

1. Get the number to be reversed, n;

2. Initialize the reversed number, reverse to be zero. reverse = 0;


3. While number to be reversed is greater than zero
a. Extract the rightmost digit of the number, n and assign it to r.
b. Calculate reverse by increasing reverse by a factor of 10 and add r.
c. Remove the rightmost digit from n by using integer division by 10.
4. Display the reversed number, reverse.
Unit III 3.39

Pseudocode

Procedure reverse

Input : n (Number to be reversed)

Output : reverse (reversed number)

var r; (remainder value)

var n; (Number to be reversed)

var reverse; (reversed number)

begin

reverse=0;

write ('enter the number to be reversed');

read (n);

while n>0

do

begin

r=n mod 10;

reverse = reverses *10 +r;

n = n/10;

end

write (“The reversed number is‟, reverse);

end

Program

n=eval(input("enter a number"))
3.40 Control Flow, Functions

sum=0

while(n>0):

a=n%10

sum=sum*10+a

n=n//10

print(“The Reversed number is:”, sum)

Output

enter a number

189

The Reversed number is: 981

Practice Problems

1. Write a program to check the number is odd or even.

2. Write a program to check the year is leap year or not

3. Write a program to find greatest of two numbers

4. Write a program for checking eligibility for vote

5. Write a program to find sum of digits of a number

6. Write a program to check the given number is palindrome or not.

7. Write a program to check the given number is Armstrong or not

8. How can you use for loop in sequence.

9. How can you use else statement if loops.

10. Explain in detail about operators in detail.


Unit IV 4.1

UNIT IV

FUNCTION

Functions: return values, parameters, local and global scope. Lambda, filter, map
and reduce functions.
Algorithms: The smallest divisor of an integer-The greatest common divisor of
two integers-Generating Prime Numbers-Computing the Prime Factors of an
integer- Raising a Number to a Large Power

A function is a set of statements that take inputs, does definite computation and
produces results. Functions are targeted to get repetitive task done, thereby saving lot of
program memory space.

There are three types of functions in Python:

• Built-in functions, such as help() to ask for help, min() to get the minimum
value, print() to print an object to the terminal
• User-Defined Functions (UDFs), which are customized functions that users
create to serve a specific need.
• Anonymous functions, which are also called lambda functions that are not
declared with the standard “def” keyword.

4.1.1 Built-In Functions:

The Python interpreter has a number of functions and types built into it that are
always available. Eg: abs(),min(),max() etc.

Example:

print("Welcome")

Output:

Welcome
4.2 Function

4.1.2 User Defined Function

A user defined function is a programmed routine that has its parameters set by the
user of the system.

4.1.2.1 Creating a user defined function

In Python a function is defined using the def keyword:

Example:

def sat_fn():
print("Welcome")

4.1.2.2 Calling a function

To call a function, use the function name followed by parenthesis:

Example:

def sat_fn():
print("Welcome")
sat_fn()

Output:

Welcome

4.1.2.3 Parameters

Parameters are the place holder to carry any arguments passed on to a defined
function or method. In other words, parameters are named entities for the arguments
passed to any function or method call.

Parameters are suffixed after the function name, enclosed by parentheses. You
can add as many parameters as you want, delimited by commas for every parameter
being passed.

The following example has a function with one parameter (fname). When the
function is called, we pass along a first name, which is used inside the function to print
the full name:
Unit IV 4.3

Example:

defsat_fn(fname):

print(fname + " grace ")

sat_fn("Hannah")

sat_fn("Joannah")

Output:

Hannah grace

Joannah grace

4.1.2.3 .1 Default parameter value

If we call the function without parameter, it uses the default value:

Example:

defsat_fn(Animal="Tiger"):

print(" I am a " + Animal)

sat_fn("Lion")

sat_fn("Cheetah")

sat_fn()

Output:

I am a Lion

I am a Cheetah

I am a Tiger
4.4 Function

4.1.2.3 .2 Passing a list as a parameter

We can pass any type of data as parameter to a function (string, number, list,
dictionary etc.), and it will be treated as the same type of data inside the function.

E.g. if we pass a List as a parameter, it will still be a List when it reaches the function
body.

Example:

defsat_fn(country):

for y in country:

print(y)

name=["India","China","London"]

sat_fn(name)

Output:

India

China

London

4.1.2.4 Return values

The return statement causes your function to exit and hand back a value to its
caller. The return statement is the point in a function that gives back the control back to
the caller, along with the type of value defined.

To let a function return a value, use the return statement:

Example:

defsat_fn(x):

return 5 * x
Unit IV 4.5

print(sat_fn(2))

print(sat_fn(4))

print(sat_fn(6))

output:

10

20

30

If we want to type some text using user defined function sat_fn(), no need to use
return statement. However, if we want to continue to work with the result of the function
and try out some operations on it, then we need to use the return statement to actually
return a value, such as a String, an integer etc. Consider the following scenario, where
sat_fn() returns a string “, while the my_fn() returns None:

Example:

defsat_fn():

print("Welcome All")

return(4)

defmy_fn():

print("Welcome All")

# Multiply the output of `sat_fn()` with 2

print(sat_fn()*2)

# (Try to) multiply the output of `my_fn()` with 2

print(my_fn() * 2)
4.6 Function

Output:

Welcome All

Welcome All

Traceback (most recent call last):

File "C:/Users/ADMIN/AppData/Local/Programs/Python/Python37/prg6.py", line 9, in


<module>

print(my_fn() * 2)

TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'

The second function gives an error because we can’t perform any operations with
a None. we’ll get a TypeError that says that you can’t do the multiplication operation for
NoneType(the None that is the result of my_fn()).

4.1.2.5 Global vs local variables

In general, variables that are defined inside a function body have a local scope,
and those defined outside have a global scope. That means that local variables are
defined within a function block and can only be accessed inside that function, while
global variables can be obtained by all functions that might be in your script:

Example:

# Global variable `j`

j=1

# Define `sum()` function

def sum(*args):

# Local variable 'a'

a=0
Unit IV 4.7

for k in args:

a += k

return a

# Access the global variable

print("Initial Value is " + str(j))

# Access the local variable

print("Total is " + str(a))

Output:

Initial Value is 1

Traceback (most recent call last):

File "C:/Users/ADMIN/AppData/Local/Programs/Python/Python37/prg7.py", line 15,


in <module>

print("Total is " + str(a))

NameError: name 'a' is not defined

We could observe that we get a Name Error that says that the name ‘a’ is not
defined when you try to print out the local variable ’a’, that was defined inside the
function body. The ‘j’ variable, on the other hand, can be printed out without any
problems.

4.1.3 Anonymous Functions

In Python, anonymous function is one that does not have a name or signature. As
we already know that def keyword is used to define the normal functions and
the lambda keyword is used to create anonymous functions. It has the following syntax:

Syntax:

lambda arguments: expression


4.8 Function

• This function can have any number of arguments but only one expression, which
is evaluated and returned.

• One is free to use lambda functions wherever function objects are required.

• It has various uses in particular fields of programming besides other types of


expressions in functions.

Let’s look at this example and try to understand the difference between a normal
def defined function and lambda function. This is a program that returns the cube of a
given value:

Example:

# Python code to illustrate square of a number


# showing difference between def() and lambda().
def square(x):
return x*x;

j = lambda y: y*y
print(j(4))

print(square(3))

Output:

16

Without using Lambda : Here, both of them returns the square of a given number. But,
while using def, we needed to define a function with a name square and needed to pass a
value to it. After execution, we also needed to return the result from where the function
was called using the return keyword.

Using Lambda : Lambda definition does not include a “return” statement, it always
contains an expression which is returned. We can also put a lambda definition anywhere
Unit IV 4.9

a function is expected, and we don’t have to assign it to a variable at all. This is the
simplicity of lambda functions.

Lambda functions can be used along with built-in functions like filter(), map() and
reduce().

4.1.3.1 Use of lambda() with filter()

The filter() function in Python takes in a function and a list as arguments. This
offers an elegant way to filter out all the elements of a sequence “sequence”, for which
the function returns True. Here is a small program that returns the even numbers from an
input list:

Example:

# filter() with lambda()

li=[4,5,8,23,45,67,56,23,57,58]

even_list = list(filter(lambda y: (y%2 == 0) , li))

print(even_list)

Output:

[4, 8, 56, 58]

4.1.3.2 Use of lambda() with map()

The map() function in Python takes in a function and a list as argument. The
function is called with a lambda function and a list and a new list is returned which
contains all the lambda modified items returned by that function for each item. Example:

Example:

# Python code to illustrate map() with lambda()

#To get square of a list.

li=[2,5,8,7,6,10,20]
4.10 Function

final_list = list(map(lambda y: y*y , li))

print(final_list)

Output:

[4, 25, 64, 49, 36, 100, 400]

4.1.3.3 Use of lambda() with reduce()

The reduce() function in Python takes in a function and a list as argument. The
function is called with a lambda function and a list and a new reduced result is returned.
This performs a repetitive operation over the pairs of the list. This is a part of functools
module. Example:

Example:

# Python code to illustrate reduce() with lambda()

# to get sum of a list

fromfunctools import reduce

li = [5, 8, 10, 20, 50, 100]

sum = reduce((lambda x, y: x + y), li)

print (sum)

Output:

193

Here the results of previous two elements are added to the next element and this goes on
till the end of the list like (((((5+8)+10)+20)+50)+100).

4.2 SMALLEST DIVISOR OF AN INTEGER

4.2.1 ProblemStatement:

Given an integer n device an algorithm that will find its smallest exact divisor
other thanOne.
Unit IV 4.11

4.2.2 Algorithm Development:

Eg. Find the smallest divisor of 36

Consider n=36.

If the given number is even then the smallest divisor will be 2 always. To find whether
the given number is even use modulusoperation.

n % 2 ==0 then n is even. 2 is the smallest divisor.

If the given value is not even then the smallest divisor would be more than 2. Therefore
consider the starting divisor value as 3.

Smaller factor n = 36 Bigger factor


2 Linked with 18
3 linked with 12
4 linked with 9
6 linked with 6

From this we can see that the smallest divisor (2) is linked with the largest divisor(18),
the second smallest divisor (3) is linked with the second biggest divisor (12) and so on.
In the last step we could find that the fourth smallest factor (6) is linked with the fourth
biggest factor (6).

6*6=36
62 =36
Sqrt(36) = 6

We can conclude that the smallest divisor will not be more than the square root of the
given number “n‟. Therefore consider divisor value only till the sqrt(n).

r=trunc(sqrt(n))

trunc : truncate will convert the floating point value to a integer value.

sqrt(n) : finds the square root of the number “n‟.


4.12 Function

The divisor values considered will be starting with 3 till the value “r‟.

d=3
r=trunc(sqrt(n))
while(d<r)

Every time the current ‘”d‟ value is checked as whether it is a perfect divisor of “n‟ or
not. The remainder is checked to find out whether the given number “n‟ is perfectly
divisible by “d‟. The modulus operator is used for finding the remainder.

n% d
If the remainder is not equal to 0 then it means that “d‟ is not a perfect divisor of ”n‟.
Then we need to consider the next divisor. Therefore the condition is established as
shown below.

d=3
r=trunc(sqrt(n))
while (d<r) && (n%d !=0)

If both the condition is true it is necessary to find out the next divisor value “d‟.

The “d‟ value will not be even because all even values will have 2 as the smallest
divisor.

Therefore always increment “d‟ by 2. So that only odd values of “d‟ is considered.

d=3
r=trunc(sqrt(n))
while (d<r) && (n%d !=0) do
d=d+2
end
For prime numbers the smallest divisor “d‟ will not be found using the previous set of
statements. Since the divisors of prime number will be 1 or the number it self. For
checking this the last conditional statement is used.
Unit IV 4.13

ifn%d ==0 write(d)


else
write (1)
Ifthegivennumber“n‟isaprimenumberthen1willbedisplayed.Ifthegivennumber“n‟ is not a
prime number then “d‟ will bedisplayed.

4.2.3 Algorithm Description:

Step 1: Establish nthe integer whose smallest divisor is required.

Step 2: If n is an even number then return 2 as smallest divisor else

Step 2.a Compute r the square root of n

Step 2.b Initialize divisor d to 3

Step 2.c While not an Exact divisor and Square root limit not reached do

Step 2.c.1 Generate next member in the odd sequence d.

Step 2.d If current value d is an exact divisor then return it as the exact divisor of n else
return 1 as the smallest divisor of n.

4.2.4 Pseudo code:

PROCEDURE squareroot

Input: n(Given Number) : Integer;

Output: d (Smallest divisor of n): Integer:Varr :Integer

Begin

Read n;

If(n%2 ==0)

d=2;

Else

d = 3;
4.14 Function

r = trunc(sqrt(n));

While (d < r) && (n mod d!=0)

d=d+2;

End

End

If (n mod d !=0)

d = 1;

Write d;

End

4.2.5 Program:

from math import sqrt

from math import floor

defsmallestDivisor(n):

if n % 2 == 0:

print ("The smallest divisor for {} is {}".format(n, 2))

else:

r = floor(sqrt(n))

d=3

while d < r and n % d != 0 :

d=d+2

if n % d != 0:

print ("The smallest divisor for {} is {}".format(n,1))

else:

print ("The smallest divisor for {} is {}".format(n, d))

n=int(input("Enter an integer:"))
Unit IV 4.15

smallestDivisor(n)

Output:

Enter an integer:63

The smallest divisor for 63 is 3

Enter an integer:1013

The smallest divisor for 1013 is 1

4.3. GREATEST COMMON DIVISOR

4.3.1 Problem Statement:

To design an algorithm for finding the greatest common divisor of given two
non-zero integers n and m.

4.3.2 Algorithm Development:

Gcd of two numbers is the largest integer that divides both these integers without
any remainder. The usual method is to compute all the divisors of n and m
independently. With these two lists select the largest element common to both the list.
This common element is termed as gcd of the two numbers. But this is a time consuming
process because of generating all factors of the twointegers.

For a better solution, let us take the following considerations.

• Gcd of two numbers cannot be more than the smallernumber.


• Gcd of two numbers can be the smaller number itself if it exactly divides the
bigger number. Eg: GCD of 36 and 12 is12.
• Gcd of two numbers can be formed by an iterative construct. This reduces the
value of numbers smaller in every iteration by the difference betweenthem
• modfunction is used to find the remainder after thedivision.
• If it returns a zero it means that the bigger number is divisible by the smaller
number. Therefore the smaller number is thegcd.
4.16 Function

• If mod function does not return a zero the difference between the two numbers are
calculated , which is same as the result of the mod function. The two numbers are
replaced with the smaller number and the difference. This process is repeated till
the mod function returns zero. At this stage the smaller number is the gcd of the
two given numbers.

4.3.3 Algorithm description:

1) Read the two positive integers (non-zero) n &m

2) Repeat the following until reminder iszero

a) Get remainder(r) by dividing the larger integer by smallerinteger

b) If reminder not equal tozero

i. Larger integer(m) will take the value of smaller integer (n).

ii. Smaller integer(n) will take the value ofreminder(r).

3) Print the larger value as gcd ,m

4.3.4 Pseudocode :

PROCEDURE gcd (n, m :Integer)

Input: n ,m(Given Number) : Integer;

r :Integer;{ for storingremainder}

Begin

Read n,m;

Repeat

r = n % m;

n = m;

m =r;
Unit IV 4.17

until(r !=0);

Writeln(n); { display the value ofgcd}

End

4.3.5 Program:

defgcd(n, m):

while True:

r= n %m

n=m

m=r

if r == 0:

break

print(n)

x=int(input("Enter an integer:"))

y=int(input("Enter an integer:"))

gcd(x,y)

Output:

Enter an integer:4

Enter an integer:6

Enter an integer:12

Enter an integer:17

1
4.18 Function

4.4 GENERATION OF PRIME SERIES

4.4.1 Problem Statement

To generate all the prime numbers less than the given integer n.

4.4.2 Algorithm Development

Any integer n will be called as prime if it does not have factor other than 1 and its
own (n).Therefore for every time it is required to do n-2 division and comparison
operations which takes much time for larger values of n. The method given below simply
generates prime numbers untily ou get bored and stop it (likely), the maximum integer
size is reached (unlikely), or the program runs out of memory (much more likely than the
last one). It is based on the sieve method, and is quite fast.

To present the algorithm used by this method, we will start with the simple-
minded prime generation method. It is based on a double loop like this: this:

forn := 2 to infinity do

ford := 2 to n / 2 do

ifd divides n, proceed to the next n

printn

Now, we will try to improve the efficiency. First, we observe that the inner loop
needs only to check the d values which are themselves prime. Since it has already
identified these values, we need only remember them. So now wehave:

primes := { }

for n := 2 to infinity do

for each d in primes do

if d divides n, proceed to the next n

print n

primes := primes + {n}


Unit IV 4.19

This version is faster because the inner loop performs fewer iterations. It is possible to
make it still faster, however, by using a better data structure for primes. For this, first off,
we observe that any given prime number eliminates a series of its multiples in increasing
order. For instance, as n increases, the prime number 2 will eliminate 4, 6, 8, 10, . . ., in
that order. The prime number 7 eliminates 14, 21, 28, and so forth. This means that, for
any prime, we can predict which n value will be eliminated next.

This leads to the notion of an eliminator object. It is a pair of numbers, a prime


and one of its multiples. The multiple is the next n value which it will eliminate. It also
has a method advance which moves it to its next victim. That simply means adding the
prime to the multiple to create the next multiple. We keep a collection of these. For each
n value, we check to see if a member of our eliminator collection eliminates n. If so, we
know that that n is not prime, and we advance the eliminator.

Here's what that looks like:

n eliminators Action
2 Print n
3 (2,4) Print n
4 (2,4), (3,6) Eliminate n
5 (2,6), (3,6) Print n
6 (2,6), (3,6), (5,10) Eliminate n
7 (2,8), (3,9), (5,10) Print n
8 (2,8), (3,9), (5,10), (7,14) Eliminate n
9 (2,10), (3,9), (5,10), (7,14) Eliminate n
10 (2,10), (3,12), (5,10), (7,14) Eliminate n
11 (2,12), (3,12), (5,15), (7,14) Print n
12 (2,12), (3,12), (5,15), (7,14), (11, 22) Eliminate n

Finally, we want to answer the question "if eliminators contains some eliminator e =
(p, eliminators)" quickly. First observe that, at each step, if there is an
4.20 Function

eliminator for n in eliminators, it is always one with the smallest multiple.


Therefore we organize eliminators as a heap. A heap is a data structure from which is
it is efficient to find the smallest (or largest)item.

4.4.3 Pesudocode

PROCEDURE prime series

Input: N – Prime Series need to be generated up to N

Output: Set of Prime numbers printed

Begin

eliminators := { };

for n := 2 to infinity do

If eliminators contains some element e = (p, n) then

advance e to (p, n + p)

If there are any other e' = (p', n), advance them, too.

proceed to the next n

Write n;

eliminators := eliminators + {(n, 2n)}

End

4.4. 4 Program

r=int(input("Enter upper limit: "))


for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
Unit IV 4.21

if(k<=0):
print(a)
Output:
Enter upper limit: 10
2
3
5
7
4.5 COMPUTING THE PRIME FACTORS OF AN INTEGER

4.5.1Problem Definition:

Design an algorithm to compute all the prime factors for a given integer n.

4.5.2 Algorithm Development:

Any integer can be expressed as a product of several prime numbers. So, the given
integer n can be expressed as

n=f1 * f2* f3*f4 ............................. *fk

where n >1 and f1<=f2<=f3 ............................................... <= fk

Sayfor example

16 = 2 * 2 * 2*2

12 = 2 * 2 * 3

15 = 3 * 5

22 = 2 * 11

36 = 2 * 2 * 3 * 3

A common approach to get the set of prime factors is to choose the least prime number
which is 2 and treat it as divisor and repeat the factorization until 2 is no longer an exact
divisor. Follow the procedure for next smallest prime number until n reduced to 1.
4.22 Function

A simple example is given below.

Prime
2 2 2 3 4 5
Factors
Given
value (n) 60 30 15 5 5 5 1

The values which are bolded cannot be divided by the corresponding prime factors
(prime numbers which are above the bolded value). We know that all prime factors of n
must be less than or equal to √n (Square root of n). This makes the process as easy by
generating a list of primes up to √n before the process of establishing the prime factors of
n. The core operations which are used in this process are division and modulus which
helps to capture the quotient and remainder. The possible choices of the operation are
listed below.

(i) Exact division

(ii) Quotient greater than divisor

4.5.3 Algorithm Description:

1. Establish the integer n for which prime factors to besought.

2. Compute the remainder r and quotient q for the first primenxtprime=2.

3. While ( it is not established that n is prime )do

a. If nxtprime is an exact divisor of nthen

1. Save nxtprime as a factorf

2. Reduce n bynxtprime

Else

1. Get next biggest prime from the collection

b. Compute the next quotient q and remainder r for current value of n


and current prime divisor nxtprime
Unit IV 4.23

4. If n is greater than 1then

Add n to the list as prime factor f

5. Return the prime factors f for the given numbern.

4.5.4 Pseudocode

PROCEDURE PRIMEFACTORS

Input : n, An integer for which the prime factors need to be deduced

Output : The set of prime factors

Begin

nxtprime=2;

q=n/nxtprime;

r=n%nxtprime;

i=0

while (r=0 or q>nxtprime)

Begin

If(r=0) then

Begin

i=i+1

F[i]=nxtprime

n=q

End

Else

Get(d,nxtprime) // Get is a fn which gives next prme


4.24 Function

q=n/nxtprime

r=n%nxtprime

End

If n>1 then

Begin

i=i+1

F[i]=n

End

Return F[1..i]

End

4.5.5 Program

n=int(input("Enter an integer:"))

print("Factors are:")

i=1

while(i<=n):

k=0

if(n%i==0):

j=1

while(j<=i):

if(i%j==0):

k=k+1

j=j+1
Unit IV 4.25

if(k==2):

print(i)

i=i+1

Output:

Enter an integer:280

Factors are:

4.6 RAISING A NUMBER TO A LARGERPOWER

4.6.1 Problem Statement

Design an algorithm for computing the value of xn, where n is the positive integer
and its value is greater than 1.

4.6.2 Algorithm development

The given expression is p = xn , where x and n are the input.

The simple method is to get the p value by repeatedly multiplying x value for n
iterations and store the value in the p variable.

The computation is as follows

Initialize p = 1,

fori= 1 to n do

p=p*x;

Most of the times this way is satisfactory. But an efficient algorithm can be derived for
achieving efficiency.
4.26 Function

For example, let us take x10 the step by step computation will be

P1=x1=x

P2=x2=x*x

P3=x3=x2*x

P4=x4=x3*x

P10=x10=x9*x

In the above steps, x is increasing by one at each step.

For example x4 = x3 * x = (x2 * x) * x , this requires three multiplications, in terms of


power addition the result is 2+1+1=4.

To reduce this x4 = x2*x2 , this requires two multiplications. In terms of power addition
the result is 2+2=4.

Therefore multiplication translates into addition of powers.

The possible set of numbers that add up to 10are

8 + 2 =10

7 + 3 =10

6 +4 =10

5 + 5=10

4 + 4 +2 =10 and so on

Adding 4+4+2 is not going to be efficient as adding two numbers.

The equal power 5+5 or 6+4 may be optimal combination.

For x10=x5+x5 for that first we have generated x5 then multiplying x5 itself. Next to
compute x5,
Unit IV 4.27

x5 = x2 * x2+5

The reduced steps for computing x10 are

x2 = x * x

x4= x2 * x2

x5 = x4* x

x10= x5 *x5

In this scheme, we have only four rather than nine multiplications made earlier.

Consider another example to compute x23,

x23= x22 * x

x22= x11 * x11 x11 = x10 * x

x10= x5 * x5

x5 = x4* x

x4= x2 * x2

x2 = x * x

Here, we require 7 multiplications are required. From the above consideration, we come
to a conclusion that two conditions apply:

(a) If there is an odd power, it must have been generated from the power that
isone less (eg. x23 = x22*x)

(b) If there is an odd power, it can be computed from a power that is half its
size(x22= x11 * x11)

Our algorithm will need to be two parts:

1. Determination of multiplication strategy


4.28 Function

2. Power evaluation

To carry out the multiplication procedure, the integer divide the current power by 2 and
repeat the odd even procedure.

The odd/even information can be recorded in an array by storing a 1 for odd and 0 for
even powers.

For our example x23,

x23 d[1] =1

x11 d[2] =1

x5 d[3] =1

x2 d[4] =0

x1 d[5] =1

The power evaluation can be done using the following rule: if the current d array element
is zero then

(a) Square the current power product p.

(b) Square the current product p and multiply by x to generate an odd power.

If the power sequence are labelled psequence then to include the current power sequence
member into the accumulated product we can use the following standard form

Product = product * psequence

initializations of variables are

Product =1;

Psequence = x

In the successive iterations, the power value of psequence will need to be


doubled. This step can be achieved using:

Psequence = psequence * psequence


Unit IV 4.29

The next step in each iteration is that n must be divided by 2.

For eg. n = n div 2

The algorithm will terminate when n is reduced to zero.

4.6.3 Algorithm description

Step 1 : Get the input integer x and power n.

Step 2 : Initialize power sequence and product variable for the zero power case.

Step 3 : while the power is greater than zero do

(a) If next most significant binary digit of power n is onethen

(a.1) multiply accumulated product by current power sequence value;

(b) reduce power n by a factor of two using integerdivision.

(c) get next power sequence member by multiplying current value byitself.

Step 4 : Return x raised to the powern.

4.6.4 Pseudocode

Procedure Power

Varx,n,product,sequence : integer

Begin

Writeln(“Enter the Power”);

Readln(x,n);

Product:=1

Sequence:=x

While n>0 do

Begin
4.30 Function

If n mod x=1 then

Product:=product * sequence

n:=n div 2

sequence:=sequence * sequence

End

Writeln(“product”)

End

4.6.5 Program:

def power(base,exp):

if(exp==1):

return(base)

if(exp!=1):

return(base*power(base,exp-1))

base=int(input("Enter base: "))

exp=int(input("Enter exponential value: "))

print("Result:",power(base,exp))

Output:

Enter base: 2

Enter exponential value: 4

Result:16
Unit V 5.1

UNIT V

PYTHON COLLECTIONS (ARRAYS)

Lists: list operations, list slices, list methods, list loop, mutability, aliasing,
cloning lists, list parameters; Tuples: tuple assignment, tuple as return value;
Dictionaries: operations and methods; advanced list processing – list
comprehension;
Algorithms: Removal of Duplicates -Partitioning -Finding the kth smallest
Element- histogram.

There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate members.


• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.

When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security

5.1 PYTHON LIST

Lists are just like the arrays, declared in other languages. Lists need not be homogeneous
always which makes it a most powerful tool in Python. A single list may contain
DataTypes like Integers, Strings, as well as Objects. Lists are also very useful for
implementing stacks and queues. Lists are mutable, and hence, they can be altered even
after their creation.
5.2 Python Collections (Arrays)

In Python, list is a type of container in Data Structures, which is used to store multiple
data at the same time. Unlike Sets, the list in Python are ordered and have a definite
count. The elements in a list are indexed according to a definite sequence and the
indexing of a list is done with 0 being the first index. Each element in the list has its
definite place in the list, which allows duplicating of elements in the list, with each
element having its own distinct place and credibility.

Creating a List

Lists in Python can be created by just placing the sequence inside the square brackets[].
Unlike Sets, list doesn’t need a built-in function for creation of list. A list may contain
duplicate values with their distinct positions and hence, multiple distinct or duplicate
values can be passed as a sequence at the time of list creation.

It can have any number of items and they may be of different types (integer, float, string
etc.).

# empty list

my_list = []

# list of integers

my_list = [1, 2, 3]

# list with mixed datatypes

my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]


Unit V 5.3

ACCESSING VALUES IN LISTS

To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −

#!/usr/bin/python

list1 =['physics','chemistry',1997,2000];

list2 =[1,2,3,4,5,6,7];

print"list1[0]: ", list1[0]

print"list2[1:5]: ", list2[1:5]

When the above code is executed, it produces the following result −

list1[0]: physics

list2[1:5]: [2, 3, 4, 5]

UPDATING LISTS

You can update single or multiple elements of lists by giving the slice on the left-hand
side of the assignment operator, and you can add to elements in a list with the append()
method. For example −

#!/usr/bin/python

list=['physics','chemistry',1997,2000];

print"Value available at index 2 : "

print list[2]

list[2]=2001;
5.4 Python Collections (Arrays)

print"New value available at index 2 : "

print list[2]

Note − append() method is discussed in subsequent section.

When the above code is executed, it produces the following result −

Value available at index 2 :

1997

New value available at index 2 :

2001

DELETE LIST ELEMENTS

To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −

#!/usr/bin/python

list1 =['physics','chemistry',1997,2000];

print list1

del list1[2];

print"After deleting value at index 2 : "

print list1

When the above code is executed, it produces following result −

['physics', 'chemistry', 1997, 2000]


Unit V 5.5

After deleting value at index 2 :

['physics', 'chemistry', 2000]

Note − remove() method is discussed in subsequent section

5.2 BASIC LIST OPERATIONS

Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the
prior chapter.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

5.3 SLICING OF A LIST

In Python List, there are multiple ways to print the whole List with all the elements, but
to print a specific range of elements from the list, we use Slice operation. Slice operation
is performed on Lists with the use of colon(:). To print elements from beginning to a
range use [:Index], to print elements from end use [:-Index], to print elements from
specific Index till the end use [Index:], to print elements within a range, use [Start
5.6 Python Collections (Arrays)

Index:End Index] and to print whole List with the use of slicing operation, use [:].
Further, to print whole List in reverse order, use [::-1].

Slicing can be best visualized by considering the index to be between the elements as
shown below in Fig.1. So if we want to access a range, we need two index that will slice
that portion from the list.

Fig.1

# Python program to demonstrate

# Removal of elements in a List

# Creating a List

List = ['G','E','E','K','S','F',

'O','R','G','E','E','K','S']

print("Intial List: ")

print(List)

# Print elements of a range

# using Slice operation


Unit V 5.7

Sliced_List = List[3:8]

print("\nSlicing elements in a range 3-8: ")

print(Sliced_List)

# Print elements from beginning

# to a pre-defined point using Slice

Sliced_List = List[:-6]

print("\nElements sliced till 6th element from last: ")

print(Sliced_List)

# Print elements from a

# pre-defined point to end

Sliced_List = List[5:]

print("\nElements sliced from 5th "

"element till the end: ")

print(Sliced_List)

# Printing elements from

# beginning till end

Sliced_List = List[:]

print("\nPrinting all elements using slice operation: ")

print(Sliced_List)
5.8 Python Collections (Arrays)

# Printing elements in reverse

# using Slice operation

Sliced_List = List[::-1]

print("\nPrinting List in reverse: ")

print(Sliced_List)

Output

Intial blank List:

[]

List with the use of String:

['GeeksForGeeks']

List containing multiple values:

Geeks

Geeks

Multi-Dimensional List:

[['Geeks', 'For'], ['Geeks']]

List with the use of Numbers:

[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:

[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']


Unit V 5.9

5.4 BUILT-IN LIST METHODS

Python includes following list methods

S.No Methods Description


1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in
list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort([func]) Sorts objects of list, use compare func if given

PYTHON LIST APPEND() METHOD

Description

The method append appends a passed obj into the existing list.

Syntax

Following is the syntax for append method −

list.append(obj)

Parameters

• obj − This is the object to be appended in the list.

Return Value

This method does not return any value but updates existing list.
5.10 Python Collections (Arrays)

Example

The following example shows the usage of append method.

#!/usr/bin/python

aList=[123,'xyz','zara','abc'];

aList.append(2009);

print"Updated List : ",aList

When we run above program, it produces following result −

Updated List : [123, 'xyz', 'zara', 'abc', 2009]

PYTHON LIST COUNT METHOD

Description

The method count returns count of how many times obj occurs in list.

Syntax

Following is the syntax for count method −

list.count(obj)

Parameters

• obj − This is the object to be counted in the list.

Return Value

This method returns count of how many times obj occurs in list.

Example

The following example shows the usage of count method.


Unit V 5.11

#!/usr/bin/python

aList=[123,'xyz','zara','abc',123];

print"Count for 123 : ",aList.count(123)

print"Count for zara : ",aList.count('zara')

When we run above program, it produces following result −

Count for 123 : 2

Count for zara : 1

PYTHON LIST EXTEND METHOD

Description

The method extend appends the contents of seq to list.

Syntax

Following is the syntax for extend method −

list.extend(seq)

Parameters

• seq − This is the list of elements

Return Value

This method does not return any value but add the content to existing list.

Example

The following example shows the usage of extend method.


5.12 Python Collections (Arrays)

#!/usr/bin/python

aList=[123,'xyz','zara','abc',123];

bList=[2009,'manni'];

aList.extend(bList)

print"Extended List : ",aList

When we run above program, it produces following result −

Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

PYTHON LIST INDEX METHOD

Description

The method index returns the lowest index in list that obj appears.

Syntax

Following is the syntax for index method −

list.index(obj)

Parameters

• obj − This is the object to be find out.

Return Value

This method returns index of the found object otherwise raise an exception indicating
that value does not find.

Example

The following example shows the usage of index method.


Unit V 5.13

#!/usr/bin/python

aList=[123,'xyz','zara','abc'];

print"Index for xyz : ",aList.index('xyz')

print"Index for zara : ",aList.index('zara')

When we run above program, it produces following result −

Index for xyz : 1

Index for zara : 2

PYTHON LIST INSERT METHOD

Description

The method insert inserts object obj into list at offset index.

Syntax

Following is the syntax for insert method −

list.insert(index, obj)

Parameters

• index − This is the Index where the object obj need to be inserted.

• obj − This is the Object to be inserted into the given list.

Return Value

This method does not return any value but it inserts the given element at the given index.

Example

The following example shows the usage of insert method.


5.14 Python Collections (Arrays)

#!/usr/bin/python

aList=[123,'xyz','zara','abc']

aList.insert(3,2009)

print"Final List : ",aList

When we run above program, it produces following result −

Final List : [123, 'xyz', 'zara', 2009, 'abc']

PYTHON LIST POP METHOD

Description

The method pop removes and returns last object or obj from the list.

Syntax

Following is the syntax for pop method −

list.pop(obj = list[-1])

Parameters

• obj − This is an optional parameter, index of the object to be removed from the
list.

Return Value

This method returns the removed object from the list.

Example

The following example shows the usage of pop method.


Unit V 5.15

#!/usr/bin/python

aList=[123,'xyz','zara','abc'];

print"A List : ",aList.pop()

print"B List : ",aList.pop(2)

When we run above program, it produces following result −

A List :abc

B List :zara

PYTHON LIST REMOVE METHOD

Parameters

• obj − This is the object to be removed from the list.

Return Value

This method does not return any value but removes the given object from the list.

Example

The following example shows the usage of remove method.

#!/usr/bin/python

aList=[123,'xyz','zara','abc','xyz'];

aList.remove('xyz');

print"List : ",aList

aList.remove('abc');
5.16 Python Collections (Arrays)

print"List : ",aList

When we run above program, it produces following result −

List : [123, 'zara', 'abc', 'xyz']

List : [123, 'zara', 'xyz']

PYTHON LIST REVERSE METHOD

Description

The method reverse reverses objects of list in place.

Syntax

Following is the syntax for reverse method −

list.reverse()

Return Value

This method does not return any value but reverse the given object from the list.

Example

The following example shows the usage of reverse method.

#!/usr/bin/python

aList=[123,'xyz','zara','abc','xyz'];

aList.reverse();

print"List : ",aList

When we run above program, it produces following result −


Unit V 5.17

List : ['xyz', 'abc', 'zara', 'xyz', 123]

PYTHON LIST SORT METHOD


Description
The method sort sorts objects of list, use compare func if given.

Syntax
Following is the syntax for sort method −

list.sort([func])

Return Value
This method does not return any value but it changes from the original list.

Example
The following example shows the usage of sort method.

#!/usr/bin/python

aList=[123,'xyz','zara','abc','xyz'];
aList.sort();

print"List : ",aList

When we run above program, it produces following result −

List : [123, 'abc', 'xyz', 'xyz', 'zara']

5.5 PYTHON - LOOPS

In general, statements are executed sequentially: The first statement in a function is


executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more
complicated execution paths.
5.18 Python Collections (Arrays)

A loop statement allows us to execute a statement or group of statements multiple times.


The following Fig.2 illustrates a loop statement −

Fig.2

Python programming language provides following types of loops to handle looping


requirements.

•Repeats a statement or group of statements while a given


while loop condition is TRUE. It tests the condition before executing the
loop body.

for loop •Executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

nested loops •You can use one or more loop inside any another while, for or
do..while loop.
Unit V 5.19

LOOP CONTROL STATEMENTS

Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their
detail.

Let us go through the loop control statements briefly

• Terminates the loop statement and transfers


break statement execution to the statement immediately
following the loop.

• Causes the loop to skip the remainder of its


continue statement body and immediately retest its condition
prior to reiterating.

• The pass statement in Python is used when a


pass statement statement is required syntactically but you do
not want any command or code to execute.

PYTHON WHILE LOOP STATEMENTS

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is −

while expression:

statement(s)

Here, statementss may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true.
5.20 Python Collections (Arrays)

When the condition becomes false, program control passes to the line immediately
following the loop.

In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.
Unit V 5.21

Example

#!/usr/bin/python

count=0

while(count <9):

print'The count is:', count

count= count +1

print"Good bye!"

When the above code is executed, it produces the following result −

The count is: 0

The count is: 1

The count is: 2

The count is: 3

The count is: 4

The count is: 5

The count is: 6

The count is: 7

The count is: 8

Good bye!
5.22 Python Collections (Arrays)

The block here, consisting of the print and increment statements, is executed repeatedly
until count is no longer less than 9. With each iteration, the current value of the index
count is displayed and then increased by 1.

THE INFINITE LOOP

A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never
resolves to a FALSE value. This results in a loop that never ends. Such a loop is called
an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.

#!/usr/bin/python

var=1

whilevar==1:# This constructs an infinite loop

num=raw_input("Enter a number :")

print"You entered: ",num

print"Good bye!"

When the above code is executed, it produces the following result −

Enter a number :20

You entered: 20

Enter a number :29

You entered: 29

Enter a number :3
Unit V 5.23

You entered: 3

Enter a number between :Traceback (most recent call last):

File "test.py", line 5, in <module>

num = raw_input("Enter a number :")

KeyboardInterrupt

Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.

USING ELSE STATEMENT WITH LOOPS

Python supports to have an else statement associated with a loop statement.

• If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.

• If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise else statement gets
executed.

#!/usr/bin/python

count=0

while count <5:

print count," is less than 5"

count= count +1

else:
5.24 Python Collections (Arrays)

print count," is not less than 5"

When the above code is executed, it produces the following result −

0 is less than 5

1 is less than 5

2 is less than 5

3 is less than 5

4 is less than 5

5 is not less than 5

SINGLE STATEMENT SUITES

Similar to the if statement syntax, if your while clause consists only of a single
statement, it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause −

#!/usr/bin/python

flag=1

while(flag):print'Given flag is really true!'

print"Good bye!"

It is better not try above example because it goes into infinite loop and you need to press
CTRL+C keys to exit.

PYTHON FOR LOOP STATEMENTS

It has the ability to iterate over the items of any sequence, such as a list or a string.
Unit V 5.25

Syntax

foriterating_var in sequence:

statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating_var. Next, the statements block is
executed. Each item in the list is assigned to iterating_var, and the statementss block is
executed until the entire sequence is exhausted.

Flow Diagram

Example

#!/usr/bin/python

for letter in'Python':# First Example

print'Current Letter :', letter


5.26 Python Collections (Arrays)

fruits=['banana','apple','mango']

for fruit infruits:# Second Example

print'Current fruit :', fruit

print"Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

ITERATING BY SEQUENCE INDEX

An alternative way of iterating through each item is by index offset into the sequence
itself. Following is a simple example −

#!/usr/bin/python

fruits=['banana','apple','mango']

for index in range(len(fruits)):

print'Current fruit :', fruits[index]

print"Good bye!"
Unit V 5.27

When the above code is executed, it produces the following result −

Current fruit : banana

Current fruit : apple

Current fruit : mango

Good bye!

Here, we took the assistance of the len built-in function, which provides the total number
of elements in the tuple as well as the range built-in function to give us the actual
sequence to iterate over.

USING ELSE STATEMENT WITH LOOPS

Python supports to have an else statement associated with a loop statement

• If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.

• If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.

The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 through 20.

#!/usr/bin/python

fornumin range(10,20):#to iterate between 10 to 20

foriin range(2,num):#to iterate on the factors of the number

ifnum%i==0:#to determine the first factor

j=num/i#to calculate the second factor

print'%d equals %d * %d'%(num,i,j)


5.28 Python Collections (Arrays)

break#to move to the next number, the #first FOR

else:# else part of the loop

printnum,'is a prime number'

When the above code is executed, it produces the following result −

10 equals 2 * 5

11 is a prime number

12 equals 2 * 6

13 is a prime number

14 equals 2 * 7

15 equals 3 * 5

16 equals 2 * 8

17 is a prime number

18 equals 2 * 9

19 is a prime number

PYTHON NESTED LOOPS

Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.

SYNTAX

foriterating_var in sequence:
foriterating_var in sequence:
statements(s)
statements(s)
Unit V 5.29

The syntax for a nested while loop statement in Python programming language is as
follows −

while expression:

while expression:

statement(s)

statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other type
of loop. For example a for loop can be inside a while loop or vice versa.

EXAMPLE

The following program uses a nested for loop to find the prime numbers from 2 to 100 −

#!/usr/bin/python

i=2

while(i<100):

j =2

while(j <=(i/j)):

ifnot(i%j):break

j = j +1

if(j >i/j):printi," is prime"

i=i+1

print"Good bye!"
5.30 Python Collections (Arrays)

When the above code is executed, it produces following result −

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
Unit V 5.31

PYTHON BREAK STATEMENT

It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.

The most common use for break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost
loop and start executing the next line of code after the block.

SYNTAX

The syntax for a break statement in Python is as follows −

break

FLOW DIAGRAM
5.32 Python Collections (Arrays)

EXAMPLE

#!/usr/bin/python

for letter in'Python':# First Example

if letter =='h':

break

print'Current Letter :', letter

var=10# Second Example

whilevar>0:

print'Current variable value :',var

var=var-1

ifvar==5:

break

print"Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P

Current Letter : y

Current Letter : t

Current variable value : 10


Unit V 5.33

Current variable value : 9

Current variable value : 8

Current variable value : 7

Current variable value : 6

Good bye!

PYTHON CONTINUE STATEMENT

It returns the control to the beginning of the while loop.. The continue statement rejects
all the remaining statements in the current iteration of the loop and moves the control
back to the top of the loop.

The continue statement can be used in both while and for loops.

SYNTAX

continue

FLOW DIAGRAM
5.34 Python Collections (Arrays)

EXAMPLE

#!/usr/bin/python

for letter in'Python':# First Example

if letter =='h':

continue

print'Current Letter :', letter

var=10# Second Example

whilevar>0:

var=var-1

ifvar==5:

continue

print'Current variable value :',var

print"Good bye!"

When the above code is executed, it produces the following result −

Current Letter : P

Current Letter : y

Current Letter : t

Current Letter : o

Current Letter : n
Unit V 5.35

Current variable value : 9

Current variable value : 8

Current variable value : 7

Current variable value : 6

Current variable value : 4

Current variable value : 3

Current variable value : 2

Current variable value : 1

Current variable value : 0

Good bye!

PYTHON PASS STATEMENT

It is used when a statement is required syntactically but you do not want any command
or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written
yet e.g.,instubsforexamplee.g.,instubsforexample−

SYNTAX

pass

EXAMPLE

#!/usr/bin/python

for letter in'Python':

if letter =='h':
5.36 Python Collections (Arrays)

pass

print'This is pass block'

print'Current Letter :', letter

print"Good bye!"

When the above code is executed, it produces following result −

Current Letter : P

Current Letter : y

Current Letter : t

This is pass block

Current Letter : h

Current Letter : o

Current Letter : n

Good bye!

5.6 MUTABILITY

Lists are mutable. Mutable means, we can change the content without changing
the identity. Mutability is the ability for certain types of data to be changed without
entirely recreating it.Using mutable data types can allow programs to operate quickly
and efficiently. Example for mutable data types are: List, Set and Dictionary

Example 1:

numbers=[42,123]

numbers[1]=5

numbers [42,5]
Unit V 5.37

Here, the second element which was 123 is now turned to be 5.

Figure 5.1 shows the state diagram for cheeses, numbers and empty:

Lists are represented by boxes with the word “list” outside and the elements of the list
inside. cheeses refers to a list with three elements indexed 0, 1 and 2.

numbers contains two elements; the diagram shows that the value of the second
element has been reassigned from 123 to 5. empty refers to a list with no elements.

The in operator also works on lists.

>>>cheeses = ['Cheddar', 'Edam', 'Gouda']

>>> 'Edam' in
cheeses True

>>> 'Brie' in
cheeses False

5.7ALIASING

If a refers to an object and we assign b = a, then both variables refer to the same object:

>>> a = [1, 2, 3]

>>> b = a

>
>
>b
5.38 Python Collections (Arrays)

is
a
Tr
ue

The state diagram looks like Figure 4.2.

Figure 5.2 State Diagram

The association of a variable with an object is called a reference. In this


example, there are two references to the same object.An object with more than one
reference has more than one name, so we say that the object is aliased.If the aliased
object is mutable, changes made with one alias affect the other:

5.8 CLONING LISTS

veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","minehead
"]

veggies[1]="beetroot"

# Copying a list gives it another


name daniel=veggies

# Copying a complete slice


CLONES a list
david=veggies[:]

daniel[6]="emu"

# Daniel is a SECOND NAME for veggies so that changing Daniel also


changes veggies. # David is a COPY OF THE CONTENTS of veggies so that
changing Daniel (or veggies) does NOT changeDavid.

# Changing carrots into beetroot was done before any of the copies were made,
Unit V 5.39

so will affect all of veggies, daniel and david

for display in (veggies, daniel,


david): print(display)

Output:

['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion','emu']

['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion','emu']

['potatoes', 'beetroot', 'pepper', 'parsnips', 'swedes', 'onion', 'minehead']

5.9 LISTPAPRAMETERS

When we pass a list to a function, the function gets a reference to the list. If the
function modifies the list, the caller sees the change. For example, delete_head removes
the first element from a list:

Example:

defdelete_head(t):

d
el t[0]
Here’s how
it is used:

>>>letters = ['a', 'b', 'c']

>>>delete_head(letters)

>>>letters

Output:

['b', 'c']

The parameter t and the variable letters are aliases for the same object. The stack
diagram looks like Figure 4.3.Since the list is shared by two frames, I drew it between
them. It is important to distinguish between operations that modify lists and operations
5.40 Python Collections (Arrays)

that create new lists. For example, the append method modifies a list, but the + operator
creates a newlist.

Example 1:

>>> t1 = [1, 2]

>>> t2 = t1.append(3)

>>> t1

Output:

[1, 2, 3]

Example 2:

>>> t2

Output:

None

Figure 5.3 Stack Diagram

5.10 PYTHON - TUPLES

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists
and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you


can put these comma-separated values between parentheses also. For example −
Unit V 5.41

tup1 = ('physics', 'chemistry', 1997, 2000);

tup2 = (1, 2, 3, 4, 5 );

tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though
there is only one value −

tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.

ACCESSING VALUES IN TUPLES

To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −

#!/usr/bin/python

tup1 =('physics','chemistry',1997,2000);

tup2 =(1,2,3,4,5,6,7);

print"tup1[0]: ", tup1[0];

print"tup2[1:5]: ", tup2[1:5];

When the above code is executed, it produces the following result −

tup1[0]: physics

tup2[1:5]: [2, 3, 4, 5]
5.42 Python Collections (Arrays)

UPDATING TUPLES

Tuples are immutable which means you cannot update or change the values of tuple
elements. You are able to take portions of existing tuples to create new tuples as the
following example demonstrates −

#!/usr/bin/python

tup1 =(12,34.56);

tup2 =('abc','xyz');

# Following action is not valid for tuples

# tup1[0] = 100;

# So let's create a new tuple as follows

tup3 = tup1 + tup2;

print tup3;

When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

DELETE TUPLE ELEMENTS

Removing individual tuple elements is not possible. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example −

#!/usr/bin/python

tup=('physics','chemistry',1997,2000);

printtup;

deltup;
Unit V 5.43

print"After deleting tup : ";

printtup;

This produces the following result. Note an exception raised, this is because
after deltup tuple does not exist any more −

('physics', 'chemistry', 1997, 2000)


After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
printtup;
NameError: name 'tup' is not defined

BASIC TUPLES OPERATIONS

Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the
prior chapter −

Python Expression Results Description


len(1,2,3(1,2,3) 3 Length
1,2,31,2,3 + 4,5,64,5,6 1,2,3,4,5,61,2,3,4,5,6 Concatenation
′Hi!′,′Hi!′, * 4 ′Hi!′,′Hi!′,′Hi!′,′Hi!′′Hi!′,′Hi!′,′Hi!′,′Hi!′ Repetition
3 in 1,2,31,2,3 True Membership
for x in 1,2,31,2,3: print x, 123 Iteration

INDEXING, SLICING, AND MATRIXES

Because tuples are sequences, indexing and slicing work the same way for tuples as they
do for strings. Assuming following input −

L =('spam','Spam','SPAM!')
5.44 Python Collections (Arrays)

Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

Negative: count from the


L[-2] 'Spam'
right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

NO ENCLOSING DELIMITERS

Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples −

#!/usr/bin/python

print'abc',-4.24e93,18+6.6j,'xyz';

x, y =1,2;

print"Value of x , y : ",x,y;

When the above code is executed, it produces the following result −

abc -4.24e+93 (18+6.6j) xyz

Value of x , y : 1 2

BUILT-IN TUPLE FUNCTIONS

Python includes the following tuple functions −


Unit V 5.45

Sr.No. Function with Description

1 cmptuple1,tuple2tuple1,tuple2
Compares elements of both tuples.

2 lentupletuple
Gives the total length of the tuple.

3 maxtupletuple
Returns item from the tuple with max value.

4 mintupletuple
Returns item from the tuple with min value.

5 tupleseqseq
Converts a list into tuple.

TUPLE METHODS

Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a


tuple

index() Searches the tuple for a specified value and returns the
position of where it was found

ADVANTAGES OF TUPLE OVER LIST

Since tuples are quite similar to lists, both of them are used in similar situations as well.

However, there are certain advantages of implementing a tuple over a list. Below listed
are some of the main advantages:
5.46 Python Collections (Arrays)

• We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
• Since tuples are immutable, iterating through tuple is faster than with list. So
there is a slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary.
With lists, this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that
it remains write-protected.

5.11 PYTHON - DICTIONARY

Each key is separated from its value by a colon ::, the items are separated by commas,
and the whole thing is enclosed in curly braces. An empty dictionary without any items
is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.

ACCESSING VALUES IN DICTIONARY

To access dictionary elements, you can use the familiar square brackets along with the
key to obtain its value. Following is a simple example −

#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}

print"dict['Name']: ",dict['Name']

print"dict['Age']: ",dict['Age']

When the above code is executed, it produces the following result −

dict['Name']: Zara

dict['Age']: 7
Unit V 5.47

If we attempt to access a data item with a key, which is not part of the dictionary, we get
an error as follows −

#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}

print"dict['Alice']: ",dict['Alice']

When the above code is executed, it produces the following result −

dict['Alice']:

Traceback (most recent call last):

File "test.py", line 4, in <module>

print "dict['Alice']: ", dict['Alice'];

KeyError: 'Alice'

UPDATING DICTIONARY

You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry as shown below in the simple example −

#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}

dict['Age']=8;# update existing entry

dict['School']="DPS School";# Add new entry

print"dict['Age']: ",dict['Age']
5.48 Python Collections (Arrays)

print"dict['School']: ",dict['School']

When the above code is executed, it produces the following result −

dict['Age']: 8

dict['School']: DPS School

DELETE DICTIONARY ELEMENTS

You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example −

#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Class':'First'}

deldict['Name'];# remove entry with key 'Name'

dict.clear();# remove all entries in dict

deldict;# delete entire dictionary

print"dict['Age']: ",dict['Age']

print"dict['School']: ",dict['School']

This produces the following result. Note that an exception is raised because
after deldictdictionary does not exist any more −
Unit V 5.49

dict['Age']:

Traceback (most recent call last):

File "test.py", line 8, in <module>

print "dict['Age']: ", dict['Age'];

TypeError: 'type' object is unsubscriptable

Note − del method is discussed in subsequent section.

PROPERTIES OF DICTIONARY KEYS

Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys −

aa More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For
example −

#!/usr/bin/python

dict={'Name':'Zara','Age':7,'Name':'Manni'}

print"dict['Name']: ",dict['Name']

When the above code is executed, it produces the following result −

dict['Name']: Manni

bb Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example

#!/usr/bin/python
5.50 Python Collections (Arrays)

dict={['Name']:'Zara','Age':7}

print"dict['Name']: ",dict['Name']

When the above code is executed, it produces the following result −

Traceback (most recent call last):

File "test.py", line 3, in <module>

dict = {['Name']: 'Zara', 'Age': 7};

TypeError: unhashable type: 'list'

BUILT-IN DICTIONARY FUNCTIONS & METHODS

Python includes the following dictionary functions −

S.N. Function with Description

1 cmpdict1,dict2dict1,dict2
Compares elements of both dict.

2 lendictdict
Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.

3 strdictdict
Produces a printable string representation of a dictionary

4 typevariablevariable
Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.

Python includes following dictionary methods −


Unit V 5.51

Sr.No. Methods with Description

1 dict.clear
Removes all elements of dictionary dict

2 dict.copy
Returns a shallow copy of dictionary dict

3 dict.fromkeys
Create a new dictionary with keys from seq and values set to value.

4 dict.getkey,default=Nonekey,default=None
For key key, returns value or default if key not in dictionary

5 dict.has_keykeykey
Returns true if key in dictionary dict, false otherwise

6 dict.items
Returns a list of dict's key,valuekey,value tuple pairs

7 dict.keys
Returns list of dictionary dict's keys

8 dict.setdefaultkey,default=Nonekey,default=None
Similar to get, but will set dict[key]=default if key is not already in dict

9 dict.updatedict2dict2
Adds dictionary dict2's key-values pairs to dict

10 dict.values
Returns list of dictionary dict's values

PYTHON DICTIONARY COMPREHENSION


5.52 Python Collections (Arrays)

Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.

Dictionary comprehension consists of an expression pair (key: value) followed by for


statement inside curly braces {}.

Here is an example to make a dictionary with each item being a pair of a number and its
square.

Example
squares = {x: x*x for x in range(6)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)

This code is equivalent to

squares={}

for x in range(6):

squares[x]= x*x

A dictionary comprehension can optionally contain more for or if statements.

An optional if statement can filter out items to form the new dictionary.

5.12 LIST COMPREHENSION IN PYTHON

List comprehensions are used for creating new lists from other iterables.

As list comprehensions returns lists, they consist of brackets containing the expression,
which is executed for each element along with the for loop to iterate over each element.

This is the basic syntax:

new_list = [expression for_loop_one_or_more conditions]

For example, find the squares of a number using the for loop:
Unit V 5.53

numbers = [1, 2, 3, 4]

squares = []

for n in numbers:

squares.append(n**2)

print(squares) # Output: [1, 4, 9, 16]

Finding squares using list comprehensions:

numbers = [1, 2, 3, 4]

squares = [n**2 for n in numbers]

print(squares) # Output: [1, 4, 9, 16]

Here, square brackets signifies that the output is a list. n**2 is the expression executed for
each element and for n in numbers is used to iterate over each element. In other words,
execute n**2 (expression) for each element in numbers.

A more complex example of list comprehension:

Find common numbers from two lists using for loop.

Using conditions in list comprehensions:


5.54 Python Collections (Arrays)

list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]

common_num = []

for a in list_a:
for b in list_b:
if a == b:
common_num.append(a)

print(common_num) # Output [2, 3, 4]

Find common numbers from two list using list comprehension:

list_a = [1, 2, 3, 4]
list_b = [2, 3, 4, 5]
common_num = [a for a in list_a for b in list_b if a == b]
print(common_num) # Output: [2, 3, 4]

Return numbers from the list which are not equal as a tuple:

list_a = [1, 2, 3]
list_b = [2, 7]
different_num = [(a, b) for a in list_a for b in list_b if a != b]
print(different_num) # Output: [(1, 2), (1, 7), (2, 7), (3, 2), (3, 7)]
Unit V 5.55

Here. as we are returning a list of tuples, tuples must be in parenthesis to avoid errors. In
the above example, tuples with a and b will be printed such that a and b are not the same.

List comprehensions can also be used to iterate over strings, as shown below:

list_a = ["Hello", "World", "In", "Python"]


small_list_a = [str.lower() for str in list_a]
print(small_list_a) # Output: ['hello', 'world', 'in', 'python']

This example converts each of the string from list_a to a smaller case.

Like tuples, list comprehensions can be used to produce a list of a list, as shown below:

list_a = [1, 2, 3]
square_cube_list = [ [a**2, a**3] for a in list_a]
print(square_cube_list) # Output: [[1, 1], [4, 8], [9, 27]]

5.13 REMOVE DUPLICATES FROM A PYTHON LIST

First we have a List that contains duplicates:

A List with Duplicates

mylist = ["a", "b", "a", "c", "c"]

Create a dictionary, using the List items as keys. This will automatically remove any
duplicates because dictionaries cannot have duplicate keys.

Create a Dictionary. Then, convert the dictionary back into a list:

Convert Into a List

mylist = ["a", "b", "a", "c", "c"]

mylist = list( dict.fromkeys(mylist) )


5.56 Python Collections (Arrays)

Now we have a List without any duplicates, and it has the same order as the original List.

Print the List to demonstrate the result

Print the List

mylist = ["a", "b", "a", "c", "c"]

mylist = list(dict.fromkeys(mylist))

print(mylist)

CREATE A FUNCTION

If you like to have a function where you can send your lists, and get them back without
duplicates, you can create a function and insert the code from the example above.

Create a function that takes a List as an argument.

Create a Function

defmy_function(x):

Create a dictionary, using this List items as keys.Convert the dictionary into a list.Return
the list. Call the function, with a list as a parameter: At last print the result:

defmy_function(x):
return list(dict.fromkeys(x))

mylist = my_function(["a", "b", "a", "c", "c"])

print(mylist)
Unit V 5.57

5.14 K’TH SMALLEST/LARGEST ELEMENT IN UNSORTED ARRAY

Given an array and a number k where k is smaller than size of array, we need to find the
k’th smallest element in the given array. It is given that all array elements are distinct.

Examples:

Input: arr[] = {7, 10, 4, 3, 20, 15}

k=3

Output: 7

Input: arr[] = {7, 10, 4, 3, 20, 15}

k=4

Output: 10

A Simple Solution is to sort the given array using a O(nlogn) sorting algorithm
like Merge Sort, Heap Sort, etc and return the element at index k-1 in the sorted array.
Time Complexity of this solution is O(nLogn).

Program

# Python3 program to find k'th smallest


# element

# Function to return k'th smallest


# element in a given array
defkthSmallest(arr, n, k):

# Sort the given array


arr.sort()
5.58 Python Collections (Arrays)

# Return k'th element in the


# sorted array
returnarr[k-1]

# Driver code
if __name__=='__main__':
arr = [12, 3, 5, 7, 19]
n = len(arr)
k=2
print("K'th smallest element is",
kthSmallest(arr, n, k))
Output:

K'th smallest element is 5

5.15 PYTHON PARTITION

The Python Partition is one of the Python String Method which is used to split the given
string using the specified separator and return a tuple with three arguments. This Python
partition function will start looking for the separator from Left Hand side and once it
finds the separator, it will return the string before the Separator as Tuple Item 1,
Separator itself as Tuple Item 2 and remaining string (or string after the Separator) as
Tuple Item 3.

Syntax of a Partition Function in Python

The basic syntax of the Partition method in Python Programming Language is as shown
below:

String_Value.partition(Separator)

• String_Value: Please select the valid String variable or you can use the String
directly.
Unit V 5.59

• Separator: This argument is required and if you forget this argument, python will
throw TypeError.

Return Value

Python Partition function will return Tuple with three arguments. For example, If we
have A*B*C and If we use * as separator. The Python Partition function will search for *
from left to right. Once it find * it will return the string before the * symbol as Tuple
Item 1 (A), * as Tuple Item 2 and remaining string as Tuple Item 3 (B*C)

PYTHON PARTITION METHOD EXAMPLE

The following set of examples will help you understand the Partition Function in Python
Programming Language.

PYTHON CODE

# Python Partition Method Example

Str1 = 'Tutorial Gateway'


Str2 = 'Learn-Python-Programming'
Str3 = '[email protected]'

Str4 = Str1.partition(' ')


print("After Partitioning String 1 = ", Str4)

Str5 = Str2.partition('-')
print("After Partitioning String 2 = ", Str5)

Str6 = Str3.partition('@')
print("After Partitioning String 3 = ", Str6)

#Performing Python Partition function directly


Str7 = 'First_Image.png'.partition('.')
print("After Partitioning String 7 = ", Str7)
5.60 Python Collections (Arrays)

OUTPUT

In this python partition example, First, we declared three String variable Str1, Str2, Str3.
Next, we assigned corresponding value using following statement

Str1 = 'Tutorial Gateway'

Str2 = 'Learn-Python-Programming'

Str3 = '[email protected]'

Following statement will partition the Str1 string into multiple parts based on the
separator we specified (i.e, Empty Space) and prints the output.

Str4 = Str1.partition(' ')

print("After Partitioning String 1 = ", Str4)

Following statement will partition the Str2 string into multiple parts based on the ‘_’
symbol and prints the output.
Unit V 5.61

Str5 = Str2.partition('-')

print("After Partitioning String 2 = ", Str5)

The following Python partition statement will partition the Str3 string into multiple parts
based on the ‘@’ symbol and prints the output.

Str6 = Str3.partition('@')

print("After Partitioning String 3 = ", Str6)

Below statement uses the Partition function directly on String

Str7 = 'First_Image.png'.partition('.')

print("After Partitioning String 7 = ", Str7)

If you try something like,

Str8 = Str1.partition('*')

Above statement will look for *, which doesn’t exist. So it will return the tuple as
(‘Tutorial Gateway’, ”, ”)

5.16 HISTOGRAM

 A histogram is a visual representation of the Distribution of a Quantitative


variable.

 Appearance is similar to a vertical bar graph, but used mainly for


continuous distribution

 It approximates the distribution of variable being studied

 A visual representation that gives a discretized display of value counts.


5.62 Python Collections (Arrays)

Example

defhistogram(s):

d = dict() for c ins:

if c not in d:

d[c] = 1

else:

d[c] += 1

return d

The name of the function is histogram, which is a statistical term for a collection
of counters (or frequencies).

The first line of the function creates an empty dictionary. The for loop traverses
the string. Each time through the loop, if the character c is not in the dictionary, we
create a new item with key c and the initial value 1 (since we have seen this letter once).
If c is already in the dictionary we increment d[c]. Here’s how it works:
Unit V 5.63

Example:

>>> h = histogram('brontosaurus')

>>>h

Output:

{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}

The histogram indicates that the letters 'a' and 'b' appear once; 'o' appears twice,
and so on. Dictionaries have a method called get that takes a key and a default value. If
the key appears in the dictionary, get returns the corresponding value; otherwise it returns
the default value. For example:

>>> h = histogram('a')

>>>h

{'a': 1}

>>>h.get('a',0)

>>>h.get('b',0)

As an exercise, use get to write histogram more concisely. We should be able to


eliminate the if statement.

If we use a dictionary in a for statement, it traverses the keys of the dictionary.


For example, print_hist prints each key and the corresponding value:

defprint_hist(h):

for c inh:

pr
int(c, h[c]) Here’s what
the output looks like:
5.64 Python Collections (Arrays)

>>> h = histogram('parrot')
>>>print_hist(h) a1
p1
r2
t1
o1

Again, the keys are in no particular order. To traverse the keys in sorted order, we
can use the built-in function sorted:
>>>for key in sorted(h):
... print(key, h[key])
a1
o1
p1
r2
t1

Write a function named choose_from_hist that takes a histogram as defined in


Histogram given above and returns a random value from the histogram, chosen with
probability in proportion to frequency. For example, for this histogram:

>>> t = ['a', 'a', 'b']

>>>hist = histogram(t)

>>>hist

{'a': 2, 'b': 1}

The function should return 'a' with probability 2/3 and 'b' with probability 1/3.
Unit V 5.65

TWO MARKS

1. What are elements in a list? Give example.


The values in a list are called elements or items. A list must be enclosed in square
brackets ([and]). Examples:
>>>[10,20,30]
>>>[‘hi’,’hello’,’welcome’]

2. What is a nested list? Give example.


A list within another list is called nested list.
Example:
[‘good’,10,[100,99]]

3. What is a empty list?


A list that contains no elements is called empty list. It can be created with empty
brackets, [].

4. What is list slicing? Write its syntax.


List slicing is a computationally fast way to methodically access parts of given
data.
Syntax:
Listname [start:end:step]

5. What is mutability? What is its use?


Mutability is the ability for certain types of data to be changed without entirely
recreating it. Using mutable data types can allow programs to operate quickly and
efficiently.
6. List any three mutable data types. Give example for mutability.
Example for mutable data types are:
List, Set and Dictionary
5.66 Python Collections (Arrays)

Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
Output: [42,5]

7. What is aliasing? Give example.

An object with more than one reference has more than one name, so we say that
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other.
Example:
If a refers to an object and we assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>>b is a True

8. What is the difference between copying and cloning lists?

Copying a list gives it another name but copying a complete slice clones a list.

9. Give example for copying and cloning lists.

Example:
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","min
ehead"]
veggies[1]="beetroot"
Copying a list
daniel=veggies CLONES a list
david=veggies[:] daniel[6]="emu"
Unit V 5.67

10. Define Dictionaries. Give example.

A dictionary is an associative array (also known as hashes). Any key of the


dictionary is associated (or mapped) to a value. The values of a dictionary can
be any Python data type.

Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>>t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])

11. What is list processing?

List processing is a list of programming codes, including abstract data structure,


used to calculate specified variables in a certain order. A value may repeat more
than once.

You might also like