12CS em 01
12CS em 01
..1..
12 – Computer Science
..2..
12 – Computer Science
The return value of the pure functions solely The return value of the impure functions
depends on its arguments passed. does not solely depend on its arguments
passed.
Hence, if you call the pure functions with the Hence, if you call the impure functions with
same set of arguments, you will always get the same set of arguments, you might get
the same return values. the different return values.
They do not have any side effects. They have side effects.
5. What happens if you modify a variable outside the function? Give an example.
One of the most popular groups of side effects is modifying the variable outside
of function.
For example
let y: = 0
(int) inc(int) x:
y: = y + x;
return (y)
In the above example the value of ‘y’ get changed inside the function definition
due to which the result will change each time. The side effect of the inc() function is
it is changing the data of the external visible variable ‘y’.
..3..
12 – Computer Science
In the above function definition, the variables 'a' and 'b' are parameters and the
value which is passed to the variables 'a' and 'b' are arguments. We have also not
specified the datatype for 'a' and 'b'. This is an example of parameters without type.
(ii) Parameter with Type
The parameters 'a' and 'b' are specified in the data type brackets () in the above
function definition. This is an example of parameters with type.
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function
ii) Identify the statement which tells it is a recursive function
iii) Name of the argument variable
iv) Statement which invoke the function recursively
v) Statement which terminates the recursion
Answers:
i) gcd
ii) let rec gcd a b
iii) a, b
..4..
12 – Computer Science
ENGINE
getSpeed
No
Requi
red
Pull Fuel
Spe
Yes
Return
..5..
12 – Computer Science
➢ The person who drives the car doesn't care about the internal working.
➢ To increase the speed of the car he just presses the accelerator to get the desired
behaviour. Here the accelerator is the interface between the driver (the calling /
invoking object) and the engine (the called object).
➢ Internally, the engine of the car is doing all the things. It's where fuel, air, pressure,
and electricity come together to create the power to move the vehicle.
➢ All of these actions are separated from the driver, who just wants to go faster.
Thus, we separate interface from implementation.
..6..
2 DATA ABSTRACTION
..7..
12 – Computer Science
..8..
12 – Computer Science
..9..
12 – Computer Science
for example
Let's take an abstract datatype called city. This city object will hold the city's name,
and its latitude and longitude.
city = makecity (name, lat, lon)
✓ Here the function makecity (name, lat, lon) is the constructor. When it creates
an object city, the values name, lat and lon are sent as parameters.
✓ getname(city), getlat(city) and getlon(city) are selector functions that obtain
information from the object city.
2. What is a List? Why List can be called as Pairs. Explain with suitable example
✓ List is constructed by placing expressions within square brackets separated by
commas. Such an expression is called a list literal.
✓ The elements in the list can be of any type, and it can be changed.
Example:
lst := [10, 20]
10 and 20 can be accessed through Ist[0] and lst[1] respectively.
The above example mathematically we can represent.
✓ Any way of bundling two values together into one can be considered as a pair.
Lists are a common method to do so. Therefore, List can be called as Pairs.
Example:
lst[(0, 10), (1, 20)]
where 0 and 1 are index position and 10 and 20 are values. That is, the
elements of lst.
3. How will you access the multi-item. Explain with example.
You can use the structure construct in the OOP language to represent multi-part
objects where each part is named.
Consider the following pseudo code:
class Person:
creation( ) The new data type Person is the class
firstName := " " name, creation() is the function and
lastName := " " firstName, lastName, id, email are
id := " " variables.
email := " "
..10..
3 SCOPING
..11..
12 – Computer Science
10. The members that are accessible from within the class and are also available to its
subclasses is called
(A) Public members (B) Protected members
(C) Secured members (D) Private members
II. Answer the following questions: (2 Marks)
1. What is a scope?
Scope refers to the visibility of variables, parameters and functions in one part of
a program to another part of the same program.
2. Why scope should be used for variable. State the reason.
➢ The definition is used to indicate which part of the program the variable can be
accessed or used.
➢ It is a good practice to limit a variable's scope to a single definition. This way,
changes inside the function can't affect the variable on the outside of the
function in unexpected ways.
3. What is Mapping?
The process of binding a variable name with an object is called mapping. = (equal
to sign) is used in programming languages to map the variable and object.
4. What do you mean by Namespaces?
Namespaces are containers for mapping names of variables to objects.
5. How Python represents the private and protected Access specifiers?
➢ Python prescribes a convention of prefixing the name of the variable or method
with single or double underscore to emulate the behaviour of protected and
private access specifiers.
➢ All members in a Python class are public by default.
III. Answer the following questions: (3 Marks)
1. Define Local scope with an example.
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it
does not find it there, the outer scopes are checked.
Example
Disp( ):
a := 7 → local scope
print a
..12..
12 – Computer Science
Disp( )
Output
7
2. Define Global scope with an example.
➢ A variable which is declared outside of all the functions in a program is known as
global variable.
➢ This means, global variable can be accessed inside or outside of all the functions
in a program.
Example
a := 10 → global scope
Disp( ):
a := 7 → local scope
print a
Disp()
print a
Output
7
10
3. Define Enclosed scope with an example.
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
Example
Disp():
a := 10 → enclosed scope
Disp1()
print a
Disp1()
print a
Output
10
10
..13..
12 – Computer Science
..14..
12 – Computer Science
BUILT-IN
GLOBAL
ENCLOSED
LOCAL
Local scope:
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it
does not find it there, the outer scopes are checked.
Enclosed scope:
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
Global scope:
➢ A variable which is declared outside of all the functions in a program is known as
global variable.
➢ This means, global variable can be accessed inside or outside of all the functions
in a program.
Built-in scope:
➢ The built-in scope has all the names that are pre-loaded into the program scope
when we start the compiler or interpreter.
➢ Any variable or module which is defined in the library functions of a programming
language has Built-in or module scope.
..15..
12 – Computer Science
Example
Built-in/module scope → library files
a := 10 → global scope
Disp():
b := 7 → enclosed scope
Disp1()
c := 5 → local scope
print a, b, c
Disp1()
Disp()
Output
10
7
5
2. Write any Five Characteristics of Modules.
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
3. Write any five benefits in using modular programming.
❖ Less code to be written.
❖ Programs can be designed more easily because a small team deals with only a
small part of the entire code.
❖ Code is short, simple and easy to understand.
❖ Errors can easily be identified, as they are localized to a subroutine or function.
❖ The same code can be used in many applications.
❖ Modular programming allows many programmers to collaborate on the same
application.
❖ The scoping of variables can easily be controlled.
..16..
4 ALGORITHMIC STRATEGIES
..17..
12 – Computer Science
..18..
12 – Computer Science
➢ Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its
completion.
3. What are the factors that influence time and space complexity.
The efficiency of an algorithm depends on how efficiently it uses time and memory
space. The time efficiency of an algorithm is measured by different factors.
✓ Speed of the machine
✓ Compiler and other system Software tools
✓ Operating System
✓ Programming language used
✓ Volume of data required
4. Write a note on Asymptotic notation.
Asymptotic Notations are languages that uses meaningful statements about time
and space complexity. The following three asymptotic notations are mostly used to
represent time complexity of algorithms:
(i) Big O → worst-case
(ii) Big Ω → best-case
(iii) Big → average-case
5. What do you understand by Dynamic programming?
Dynamic programming is an algorithmic design method that can be used when the
solution to a problem can be viewed as the result of a sequence of decisions.
Steps to do Dynamic programming
➢ The given problem will be divided into smaller overlapping sub-problems.
➢ An optimum solution for the given problem can be achieved by using result of
smaller sub-problem.
➢ Dynamic algorithms use Memoization.
IV. Answer the following questions: (5 Marks)
1. Explain the characteristics of an algorithm.
❖ Input: Zero or more quantities to be supplied.
❖ Output: At least one quantity is produced.
❖ Finiteness: Algorithms must terminate after finite number of steps.
..19..
12 – Computer Science
..20..
12 – Computer Science
If you search for the number 25, the index will return to 3. If the searchable number
is not in the array, for example, if you search for the number 70, it will return -1.
3. What is Binary search? Discuss with example.
❖ Binary search also called half-interval search algorithm.
❖ It finds the position of a search element within a sorted array.
❖ The binary search algorithm can be done as divide-and-conquer search algorithm
and executes in logarithmic time.
Pseudo code for Binary search
1. Start with the middle element:
✓ If the search element is equal to the middle element of the array, then return
the index of the middle element.
✓ If not, then compare the middle element with the search value.
✓ If the search element is greater than the number in the middle index, then
select the elements to the right side of the middle index, and go to Step-1.
✓ If the search element is less than the number in the middle index, then select
the elements to the left side of the middle index, and start with Step-1.
2. When a match is found, display success message with the index of the element
matched.
3. If no match is found for all comparisons, then display unsuccessful message.
For example:
Using binary search, let's assume that we are searching for the location or index
of value 60.
❖ The mid value 50 is smaller than the target value 60. We have to change the value
of low to mid + 1 and find the new mid value again.
low = 5, high = 9
mid = 5 + ( 9 – 5 ) / 2 = 7
..21..
12 – Computer Science
❖ The mid value 80 is greater than the target value 60. We have to change the value
of high to mid - 1 and find the new mid value again.
low = 5, high = 6
mid = 5 + ( 6 – 5 ) / 2 = 5
❖ Now we compare the value stored at location 5 with our search element. We
found that it is a match.
❖ We can conclude that the search element 60 is found at lcoation or index 5.
4. Explain the Bubble sort algorithm with example.
➢ Bubble sort is a simple, it is too slow and less efficient when compared to insertion sort
and other sorting methods.
➢ The algorithm starts at the beginning of the list of values stored in an array. It compares
each pair of adjacent elements and swaps them if they are in the unsorted order.
➢ This comparison and passed to be continued until no swaps are needed.
Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a
pictorial representation of how bubble sort will sort the given array.
The above pictorial example is for iteration-1. Similarly, remaining iteration can be
done. At the end of all the iterations we will get the sorted values in an array as given
below:
11 12 13 14 15 16
..22..
TECH EASY 12 – Computer Science
..24..
12 – Computer Science
..25..
12 – Computer Science
..26..
12 – Computer Science
..28..
12 – Computer Science
(2) >>>x = 5
>>>print(x)
5
(3) >>>print( “The value of x = ”,x)
The value of x = 5
(4) >>>x = 2
>>>y = 3
>>>print( “ The sum of “,x,” and “,y,” is “, x+y )
The sum of 2 and 3 is 5
❖ The print ( ) evaluates the expression before printing it on the monitor.
❖ Comma ( , ) is used as a separator in print ( ) to print more than one item.
3. Discuss in detail about Tokens in Python.
Tokens:
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.
The normal token types are
1) Identifiers
2) Keywords
3) Operators
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens
1) Identifiers:
An Identifier is a name used to identify a variable, function, class, module or
object.
➢ An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
➢ Identifiers may contain digits (0 .. 9)
➢ Python identifiers are case sensitive i.e. uppercase and lowercase letters
are distinct.
➢ Identifiers must not be a python keyword.
➢ Python does not allow punctuation character such as %,$, @ etc., within
identifiers.
Examples : Sum, total_marks, regno, num1
..29..
12 – Computer Science
2) Keywords:
➢ Keywords are special words used by Python interpreter to recognize the
structure of program.
➢ As these words have specific meaning for interpreter, they cannot be used for
any other purpose.
Few python’s keywords are for, while, lamba, del, if, and, or,…
3) Operators:
➢ In computer programming languages operators are special symbols which
represent computations, conditional matching etc.
➢ Operators are categorized as Arithmetic, Relational, Logical, Assignment etc.
➢ Value and variables when used with operator are known as operands.
4) Delimiters:
➢ Python uses the symbols and symbol combinations as delimiters in expressions,
lists, dictionaries and strings.
➢ The following are few delimiters:
( ) [ ] { }
, : . ; ; “
5) Literals:
➢ Literal is a raw data given to a variable or constant.
➢ In Python, there are various types of literals.
1) Numeric
2) String
3) Boolean
..30..
6 CONTROL STRUCTRES
..31..
12 – Computer Science
..33..
TECH EASY
..35..
12 – Computer Science
..36..
7 PYTHON FUNCTIONS
..37..
12 – Computer Science
Example:
x = 26.7
print(math.ceil(x))
Output:
27
5. Write a Python code to check whether a given year is leap year or not.
n=int(input("Enter a Year : "))
if n%4 == 0:
print(n," is a Leap Year")
else:
print(n," is not a Leap Year")
6. What is composition in functions?
The value returned by a function may be used as an argument for another function
in a nested manner. This is called composition.
Example :
>>> n1 = eval (input ("Enter a number: "))
Enter an arithmetic expression: 234
>>> n1
234
In the above coding eval() function takes the returned value of string-based input
from input() function.
7. How recursive function works?
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to
continue recursion.
8. What are the points to be noted while defining a function?
❖ Function blocks begin with the keyword “def” followed by function name and
parenthesis ().
❖ Any input parameters or arguments should be placed within these parentheses
when you define a function.
❖ The code block always comes after a colon (:) and is indented.
..40..
12 – Computer Science
..41..
12 – Computer Science
..42..
12 – Computer Science
..43..