0% found this document useful (0 votes)
11 views27 pages

Computer Modified

This document is a textbook for the Higher Secondary Second Year Computer Science curriculum published by the Government of Tamil Nadu. It covers topics such as Python programming, data abstraction, algorithms, and database concepts, designed for students with prior knowledge of C++. The book includes practical exercises, technical terminologies, and QR codes for additional resources.

Uploaded by

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

Computer Modified

This document is a textbook for the Higher Secondary Second Year Computer Science curriculum published by the Government of Tamil Nadu. It covers topics such as Python programming, data abstraction, algorithms, and database concepts, designed for students with prior knowledge of C++. The book includes practical exercises, technical terminologies, and QR codes for additional resources.

Uploaded by

enviedguts
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link].

in

GOVERNMENT OF TAMILNADU

HIGHER SECONDARY
SECOND YEAR

COMPUTER SCIENCE

A publication under Free Textbook Programme of Government of Tamil Nadu

Department of School Education


Untouchability is Inhuman and a Crime

12th Std - CS EM Introduction [Link] 1 23-12-2022 13:19:00


Government of Tamil Nadu
First Edition - 2019
Revised Edition - 2020, 2022, 2023
Reprint - 2021, 2024
(Published under New syllabus)

NOT FOR SALE

Content Creation

The wise
possess all

State Council of Educational


Research and Training
© SCERT 2019

Printing & Publishing

Tamil NaduTextbook and Educational


Services Corporation
[Link]

II

12th Std - CS EM Introduction [Link] 2 15/12/2023 11:34:28


The tremendous effect of the computer and computing technology is in
shaping the modern society for the betterment of mankind. Human
civilization achieved the highest peak with the development
of computer known as “Internet Era”.

PREFACE Python being a high level language is good


for beginners to learn due to its easy syntax
and powerful memory management. For any
internet applications, it is good to learn as python being the
better choice.
The user of this textbook being acquainted with the knowledge of C++ in
std XI will have no difficulty in studying python language. No substantial
knowledge nor experience, is required as the examples illustrated in the
book are easy to follow

HOW
 his book does not require
T TO USE
prior knowledge in computer
Technology
THE BOOK?
 ach unit comprises of simple
E
activities and demonstrations which can be done by
the teacher
and also students.
Technical terminologies are listed in glossary for easy understanding
 he “ Do you know?” boxes enrich the knowledge of reader with
T
additional information
 orkshops are introduced to solve the exercises using software
W
applications
QR codes are used to link supporting additional
materials in digital form
How to get connected to QR Code?
o 
Download the QR code scanner from the google play store/
apple app store into your smartphone
o Open the QR code scanner application
o Once the scanner button in the application is clicked, camera opens
and then bring it closer to the QR code in the textbook.
o Once the camera detects the QR code, a URL appears in the screen.
Click the URL and go to the content page.

III

12th Std - CS EM Introduction [Link] 3 23-12-2022 13:19:00


Computer Knowledge Hub
C PG in Computer Science

Centre ffor Development of Advanced Computing [Link] Artificial Intelligence Database Management

12th Std - CS EM Introduction [Link] 4


Indian Computing Olympiad [Link] Information Management Systems
International Olympiad of Informatics [Link] and Data Analytics Fundamentals of Algorithms
Microsoft certification exams [Link] Algorithms Graphics
National Cyber Olympiad [Link] Applied Computer Science Machine Learning
Big Data Analytics Mobile and Web Computing
National Institute of Electronics & Information Technology [Link]
Bio Informatics Mobile Device Programming
National Programme on Technology Enhanced Learning [Link]
Cloud Computing Modern Programming Practices
Compiler Design & Modern Web Applications
Construction Operating Systems
After Completing +2
A Computer and Network Parallel Programming
Security Robotics
Scie
Arts & Science BSc Courses | Animation & Multimedia
Computer Networks Software Engineering
Computer Science | Geography
Computer Security Software Engineering
Journalism / Mass Media Communication | Library Science
Computer Simulation Software Testing
Maths / Physics / Chemistry / Statistics | Psychology/ Sociology
Cyber Security Systems Analysis and Design
Social Work | Visual Communication | B.C.A. COMPUTER Data Analytics Web Application Architecture
SCIENCE Data Mining Web Application Programming

IV
Technical Diploma
Scholarships for graduate
Diploma in Engineering
D and post graduate courses

DST – INSPIRE
IN Fellowships (for Ph.D)
Professional Degree & Entrance Exams
P DST – INSPIRE Scholarships
(for UG and PG)
Hotel & Catering Institute [Link] JEE-Joint Entrance Examination [Link] In addition various fellowships for
AIEEE- All India Engineering Entrance Exam JEST- Joint Entrance Screening Test [Link] SC/ST/PWD,
B.E/[Link]/ [Link] (JEE, AIEEE in IITs and NITs) Law 5-Year Integrated Course [Link] Indira Gandhi Fellowship for
Fashion Technology & Design [Link] National Defence Academy [Link] Single girl child (for UG and PG)
GATE-Graduate Aptitude Test in Engineering NET- National Eligibility Test (CSIR and UGC) [Link] Moulana Azad Fellowship
www [Link] TamilNadu Dr. Ambedkar Law University [Link] for minorities (for Ph.D)
Indian Navy – 10+2 BTech Entry Scheme Technical Entry Scheme – Army/Navy/Airforce UGC National Fellowship (for Ph.D)
CAREER GUIDANCE AFTER 12TH

Institute of Chartered Accountants of India [Link] TIFR GS - Tata Institute of Fundamental International Olympiad: for getting stipend for
Institute of Company Secretary [Link] Research Graduate School [Link] Higher Education in Science and Mathematics
Institute of Cost Accountants of India [Link] Visual Arts Degree OBC etc are available.
Institute of Banking Personal Selection IBPS [Link] [Link]
Visit website of University Grants Commission

23-12-2022 13:19:00
After PG courses
A Competitive Exams for Govt. Jobs

MPhil –Computer Science | PhD – Computer Science Airforce Common Admission Test – AFCAT | Army Education Officer Entry- AEC

12th Std - CS EM Introduction [Link] 5


Combined Defence Services –CDS | Defence Service Staff College, Nilgiris
Following are the latest topics for PhD in computer science:
Indian Defence Services | Indian Military Academy
BioInformatics and Computational Biology
Judge Advocate General Department-JAG | NCC Entry | Railway Board Examination
Capturing and Visualizing Persona Through Faces
SSC NAVY (Pilot/Observer) | SSC Tech Entry – Officers Training School
Comprehensive analysis of RNA sequencing experiments Staff Selection Examination | Tamil Nadu Public Service Commission
Designing and Evaluating Information Gathering Robots Teacher Recruitment Board | Technical Graduate Course –TGC
Digital Pathology: Diagnostic Errors, Territorial Army | Union Public Service Examination | Women Special Entry Scheme
Viewing Behavior and Image Characteristics
Embedded Systems | Game Theory | Graph Theory
Graphics and Visualization | Human Computer Interaction – HCI Computer Related Jobs
Improving Fault Tolerance and Performance of Data Center Networks
Increasing Access to Computer Science for Blind Students Applications Software Developer | Big Data Analysts
In-situ Semantic 3D Modeling Cloud Computing Programmer | College/ University Faculty
Intelligent Crowdsourcing for Natural Language Computer Programmer | Computer Teacher
Learning and Other AI Applications Computer Vocational Instructor | Computer Information Research Scientist
Learning Robust Tractable Models for Vision COMPUTER Computer Information Systems Manager | Computer Network Architect
Govt

V
SCIENCE Computer Support Specialist | Computer System Analysts
Manipulators And Manipulation In High Dimensional Spaces
Data Mining Specialist | Database Administrator
New Algorithmic Tools for Distributed Similarity Search
Information Security Analysts | Market Research Analysts
Reproducible measurements of web security and privacy Network & Computer System Administrator | Research Assistant
The Security and Privacy of Web and Mobile Advertising Systems Software Developer | User Interface Designer | Web Developer
Towards More Practical Reinforcement Learning,
with Applications to Educational Games
Research Institutions in various areas of science

Bhaba Atomic Research centre Institute of Mathematical Sciences (IMSc)


(BARC) Mumbai [Link] Chennai [Link]
CAREER GUIDANCE

BITS Pilani, [Link] Jawaharlal Nehru University (JNU) [Link]


Topics for Research after PG in Computer Studies
T
Central Universities [Link] Mumbai University, Mumbai [Link]
Chennai Mathematical Institute National Institute of Science Education and
Architectures, Compiler Optimization, and Embedded Systems. (CMI) Chennai [Link] Research (NISER), [Link]
Bioinformatics and Computational Biology | Cloud Computing Delhi University, Delhi [Link] National Institute of Technology
Hyderabad central university, (NITs) [Link]
Data Mining, Databases, and Geographical Information Systems.
Hyderabad [Link] SavithiribaiPhule Pune university,
Graphics and Visualization | High Performance Computing. Pune [Link]
IISER Educational Institutions
Human Computer Interaction | Internet of Things [Link] State Universities [Link]
Natural Language Processing | Networks, Distributed Systems, and Security. Indian Institute of Technology in Tata Institute of Fundamental Research
various places (IIT’s) [Link] (TIFR) Mumbai [Link]

23-12-2022 13:19:01
Table of Contents
Computer Science-II Year
UNIT NO. CHAPTER COMPUTER SCIENCE PAGE NO MONTH
UNIT- I 1 Function 1 June
Problem 2 Data Abstraction 11 June
Solving 3 Scoping 21 June
Techniques 4 Algorithmic Strategies 31 June
5 Python -Variables and Operators 47 July

UNIT- II 6 Control Structures 67 July


Core Python 7 Python functions 89 July
8 Strings and String manipulation 114 Aug
UNIT-III 9 Lists, Tuples, Sets and Dictionary 132 Aug
Modularity
and OOPS 10 Python Classes and objects 170 Aug

UNIT-IV 11 Database Concepts 182 Oct


Database
12 Structured Query Language (SQL) 198 Oct
concepts and
MySql 13 Python and CSV files 224 Oct
Importing C++ programs in
14 259 Oct
UNIT-V Python.
Integrating 15 Data manipulation through SQL 278 Nov
Python with
MySql and C++ Data visualization using pyplot: line
16 307 Nov
chart, pie chart and bar chart
Glossary 321
Annexure List of Python functions 327
Practical Exercises 331

E - book Assessment
VI

12th Std - CS EM Introduction [Link] 6 23-12-2022 13:19:01


CHAPTER 1
Unit I
FUNCTION

1.2 Function with respect to


Learning Objectives Programming language

After the completion of this chapter, the A function is a unit of code that is
student will be able to: often defined within a greater code structure.
Specifically, a function contains a set of
• Understand Function Specification.
code that works on many kinds of inputs,
• Parameters (and arguments). like variables, expressions and produces a
• Interface Vs Implementation. concrete output.
• Pure functions. 1.2.1 Function Specification
• Side - effects (impure functions). Let us consider the example a:= (24).
a:= (24) has an expression in it but (24)
1.1 Introduction is not itself an expression. Rather, it is a
The most important criteria in function definition. Definitions bind values
writing and evaluating the algorithm is the to names, in this case the value 24 being
time it takes to complete a task. The duration bound to the name ‘a’. Definitions are not
of computation time must be independent expressions, at the same time expressions are
of the programming language, compiler, also not treated as definitions. Definitions
and computer used. As you aware that are distinct syntactic blocks. Definitions can
algorithms are expressed using statements have expressions nested inside them, and
of a programming language. If a bulk of vice-versa.
statements to be repeated for many numbers 1.2.2 Parameters and arguments
of times then subroutines are used to finish
the task. Parameters are the variables in a
function definition and arguments are
Subroutines are the basic building the values which are passed to a function
blocks of computer programs. Subroutines definition.
are small sections of code that are used to
1. Parameter without Type
perform a particular task that can be used
repeatedly. In Programming languages these Let us see an example of a function
subroutines are called as Functions. definition:

12th Computer Science_EM Chapter [Link] 1 23-12-2022 15:42:16


When we write the type annotations
(requires: b>=0 ) for ‘a’ and ‘b’ the parentheses are
(returns: a to the power of b) mandatory. Generally we can leave out
let rec pow a b:= these annotations, because it's simpler to
if b=0 then 1 let the compiler infer them. There are times
else a * pow a (b-1) we may want to explicitly write down types.
This is useful on times when you get a type
error from the compiler that doesn't make
In the above function definition
sense. Explicitly annotating the types can
variable ‘b’ is the parameter and the value
help with debugging such an error message.
which is passed to the variable ‘b’ is the
argument. The precondition (requires) and
The syntax to define functions is close
postcondition (returns) of the function
to the mathematical usage: the definition is
is given. Note we have not mentioned any
introduced by the keyword let, followed by
types: (data types). Some language compiler
the name of the function and its arguments;
solves this type (data type) inference
then the formula that computes the image
problem algorithmically, but some require
of the argument is written after an := sign. If
the type to be mentioned.
you want to define a recursive function: use
“let rec” instead of “let”.
In the above function definition if
expression can return 1 in the then branch,
Syntax: The syntax for function definitions:
shows that as per the typing rule the
entire if expression has type int. Since the
if expression is of type ‘int’, the function's let rec fn a1 a2 ... an := k
return type also be ‘int’. ‘b’ is compared to
0 with the equality operator, so ‘b’ is also Here the ‘fn’ is used as a function
a type of ‘int’. Since ‘a’ is multiplied with name. The names ‘a1’ to ‘an’ are variables
another expression using the * operator, ‘a’ used as parameters. The keyword ‘rec’ is
must be an int. required if ‘fn’ is to be a recursive function;
otherwise it may be omitted.
2. Parameter with Type
Now let us write the same function
definition with types for some reason: Note
A function definition which call
(requires: b>=0 ) itself is called recursive function.
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int := For example: let us see an example to find
the factorial of a number.
if b=0 then 1
else a * pow a (b-1)

XII Std Computer Science 2

12th Computer Science_EM Chapter [Link] 2 23-12-2022 15:42:16


Interface is a description of all functions.
(Requires: n>= 0)
In our example, anything that "ACTS LIKE"
let rec fact n :=
a light, should have function definitions like
if n = 0 then 1 turn_on () and a turn_off (). The purpose of
else interface is to allow the computer to enforce
n ✳ fact(n-1) the properties of the class.

The syntax for function types: The difference between interface and
implementation is
x→y
x1 → x2 → y Interface Implementation
x1 → ... → xn → y
Interface just Implementation
defines what carries out the
The ‘x’ and ‘y’ are variables indicating an object can instructions defined
types. The type x → y is the type of a function do, but won’t in the interface
that gets an input of type ‘x’ and returns an actually do it
output of type ‘y’. Whereas x1 → x2 → y is
a type of a function that takes two inputs, In object oriented programs classes are
the first input is of type ‘x1’ and the second the interface and how the object is processed
input of type ‘x2’, and returns an output of and executed is the implementation.
type ‘y’. Likewise x1 → … → xn → y has
type ‘x’ as input of n arguments and ‘y’ type 1.3.1 Characteristics of interface
as output. • The class template specifies the interfaces
to enable an object to be created and
Note operated properly.
All functions are static • An object's attributes and behaviour is
definitions. There is no dynamic controlled by sending functions to the
function definitions. object.

1.3 Interface Vs Implementation For example, let's take the example of


increasing a car’s speed.
An interface is a set of action that an
object can do. For example when you press
a light switch, the light goes on, you may
not have cared how it splashed the light. In
Object Oriented Programming language, an

3 Function

12th Computer Science_EM Chapter [Link] 3 23-12-2022 15:42:16


let min x y z :=
ENGINE if x < y then
if x < z then x else z
else
if y < z then y else z
getSpeed
1.4 Pure functions

required No Pure functions are functions which


Pull Fuel
speed will give exact result when the same
arguments are passed. For example the
Yes
mathematical function sin (0) always results
Return 0. This means that every time you call the
function with the same arguments, you will
always get the same result. A function can
The person who drives the car be a pure function provided it should not
doesn't care about the internal working. To have any external variable which will alter
increase the speed of the car he just presses the behaviour of that variable.
the accelerator to get the desired behaviour.
Here the accelerator is the interface between Let us see an example
the driver (the calling / invoking object) and
the engine (the called object). let square x:=

In this case, the function call would return: x * x


be Speed (70): This is the interface.

Internally, the engine of the car is The above function square is a pure
doing all the things. It's where fuel, air, function because it will not give different
pressure, and electricity come together to results for same input.
create the power to move the vehicle. All of
There are various theoretical
these actions are separated from the driver,
advantages of having pure functions. One
who just wants to go faster. Thus we separate
advantage is that if a function is pure, then
interface from implementation.
if it is called several times with the same
Let us see a simple example, consider arguments, the compiler only needs to
the following implementation of a function actually call the function once. Let’s see an
that finds the minimum of its three example
arguments:
let length s:=
i: = 0
if i <strlen (s) then
-- Do something which doesn't affect s
++i

XII Std Computer Science 4

12th Computer Science_EM Chapter [Link] 4 23-12-2022 15:42:16


If it is compiled, strlen (s) is called Here the function Random is impure
each time and strlen needs to iterate over as it is not sure what will be the result when
the whole of ‘s’. If the compiler is smart we call the function.
enough to work out that strlen is a pure
1.4.2 Side-effects (Impure functions)
function and that ‘s’ is not updated in the
loop, then it can remove the redundant As you are aware function has side
extra calls to strlen and make the loop to effects when it has observable interaction
execute only one time. From these what we with the outside world. There are situations
can understand, strlen is a pure function our functions can become impure though
because the function takes one variable as a our goal is to make our functions pure.
parameter, and accesses it to find its length. Just to clarify remember that side effect is
This function reads external memory but not a necessary bad [Link] they
does not change it, and the value returned are useful (especially outside functional
derives from the external memory accessed. programming paradigm).
Modify variable outside a function
Note One of the most popular side effects is
Evaluation of pure modifying the variable outside of function.
functions does not cause any side
For example
effects to its output
y: = 0
1.4.1 Impure functions let inc (x: int): int:=
y: = y + x
The variables used inside the
return (y)
function may cause side effects though the
functions which are not passed with any
In the above example the value of y
arguments. In such cases the function is
get changed inside the function definition
called impure function. When a function
due to which the result will change each
depends on variables or functions outside
time. The side effect of the inc () function is
of its definition block, you can never be
it is changing the data of the external visible
sure that the function will behave the same
variable ‘y’. As you can see some side effects
every time it’s called. For example the
are quite easy to spot and some of them may
mathematical function random() will give
tricky.
different outputs for the same function call.
From all these examples and
let randomnumber :=
definitions what we can understand about
a := random() the main differences between pure and
if a > 10 then impure functions are
return: a
else
return: 10

5 Function

12th Computer Science_EM Chapter [Link] 5 23-12-2022 15:42:16


1.4.3 Chameleons of Chromeland
Pure Function Impure Function
problem using function
The return value of The return value Recall the In the Chameleons of
the pure functions of the impure Chromeland problem what you have studied
solely depends functions does in class XI. suppose two types of chameleons
on its arguments not solely depend
are equal in number. Construct an algorithm
passed. Hence, if on its arguments
you call the pure passed. Hence, that arranges meetings between these two
functions with if you call the types so that they change their color to the
the same set of impure functions third type. In the end, all should display the
arguments, you with the same same color.
will always get set of argu­ments,
the same return you might get Let us represent the number of
values. the different chameleons of each type by variables a, b
return values and c, and their initial values by A, B and C,
They do not have For example, respectively. Let a = b be the input property.
any side effects. random(), Date().
The input – output relation is a =
They do not They may modify
b = 0 and c = A + B + C. Let us name the
modify the the arguments
arguments which which are passed algorithm monochromatize. The algorithm
are passed to them to them can be specified as

monochromatize (a, b, c)
Now let’s see the example of a pure
function to determine the greatest common
-- inputs : a = A, b = B, c = C, a = b
divisor (gcd) of two positive integer numbers.
-- outputs : a = b = 0, c = A+B+C
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) In each iterative step, two chameleons
else
of the two types (equal in number) meet and
return a
change their colors to the third one. For
output
example, if A, B, C = 4, 4, 6, then the series
gcd 13 27
1
of meeting will result in
gcd 20536 7826
2 iteration a b c

0 4 4 6
In the above example ‘gcd’ is the name
of the function which recursively called till 1 3 3 8
the variable ‘b’ becomes ‘0’. Remember b
and (a mod b) are two arguments passed to 2 2 2 10
‘a’ and ‘b’ of the gcd function. 3 1 1 12

4 0 0 14

XII Std Computer Science 6

12th Computer Science_EM Chapter [Link] 6 23-12-2022 15:42:16


In each meeting, a and b each
a, b, c
decreases by 1, and c increases by 2. The
a = b, a = A, b = B, c = C
solution can be expressed as an iterative
algorithm.
True
a>0 a, b, c := a - 1, b - 1, c+2
monochromatize (a, b, c)
-- inputs : a = A, b=B, c=C, a=b False
a = b = 0, c = A + B + C
-- outputs : a = b = 0, c = A+B+C
a, b, c
while a>0
a, b, c := a-1, b-1, c+2
Now let us write this algorithm using
function
The algorithm is depicted in the flowchart
as below let rec monochromatize a b c :=
if a > 0 then
a, b, c := a-1, b-1, c+2
else
monochromatize a b c
return a, b, c

Points to remember:
• Algorithms are expressed using statements of a programming language
• Subroutines are small sections of code that are used to perform a particular task that
can be used repeatedly
• A function is a unit of code that is often defined within a greater code structure
• A function contains a set of code that works on many kinds of inputs and produces a
concrete output
• Definitions are distinct syntactic blocks
• Parameters are the variables in a function definition and arguments are the values
which are passed to a function definition through the function definition.
• When you write the type annotations the parentheses are mandatory in the function
definition
• An interface is a set of action that an object can do
• Interface just defines what an object can do, but won’t actually do it
• Implementation carries out the instructions defined in the interface
• Pure functions are functions which will give exact result when the same arguments
are passed
• The variables used inside the function may cause side effects though the functions
which are not passed with any arguments. In such cases the function is called impure
function

7 Function

12th Computer Science_EM Chapter [Link] 7 23-12-2022 15:42:16


Hands on Practice

1. Write algorithmic function definition to find the minimum among 3 numbers.


2. Write algorithmic recursive function definition to find the sum of n natural numbers.

Evaluation

Part - I
Choose the best answer (1 Mark)
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) { } (B) ( ) (C) [ ] (D) < >
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions

XII Std Computer Science 8

12th Computer Science_EM Chapter [Link] 8 23-12-2022 15:42:16


10. The functions which cause side effects to the arguments passed are called
(A) impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
Part - II

Answer the following questions (2 Marks)


1. What is a subroutine?
2. Define Function with respect to Programming language.
3. Write the inference you get from X:=(78).
4. Differentiate interface and implementation.
5. Which of the following is a normal function definition and which is recursive function
definition
i) let sum x y:
return x + y
ii) let disp :
print ‘welcome’
iii) let rec sum num:
if (num!=0) then return num + sum (num-1)
else
return num

Part - III

Answer the following questions (3 Marks)


1. Mention the characteristics of Interface.
2. Why strlen is called pure function?
3. What is the side effect of impure function. Give example.
4. Differentiate pure and impure function.

9 Function

12th Computer Science_EM Chapter [Link] 9 23-12-2022 15:42:16


Part - IV

Answer the following questions (5Marks)


1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter 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
3. Explain with example Pure and impure functions.
4. Explain with an example interface and implementation.

REFERENCES

1. Data Structures and Algorithms in Python By Michael [Link], RobertoTamassia and


Michael H. Goldwasser.
2. Data Structure and Algorithmic Thinking in Python By Narasimha Karumanchi
3. [Link]

XII Std Computer Science 10

12th Computer Science_EM Chapter [Link] 10 23-12-2022 15:42:16


CHAPTER 2
Unit I
DATA ABSTRACTION

2.2 Abstract Data Types


Learning Objectives
Abstract Data type (ADT) is a type
After the completion of this chapter, the for objects whose behavior is defined by a
student will be able to Understand set of values and operations.
• what is Abstract Data structures. The definition of ADT only mentions
• Abstract data type. what operations are to be performed but not
how these operations will be implemented. It
• Difference between concrete and abstract
does not specify how data will be organized
implementation.
in memory and what algorithms will be
• Pairs. used for implementing the operations.
• Data Abstration in Structure. It is called “abstract” because it gives an
implementation independent view. The
2.1 Data Abstraction-
process of providing only the essentials and
Introduction
hiding the details is known as abstraction.
Data abstraction is a powerful You can see that these definitions
concept in computer science that allows do not specify how these ADTs will be
programmers to treat code as objects — for represented and how the operations will be
example, car objects, pencil objects, people carried out. There can be different ways to
objects, etc. Programmers need not to worry implement an ADT, for example, the List
about how code is implemented — they have ADT can be implemented using singly linked
to just know what it does. list or doubly linked list. Similarly, stack
This is especially important when ADT and Queue ADT can be implemented
several people are doing a project. Here using lists.
project refers to the programming .With Data abstraction replicate how we
data abstraction, your group members won’t think about the world. For example, when
have to read through every line of your code you want to drive a car, you don’t need to
to understand. They can just assume that it know how the engine was built or what
does work. kind of material the tires are made of. You
Abstraction provides modularity just have to know how to diver the car. To
(modularity means splitting a program in facilitate data abstraction, you will need to
to many modules). Classes (structures) are create two types of functions: constructors
the representation for “Abstract Data Types”, and selectors.
(ADT)
11

12th Computer Science_EM Chapter [Link] 11 26-12-2022 17:25:50


2.3 constructors and selectors Notice that you don’t need to know
how these functions were implemented. You
Constructors are functions that are assuming that someone else has defined
build the abstract data type. Selectors are them for us.
functions that retrieve information from
It’s okay if the end user doesn’t know
the data type.
how functions were implemented. However,
For example, say you have an abstract the functions still have to be defined by
data type called city. This city object will someone.
hold the city’s name, and its latitude and
Let us identify the constructors and
longitude. To create a city object, you’d use a
selectors in the above code
function like
As you already know that
city:= makecity (name, lat, lon) Constructors are functions that build the
abstract data type. In the above pseudo code
To extract the information of a city
the function which creates the object of the
object, you would use functions like
city is the constructor.
• getname(city) city:= makecity (name, lat, lon)
• getlat(city)
Here makecity (name, lat, lon) is the
• getlon(city) constructor which creates the object city.
The following pseudo code will (name, lat, lon) value passed as parameter
compute the distance between two city
objects:
make city ( )
distance(city1, city2):
lt1, lg1 := getlat(city1), getlon(city1)
city
lt2, lg2 := getlat(city2), getlon(city2)
return ((lt1 - lt2)**2 + (lg1 - lg2)**2))1/2 lat lon

In the above code read distance(), Fig 1 constructor


getlat() and getlon() as functions and read
lt as latitude and lg longitude. Read := as Selectors are nothing but the
“assigned as” or “becomes” functions that retrieve information from the
data type. Therefore in the above code
lt1, lg1 := getlat(city1), getlon(city1)
• getname(city)
is read as lt1 becomes the value of • getlat(city)
getlat(city1) and lg1 becomes the value of
• getlon(city)
getlon (city1).
are the selectors because these functions
extract the information of the city object
XII Std Computer Science 12

12th Computer Science_EM Chapter [Link] 12 26-12-2022 17:25:50


city value passed as parameter city value passed as parameter city value passed as parameter

getname ( ) getlat ( ) getlon ( )

Now let us consider one more example to representation is defined as an independent


identify the constructor and selector for a part of the program.
[Link] - - as comments.
Note
- - constructor A concrete data type is a data type whose
makepoint(x, y): representation is known.
return x, y
- - selector
xcoord(point): Any program consist of two parts.
return point[0] The two parts of a program are, the part
- -selector that operates on abstract data and the part
ycoord(point): that defines a concrete representation, is
return point[1] connected by a small set of functions that
implement abstract data in terms of the
concrete representation. To illustrate this
Note technique, let us consider an example to
Data abstraction is used to define design a set of functions for manipulating
an Abstract Data Type (ADT), which is rational numbers.
a collection of constructors and selectors.
Constructors create an object, bundling Example
together different pieces of information, A rational number is a ratio of
while selectors extract individual pieces integers, and rational numbers constitute
of information from the object. an important sub-class of real numbers.
A rational number such as 8/3 or 19/23 is
typically written as:
2.4 Representation of Abstract
datatype using Rational <numerator>/<denominator>
numbers
where both the <numerator> and
The basic idea of data abstraction is <denominator> are placeholders for integer
to structure programs so that they operate values. Both parts are needed to exactly
on abstract data. That is, our programs characterize the value of the rational number.
should use data in such a way, as to make Actually dividing integers produces a float
as few assumptions about the data as approximation, losing the exact precision of
possible. At the same time, a concrete data integers.

13 Data Abstraction

12th Computer Science_EM Chapter [Link] 13 26-12-2022 17:25:50


8/3 =2.6666666666666665 component. Let us further assume that the
However, you can create an exact constructor and selectors are also available.
representation for rational numbers by
We are using here a powerful strategy
combining together the numerator and
for designing programs: 'wishful thinking'.
denominator.
We haven't yet said how a rational number
As we know from using functional is represented, or how the constructor and
abstractions, we can start programming selectors should be implemented.
productively before you have an
implementation of some parts of our
Note
program. Let us begin by assuming that
you already have a way of constructing a Wishful Thinking is the formation
rational number from a numerator and a of beliefs and making decisions according
denominator. You also assume that, given to what might be pleasing to imagine
a rational number, you have a way of instead of by appealing to reality.
selecting its numerator and its denominator

Example: An ADT for rational numbers


- - constructor
- - constructs a rational number with numerator x, denominator y
rational(x, y)
- - selector
numer(x) → returns the numerator of rational number x
denom(y) → returns the denominator of rational number y

In the above example, rational () 2.5 Lists,Tuples


is the constructor numer () and denom ()
both are selectors. In this case, selectors To implement the data abstraction,
are declared inside the constructor but not Programming languages like Python
defined. provides a compound structure called Pair
The pseudo code for the which is made up of list or Tuple. The first
representation of the rational number using way to implement pairs is with the List
the above constructor and selector is construct.

x,y:=8,3 2.5.1 List


rational(x,y) List is constructed by placing
numer(x)/denom(y) expressions within square brackets
- - output : 2.6666666666666665 separated by commas. Such an expression
is called a list literal. List can store multiple
values. Each value can be of any type and
can even be another list.

XII Std Computer Science 14

12th Computer Science_EM Chapter [Link] 14 26-12-2022 17:25:50


Example for List [10, 20]. rational(n, d):
The elements of a list can be accessed return [n, d]
in two ways. The first way is via our familiar numer(x):
method of multiple assignment, which return x[0]
unpacks a list into its elements and binds denom(x):
each element to a different name. return x[1]
lst := [10, 20]
x, y := lst 2.5.2 Tuple

In the above example x will become10 Remember, a pair is a compound


and y will become 20. data type that holds two other pieces of data.
So far,we have provided you with two ways
A second method for accessing the of representing the pair data type. The first
elements in a list is by the element selection way is using List construct and the second
operator. Unlike a list literal, a square- way with the tuple construct.
brackets expression directly following
another expression does not evaluate to a A tuple is a comma-separated
list value, but instead selects an element sequence of values surrounded with
from the value of the preceding expression. parentheses. Tuple is similar to a list. The
difference between the two is that you
lst[0] cannot change the elements of a tuple once
10 it is assigned whereas in a list, elements can
lst[1] be changed.
20
Example colour= ('red', 'blue', 'Green')
In both the example mentioned above
mathematically we can represent list similar Representation of Tuple as a Pair
to a set.
nums := (1, 2)
lst[(0, 10), (1, 20)] - where nums[0]
1
(0, 10) (1, 20)
nums[1]
2
Index position value Index position value

Any way of bundling two values Note the square bracket notation is
together into one can be considered as a used to access the data you stored in the pair.
pair. Lists are a common method to do so. To access the first element with nums[0] and
Therefore List can be called as Pairs. the second with nums[1].
Representing Rational Numbers Using
List
You can now represent a rational
number as a pair of two integers in pseudo
code : a numerator and a denominator.
15 Data Abstraction

12th Computer Science_EM Chapter [Link] 15 26-12-2022 17:25:50


2.6 Data Abstraction in person:=['Padmashri', 'Baskar', '994-
Structure 222-1234', 'compsci@[Link]']

List allow data abstraction in that but such a representation doesn't explicitly
you can give a name to a set of memory specify what each part represents.
cells. For instance, in the game Mastermind,
you must keep track of a list of four colors For this problem instead of using a
that the player guesses. Instead of using four list, you can use the structure construct (In
separate variables (color1, color2, color3, OOP languages it's called class construct)
and color4) you can use a single variable to represent multi-part objects where each
‘Predict’, e.g., part is named (given a name). Consider the
following pseudo code:
Predict:=['red', 'blue', 'green', 'green']
class Person:
What lists do not allow us to do
creation( )
is name the various parts of a multi- item
object. In the case of a Predict, you don't firstName := " "
really need to name the parts: lastName := " "
id := " "
using an index to get to each color suffices.
email := " "
But in the case of something more
complex, like a person, we have a multi- item The new data type Person is pictorially
object where each 'item' is a named thing: represented as
the firstName, the lastName, the id, and the
email. One could use a list to represent a
person:

Person class name (multi part data representation)

creation ( )
function belonging to the new datatype

}
first Name

last Name variable (field) beloging to the new


datatype
id

email

XII Std Computer Science 16

12th Computer Science_EM Chapter [Link] 16 26-12-2022 17:25:50


Let main() contains

p1:=Person() statement creates the object.


firstName := " Padmashri " setting a field called firstName with value Padmashri
lastName :="Baskar" setting a field called lastName with value Baskar
id :="994-222-1234" setting a field called id value 994-222-1234
email:="compsci@[Link]" setting a field called email with value compsci@[Link]
- - output of firstName : Padmashri

The class (structure) construct So far, you've seen how a class defines
defines the form for multi-part objects that a data abstraction by grouping related data
represent a person. Its definition adds a new items. A class is not just data, it has functions
data type, in this case a type named Person. defined within it. We say such functions are
Once defined, we can create new variables subordinate to the class because their job is
(instances) of the type. In this example to do things with the data of the class, e.g.,
Person is referred to as a class or a type, to modify or analyze the data of a Person
while p1 is referred to as an object or an object.
instance. You can think of class Person as a Therefore we can define a class as
cookie cutter, and p1 as a particular cookie. bundled data and the functions that work
Using the cookie cutter you can make many on that data. From All the above example
cookies. Same way using class you can create and explanation one can conclude the
many objects of that type. beauty of data abstraction is that we can
treat complex data in a very simple way.
Points to remember:
• Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by
a set of value and a set of operations.
• The definition of ADT only mentions what operations are to be performed but not
how these operations will be implemented.
• ADT does not specify how data will be organized in memory and what algorithms
will be used for implementing the operations
• Constructors are functions that build the abstract data type.
• Selectors are functions that retrieve information from the data type.
• Concrete data types or structures (CDT's) are direct implementations of a relatively
simple concept.
• Abstract Data Types (ADT's) offer a high level view (and use) of a concept independent
of its implementation.

17 Data Abstraction

12th Computer Science_EM Chapter [Link] 17 26-12-2022 17:25:50


Points to remember:
• A concrete data type is a data type whose representation is known and in abstract data
type the representation of a data type is unknown
• Pair is a compound structure which is made up of list or Tuple
• List is constructed by placing expressions within square brackets separated by commas
• The elements of a list can be accessed in two ways. The first way is via multiple
assignment and the second method is by the element selection operator
• Bundling two values together into one can be considered as a pair
• List does not allow to name the various parts of a multi-item object.

Evaluation
Part - I

Choose the best answer (1 Mark)


1. Which of the following functions that build the abstract data type ?
(A) Constructors (B) Destructors (C) recursive (D)Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
7. Which of the following is a compound structure?
(A) Pair (B) Triplet (C) single (D) quadrat

XII Std Computer Science 18

12th Computer Science_EM Chapter [Link] 18 26-12-2022 17:25:50


8. Bundling two values together into one can be considered as
(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats

Part - II

Answer the following questions (2 Marks)


1. What is abstract data type?
2. Differentiate constructors and selectors.
3. What is a Pair? Give an example.
4. What is a List? Give an example.
5. What is a Tuple? Give an example.

Part - III

Answer the following questions (3 Marks)


1. Differentiate Concrete data type and abstract datatype.
2. Which strategy is used for program designing? Define that Strategy.
3. Identify Which of the following are constructors and selectors?
(a) N1:=number() (b) accetnum(n1) (c) displaynum(n1)
(d) eval(a/b) (e) x,y:= makeslope (m), makeslope(n)
(f) display()
4. What are the different ways to access the elements of a list. Give example.
5. Identify Which of the following are List, Tuple and class ?
(a) arr [1, 2, 34] (b) arr (1, 2, 34) (c) student [rno, name, mark]
(d) day:= (‘sun’, ‘mon’, ‘tue’, ‘wed’) (e) x:= [2, 5, 6.5, [5, 6], 8.2]
(f) employee [eno, ename, esal, eaddress]

19 Data Abstraction

12th Computer Science_EM Chapter [Link] 19 26-12-2022 17:25:50


Part - IV

Answer the following questions (5Marks)


1. How will you facilitate data abstraction. Explain it with suitable example
2. What is a List? Why List can be called as Pairs. Explain with suitable example
3. How will you access the multi-item. Explain with example.

Reference Books
1. Data structure and algorithmic thinking with python by narasimha karumanchi
2. sign and analysis of algorithms by s sridhar
3. Data Structures and Algorithms in Python by Goodrich, Tamassia & Goldwasser
4. [Link]

XII Std Computer Science 20

12th Computer Science_EM Chapter [Link] 20 26-12-2022 17:25:50


CHAPTER 3
Unit I
SCOPING

Learning Objectives Note


The process of binding a
After the completion of this chapter, the variable name with an object is called
student will be able to mapping. = (equal to sign) is used in
• Understand what is Scoping programming languages to map the
variable and object.
• Able to implement the LEGB rule
• Understand what is module Programming languages keeps track
• Understand the implementation of of all these mappings with namespaces.
access control in programming language Namespaces are containers for mapping
names of variables to objects. You can think
of them as dictionaries, containing list
3.1 Introduction of words and its meanings. The words are
mapped with its meaning in dictionaries
Scope refers to the accessibity of a
whereas names are mapped with objects
variable with in one part of a program to
(name = object) in programming language.
another part of the same program.
This allows access to objects by names you
choose to assign to them.
3.2 Variable Scope In the following example, a is first
To understand the scope of variables mapped to the integer 5. In this case, a is the
in a programming language, it is important variable name, while the integer value 5 is
to learn about what variables really are. the object.
Essentially, they're addresses to an object Then, b is set equal to a. This actually
in memory. When you assign a variable means that b is now bound to the same
with := to an instance (object), you're integer value as a, which is 5.
binding (or mapping) the variable to that
instance. Multiple variables can be mapped 1. a:=5
to the same instance.
2. b:=a

21

12th Computer Science_EM Chapter [Link] 21 26-12-2022 17:27:47

You might also like