PST Book - Unit 1 - 5
PST Book - Unit 1 - 5
UNIT 1
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
• 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.
Step1: Start
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.
Control flow: The process of executing the statements in the given sequence is
called as control flow.
Unit I 1.3
• Sequence
• Selection
• Iteration
Sequence
Example: Algorithm to find the average of three numbers, the algorithm is as follows
Step 1: Start
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 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.
Step 1: Start
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
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.
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.
Pseudo code means a short, readable set of instructions written in English to explain an
algorithm.
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
ADD c=a+b
PRINT c
END
Advantages:
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
Rules:
Advantages:
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.
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.
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.
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
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
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
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 D: The Finance committee decides how to generate the revenue needed.
Iterations:
1. For loop
2. 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:
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
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.
Time Complexity Relatively lower time complexity Very high time complexity.
The following are some of the factors which helps in an analyzing an algorithm
• Efficiency
• Simplicity
• Generality
• Range of Growth
• Computing order of growth
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.
For example
int sum(int a[],int n)
{
Int sum=0
For (int i=0;i<n;i++)
{
Sum=sum+a[i]
}
Return sum
}
• 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.
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.
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.
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=0
Sum=sum+a[i]
Return sum
• In the above example, 4*n bytes of space is required for the array a[] elements.
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
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.
Compiler Interpreter
Compiler Interpreter
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)
1. Interactive mode
2. Script 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:
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.
This is an example of a print statement. It displays a result on the screen. In this case, the
result is the words.
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.
2.2.1 Value
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different data
types)
2.2.2 Types
Data Types
2.2.2.1 Numbers
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
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
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
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Member ship
Slice operator used >>> print(s[:10]) Slice from start and extracts five
to extract part of a Sathyabama characters.
data type
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
2.2.2.4 Tuple
Benefits of Tuple:
2.3 VARIABLES
Value should be given on the right side of assignment operator(=) and variable on left
side.
>>>counter=45
print(counter)
45
>>>bag=pencil=pen=100
>>>print(bag)
100
>>>print(pen)
100
>>>a,b,c=4,6,”ram”
>>>print(b)
>>>print(c)
ram
2.4 EXPRESSIONS
>>>55
55
>>>a=7
>>>b=8
>>>a+b+5
20
>>>z=(“hello”+”friend”)
print(z)
hellofriend
2.5 STATEMENTS
>>> 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.
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)
Example
a=5;b=4 Output
print(“Before Swapping”
Before Swapping
print(a,b)
54
temp=a
a=b
(a,b)=(b,a)
In tuple packing, the values on the left are ‘packed’ together in a tuple:
Unit II 2.13
In tuple unpacking, the values in a tuple on the right are ‘un packed’ into the
variables/names on the right:
>>>name
ram
>>>age
25
>>>salary
‘30000’
The right side can be any kind of sequence (string, list, tuple)
Example:
>>>mailid=’[email protected]’
>>>name,domain=mailid.split(‘@’)
>>>print(name)
ram
>>>print(domain)
abc.org
2.14 Data Expressions, Statements
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
• 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
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
Example:
# This is a comment.
# This is also a commentline .
# Every line has to be commented individually.
Syntax:
importmodule_name
module_name.function_name(variable)
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
1.math
2.random
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.
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
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:
2.9.1 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.
i) Built in 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.
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
Syntax :
deffun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2
…
statement n
return[expression]
Example :
defmy_add(a,b):
c=a+b
return c
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:
FLOW OF EXECUTION
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
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
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
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
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
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
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
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
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
return
my_details(name="ram")
Output
Name: ram
Age 46
2.30 Data Expressions, Statements
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
There are three different algorithms available for exchanging the values of two variables.
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
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 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
Step 1: Start
Step 2: Define a list named list1[]
Step 3 : Read the input ‘n’ value to rotate the values
Step 1: Start
Step 3: Define a function with distance with four coordinates and call the function
C=(xdiff**2)+(ydiff**2)
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?
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.
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.
11. Discuss the various operations that can be performed on a tuple and Lists
(minimum 5)with an example program
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
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
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
>>> 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
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic 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.
If the value of left operand is greater than the value (a > b) is not
> of right operand, then condition becomes 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).
and Logical If both the operands are true then condition (x and y) is
AND becomes true. true.
Bitwise Operators
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.
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
number = 3
if number >= 0:
else:
print("Value is Negative")
Output
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
num = 3.4
# 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()
draw_b()
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
if(m==0):
else:
if(m>0):
else:
Output
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
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.
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
# List of numbers
sum = 0
sum = sum+val
Output
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
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
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
...
... 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:
Algorithms
Square Root
Problem statement
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.
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
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.
36/6.5 = 5.53.
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.
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
4. Repeat
4.2) Calculate better square root value g2, by using averaging formula(g1+n/g1)/2.
5. Assign g2 to sqroot.
Pseudo Code
Procedure squareroot
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;
sqroot = g2;
write(sqroot);
end
Program
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
Output
8.0
Exponentiation
Problem Description: The program takes a base and a power and finds the power of the
base using recursion.
Problem Solution
Program
def power(base,exp):
if(exp==1):
return(base)
else:
return(base*power(base,exp-1))
result=power(base,exp)
print("Result:",result)
Output
Enter base: 2
Result: 8
Problem statement
Design an algorithm to make a sum of a given set of “n” numbers and print the result.
Algorithm development
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,
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.,
number1 = 125;
number2 = 65;
In the second step add the third number with the added value of the first two numbers
(sum).
In general,
...
sum = 0;
Algorithm description
Pseudo code
Procedure summation
Var i:integer
begin
Unit III 3.25
read(n);
i =1;
sum = 0;
while i<=n do
begin
i= i+1;
read (number)
end
end
Program
n=eval(input("Enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
Output
Enter n 10
Factorial Computation
Problem statement
Algorithm development
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)!
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;
Algorithm description
Step 3: Initialize fact variable with value one (fact = 1) and productcount = 1.
Pseudo code
Procedure factorial
Input: n: integer
Var i,productcount:integer
begin
read(n);
fact=1;
productcount=1;
while productcount<=n
do
begin
productcount = productcount + 1;
end
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
Problem statement
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.
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)
x2
i th term = × previous term
i(i − 1)
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
Considerations
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
c) Add current term with the appropriate sine value to the accumulated sum for
sine function.
Pseudocode
Input : x : real
begin
term = x;
tsinx =x;
j =3;
x2 = x * x;
begin
j = j + 2;
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)
return sine
print(round(sin(x,n),2))
Output
0.5
0.71
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
A general procedure:
Variables used:
b = Previous term
c= new term
To continue with next terms, we can reuse the variables a and b as follows:
3.34 Control Flow, Functions
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,
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
Pseudocode
begin {generate each Fibonacci number from the sum of its two predecessors}
a : =0;
b : =1;
i: = 2;
readln (n);
while i<n do
begin
writeln (a,b);
a :=a+b;
b:=a+b;
i :=i+2;
end
if i=n
end
3.36 Control Flow, Functions
Program
a=0
b=1
print(a,b)
for i in range(1,m,1):
c=a+b
print(c)
a=b
b=c
Output
Fibonacci Series:
01
8
Unit III 3.37
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
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.
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.
These two steps have to be done repeatedly until the number is greater than zero.
The reversed number can be obtained at this stage by shifting the LSB one time left by
multiplying with 10.
49 = 4*10+9
step 1: r = n mod 10
Algorithm description
Pseudocode
Procedure reverse
begin
reverse=0;
read (n);
while n>0
do
begin
n = n/10;
end
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
Output
enter a number
189
Practice Problems
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.
• 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.
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
A user defined function is a programmed routine that has its parameters set by the
user of the system.
Example:
def sat_fn():
print("Welcome")
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):
sat_fn("Hannah")
sat_fn("Joannah")
Output:
Hannah grace
Joannah grace
Example:
defsat_fn(Animal="Tiger"):
sat_fn("Lion")
sat_fn("Cheetah")
sat_fn()
Output:
I am a Lion
I am a Cheetah
I am a Tiger
4.4 Function
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
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.
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")
print(sat_fn()*2)
print(my_fn() * 2)
4.6 Function
Output:
Welcome All
Welcome All
print(my_fn() * 2)
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()).
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:
j=1
def sum(*args):
a=0
Unit IV 4.7
for k in args:
a += k
return a
Output:
Initial Value is 1
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.
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:
• 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.
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:
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().
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:
li=[4,5,8,23,45,67,56,23,57,58]
print(even_list)
Output:
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:
li=[2,5,8,7,6,10,20]
4.10 Function
print(final_list)
Output:
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:
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.1 ProblemStatement:
Given an integer n device an algorithm that will find its smallest exact divisor
other thanOne.
Unit IV 4.11
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.
If the given value is not even then the smallest divisor would be more than 2. Therefore
consider the starting divisor value as 3.
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.
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
Step 2.c While not an Exact divisor and Square root limit not reached do
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.
PROCEDURE squareroot
Begin
Read n;
If(n%2 ==0)
d=2;
Else
d = 3;
4.14 Function
r = trunc(sqrt(n));
d=d+2;
End
End
If (n mod d !=0)
d = 1;
Write d;
End
4.2.5 Program:
defsmallestDivisor(n):
if n % 2 == 0:
else:
r = floor(sqrt(n))
d=3
d=d+2
if n % d != 0:
else:
n=int(input("Enter an integer:"))
Unit IV 4.15
smallestDivisor(n)
Output:
Enter an integer:63
Enter an integer:1013
To design an algorithm for finding the greatest common divisor of given two
non-zero integers n and m.
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.
• 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.4 Pseudocode :
Begin
Read n,m;
Repeat
r = n % m;
n = m;
m =r;
Unit IV 4.17
until(r !=0);
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
To generate all the prime numbers less than the given integer n.
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
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
print n
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.
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
4.4.3 Pesudocode
Begin
eliminators := { };
for n := 2 to infinity do
advance e to (p, n + p)
If there are any other e' = (p', n), advance them, too.
Write n;
End
4.4. 4 Program
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.
Any integer can be expressed as a product of several prime numbers. So, the given
integer n can be expressed as
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
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.
2. Reduce n bynxtprime
Else
4.5.4 Pseudocode
PROCEDURE PRIMEFACTORS
Begin
nxtprime=2;
q=n/nxtprime;
r=n%nxtprime;
i=0
Begin
If(r=0) then
Begin
i=i+1
F[i]=nxtprime
n=q
End
Else
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:
Design an algorithm for computing the value of xn, where n is the positive integer
and its value is greater than 1.
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.
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
To reduce this x4 = x2*x2 , this requires two multiplications. In terms of power addition
the result is 2+2=4.
8 + 2 =10
7 + 3 =10
6 +4 =10
5 + 5=10
4 + 4 +2 =10 and so on
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
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.
x23= x22 * 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)
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.
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
(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 =1;
Psequence = x
Step 2 : Initialize power sequence and product variable for the zero power case.
(c) get next power sequence member by multiplying current value byitself.
4.6.4 Pseudocode
Procedure Power
Varx,n,product,sequence : integer
Begin
Readln(x,n);
Product:=1
Sequence:=x
While n>0 do
Begin
4.30 Function
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))
print("Result:",power(base,exp))
Output:
Enter base: 2
Result:16
Unit V 5.1
UNIT V
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:
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
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]
Also, a list can even have another list as an item. This is called nested list.
# nested list
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];
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 list[2]
list[2]=2001;
5.4 Python Collections (Arrays)
print list[2]
1997
2001
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 list1
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.
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
# Creating a List
List = ['G','E','E','K','S','F',
'O','R','G','E','E','K','S']
print(List)
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[:-6]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
Sliced_List = List[:]
print(Sliced_List)
5.8 Python Collections (Arrays)
Sliced_List = List[::-1]
print(Sliced_List)
Output
[]
['GeeksForGeeks']
Geeks
Geeks
Multi-Dimensional List:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Description
The method append appends a passed obj into the existing list.
Syntax
list.append(obj)
Parameters
Return Value
This method does not return any value but updates existing list.
5.10 Python Collections (Arrays)
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc'];
aList.append(2009);
Description
The method count returns count of how many times obj occurs in list.
Syntax
list.count(obj)
Parameters
Return Value
This method returns count of how many times obj occurs in list.
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc',123];
Description
Syntax
list.extend(seq)
Parameters
Return Value
This method does not return any value but add the content to existing list.
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc',123];
bList=[2009,'manni'];
aList.extend(bList)
Description
The method index returns the lowest index in list that obj appears.
Syntax
list.index(obj)
Parameters
Return Value
This method returns index of the found object otherwise raise an exception indicating
that value does not find.
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc'];
Description
The method insert inserts object obj into list at offset index.
Syntax
list.insert(index, obj)
Parameters
• index − This is the Index where the object obj need to be inserted.
Return Value
This method does not return any value but it inserts the given element at the given index.
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc']
aList.insert(3,2009)
Description
The method pop removes and returns last object or obj from the list.
Syntax
list.pop(obj = list[-1])
Parameters
• obj − This is an optional parameter, index of the object to be removed from the
list.
Return Value
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc'];
A List :abc
B List :zara
Parameters
Return Value
This method does not return any value but removes the given object from the list.
Example
#!/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
Description
Syntax
list.reverse()
Return Value
This method does not return any value but reverse the given object from the list.
Example
#!/usr/bin/python
aList=[123,'xyz','zara','abc','xyz'];
aList.reverse();
print"List : ",aList
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
Programming languages provide various control structures that allow for more
complicated execution paths.
5.18 Python Collections (Arrays)
Fig.2
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 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.
Syntax
while expression:
statement(s)
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):
count= count +1
print"Good bye!"
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.
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
print"Good bye!"
You entered: 20
You entered: 29
Enter a number :3
Unit V 5.23
You entered: 3
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
• 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
count= count +1
else:
5.24 Python Collections (Arrays)
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
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.
#!/usr/bin/python
flag=1
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.
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
fruits=['banana','apple','mango']
print"Good bye!"
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!
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']
print"Good bye!"
Unit V 5.27
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.
• 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
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 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
i=i+1
print"Good bye!"
5.30 Python Collections (Arrays)
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
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
break
FLOW DIAGRAM
5.32 Python Collections (Arrays)
EXAMPLE
#!/usr/bin/python
if letter =='h':
break
whilevar>0:
var=var-1
ifvar==5:
break
print"Good bye!"
Current Letter : P
Current Letter : y
Current Letter : t
Good bye!
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
if letter =='h':
continue
whilevar>0:
var=var-1
ifvar==5:
continue
print"Good bye!"
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Unit V 5.35
Good bye!
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
if letter =='h':
5.36 Python Collections (Arrays)
pass
print"Good bye!"
Current Letter : P
Current Letter : y
Current Letter : t
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
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.
>>> '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
veggies=["potatoes","carrots","pepper","parsnips","swedes","onion","minehead
"]
veggies[1]="beetroot"
daniel[6]="emu"
# Changing carrots into beetroot was done before any of the copies were made,
Unit V 5.39
Output:
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:
>>>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
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.
tup2 = (1, 2, 3, 4, 5 );
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.
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);
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');
# tup1[0] = 100;
print tup3;
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
printtup;
This produces the following result. Note an exception raised, this is because
after deltup tuple does not exist any more −
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 −
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)
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;
Value of x , y : 1 2
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
index() Searches the tuple for a specified value and returns the
position of where it was found
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.
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.
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']
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']
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'}
print"dict['Age']: ",dict['Age']
5.48 Python Collections (Arrays)
print"dict['School']: ",dict['School']
dict['Age']: 8
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'}
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']:
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.
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']
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']
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.
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
Dictionary comprehension is an elegant and concise way to create new dictionary from
an iterable in Python.
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)
squares={}
for x in range(6):
squares[x]= x*x
An optional if statement can filter out items to form the new dictionary.
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.
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)
numbers = [1, 2, 3, 4]
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.
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)
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:
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]]
Create a dictionary, using the List items as keys. This will automatically remove any
duplicates because dictionaries cannot have duplicate keys.
Now we have a List without any duplicates, and it has the same order as the original List.
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
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))
print(mylist)
Unit V 5.57
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:
k=3
Output: 7
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
# 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:
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.
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)
The following set of examples will help you understand the Partition Function in Python
Programming Language.
PYTHON CODE
Str5 = Str2.partition('-')
print("After Partitioning String 2 = ", Str5)
Str6 = Str3.partition('@')
print("After Partitioning String 3 = ", Str6)
OUTPUT
In this python partition example, First, we declared three String variable Str1, Str2, Str3.
Next, we assigned corresponding value using following statement
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.
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('-')
The following Python partition statement will partition the Str3 string into multiple parts
based on the ‘@’ symbol and prints the output.
Str6 = Str3.partition('@')
Str7 = 'First_Image.png'.partition('.')
Str8 = Str1.partition('*')
Above statement will look for *, which doesn’t exist. So it will return the tuple as
(‘Tutorial Gateway’, ”, ”)
5.16 HISTOGRAM
Example
defhistogram(s):
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:
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)
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
>>>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
Example 1:
>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers
Output: [42,5]
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
Copying a list gives it another name but copying a complete slice clones a list.
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
Example:
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>>t
Output:
dict_items([('c', 2), ('a', 0), ('b', 1)])