By QB365 on 31 Dec, 2022
QB365 provides a detailed and simple solution for every Possible Questions in Class 12 Computer Science Subject - Important 5 Mark English Medium. It will help Students to get more practice questions, Students can Practice these question papers in addition to score best marks.
12th Standard
Computer Science
Answer all the following questions.
What are called Parameters and write a note on
(i) Parameter without Type
(ii) Parameter with Type
How will you facilitate data abstraction. Explain it with suitable example.
What is a List? Why List can be called as Pairs. Explain with suitable example.
Explain the types of scopes for variable or LEGB rule with example.
Write any five benefits in using modular programming.
Discuss about Linear search algorithm.
Explain the Bubble sort algorithm with example.
Describe in detail the procedure Script mode programming.
Explain input() and print() functions with examples.
Write a detail note on for loop.
Write a program to display all 3 digit odd numbers.
Explain the different types of function with an example.
Write a Python code to find the L.C.M. of two numbers.
Explain about string operators in python with suitable example.
What is the purpose of range( )? Explain with an example.
Explain the different set operations supported by python with suitable example.
Write a menu driven program to add or delete stationary items. You should use dictionary to store items and the brand.
Explain the different operators in Relational algebra with suitable examples.
Write the different types of constraints and their functions.
Write a Python program to write a CSV File with custom quotes.
Write the syntax for getopt( ) and explain its arguments and return values.
hat is the use of HAVING clause. Give an example python script
Explain the various buttons in a matplotlib window.
What are called Parameters and write a note on Parameter with Type.
What is List? Discuss about the method by which the elements of list can be accessed. Give an example.
Explain in detail about the scope, variable scope and lifetime of a variable.
Explain the insertion sort algorithm with an example.
Write a program in python to display the following output.
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Write a python program to find Fibonacci series of n terms using recursion.
Write a program to create a list of numbers in the range 1 to 10. Then delete all the odd numbers from the list and print the final list.
Answers
Parameters and arguments:
Parameters are the variable in a function definition and arguments are the values which are passed to a function definition
(i) Parameter without Type: Let us see an example of a function,definition :
(requires: b >=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a*powa(b-1)
(i) In the above function definition variable 'b' is the parameter and the value which is passed to the variable 'b' is the argument. The precondition (requires) and postcondition (returns) of the function is given.
(ii) Note we have not mentioned any types (data types). Some language computer solves this type (data type) inference problem algorithmically, but some require the type to be mentioned.
(iii) In, the above function deinition if expression can return 1 in the then branch, shows that as per the typing rule the entire if expression has type int
(iv) Since the if expression is of type 'int', the function's return type also be int. 'b' is compared to 0 with the equality operator. so 'b' is also a type of int: Since 'a' is multiplied with another expression using the operator, 'a' must be an int.
(ii) Parameter with Type: Now let us write the same function definition with types for some reasons:
(requires: b > 0 )
(returns: a to the power of b )
let rec pow (a:int) (b:int): int :=
if b=0 then 1
n else a * pow b (a-1)
(i) When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory. Generally, we can leave out these annotations, because it's simpler to let the compiler infer them.
(ii) There are times 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 sense. Explicitly annotating the types can help with debugging such an error message.
(iii) The syntax to define functions is close to the mathematical usage: the definition is introduced by the keyword let followed by the name of the function and its arguments; then the formula that computes the image of the argumentis written atter an := sign. If you want to define a recursive function: use "let rec" instead of "let"
Syntax:The syntax for function detinitions: let irec fn al a2 ... an := k
(iv) Here the 'fn' is used as a function name. The nanmes 'a1' to 'an'are variables used as parameters. The keyword 'rec' is required if 'fn' is to be a recursive function; otherwise it may be omitted.
Data abstraction is used to define an Abstract Data Type (ADT), which is a collection of constructors and selectors. T facilitate data abstraction,you will need to create two types of functions : Constructors and Selectors.
Constructors :
(i) Constructors are functions that build the abstract data type.
(ii) Constructors create an object, bundling together different pieces of information.
(iii) For example, say you have an abstract data type called city.
(iv) This city object will hold the city's name, and its latitude and longitude.
(v) To create a city object, you'd use a function like city = makecity (name, lat, lon).
(vi) Here makecity (name, lat, lon) is the constructor which creates the object city.
Selectors :
(i) Selectors are functions that retrieve information from the data type.
(ii) Selectors extract individual pieces of information fromn the object.
(iii) To extract the information of a city object, you wouldused functions like
getname(city)
getlat(city)
getlon(city)
These are the selectors because these functions extract the information of the city object.
List :
(i) List is constructed by placing expressions within square brackets 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.
Example for List [10, 20].
(ii) The elenments of a list can be accessed in two ways. The first way is via our familiar method of multiple assignment, which unpacks a list into its elements and binds each elenment to a different name.
Ist := [10, 20]
x, y = lst
(iii) In the above example x will become l0 and y will become 20. A second method for accessing the elements in a list is by the element selection operator.
(iv) Unlike a list literal, a square-brackets expression directly following another expression does not evaluate to a list value, but instead selects an element from the value of the preceding expression.
lst [0]
10
Ist [1]
20
(v) In both the example mentioned above mathematically we can represent list similar to a set.
Pair :
Any way of bundling two values together into one can be considered as a pair. Lists are a common methodto do so. Therefore List can be called as Pairs.
Types of Variable Scope:
There are 4 types of Variable Scope, let's discuss them one by one:
Local Scope:
(i) 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.
Look at this example
1. Disp(): 2. a:=7 3. print a 4. Disp() |
Entire program |
Output of the Program 7 |
(ii) On execution of the above code the variable a displays the value 7, because it is defined and available in the local scope.
Global Scope:
(i) A variable which is declared outside of all the functions in a program is known as global variable.
(ii) This means, global variable can be accessed inside or outside of all the functions in a program.
Example:
1. a:=10 2. Disp(): 3. a:=7 4. print a 5. Disp() 6. print a |
Entire program |
Output of the Program 7 10 |
(iii) On execution of the above code the variable 'a' which is defined inside the function displays the value 7 for the function call Disp() and then it displays 10; because a is defined in global scope.
Enclosed Scope:
(i) All programming languages permit functions to be nested. A function (method) with in another function is called nested function.
(ii) 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.
(iii) When a compiler or interpreter search for a variable in a program, it first search Local, and then search Enclosing scopes. Consider
the following example:
1. Disp(): 2. a:=10 3. Disp1() 4. print a 5. Disp1() 6. print a 7. Disp() |
Entire Program |
Output of the Program 10 10 |
(iv) In the above example Disp1( ) is defined with in Disp( ). The variable 'a' defined in Disp( ) can be even used by Disp1( ) because it is also a member of Disp( ).
Built-in Scope:
(i) The built-in scope has all the names that are pre-loaded into the program scope when we start the compiler or interpreter.
(ii) Any variable or function which is defined in the modules of a programming language has Built-in or module scope. They are loaded as soon as the library files are imported to the program.Consider the following example.
Library files associated with the software |
LEGB rule :
The LEGB rule is used to decide the order in which the scopes are to be searched
for scope resolution. The scopes are listed below in terms of hierarchy (highest to
lowest).
(i) Less code to be written.
(ii) A single procedure can be developed for reuse, eliminating the need to retype the code many times.
(iii) Programs can be designed more easily because a small teana deals with only a
small part of the entire code.
(iv) Modular programming allowS many programmers to collaborate on the same
application.
(v) The code is stored across multiple files.
(vi) Code is short, sirnple and easy to understand.
(vii) Errors can easily be identified, as they are localized to a subroutine or function.
(viii) The same code can be used in man applications.
(ix) The scoping of variables can easily be controlled.
(i) Linear search also called sequential search is a sequential method for finding a particular value in a list.
(ii) This method checks the search element with each element in sequence until the desired element is found or the list is exhausted. In this searching algorithm, list need not be ordered.
procedure :
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the list.
(i) If the values do not match, move on to the next array element.
(ii) If the values match, display the current index and value of the array.
3. If no match is found, display the search element not found.
(iii) To search the number 25 in the array given below, a linear search will go step by step in a sequential order starting from the first element in the given array if the search element is found that index is returned otherwise the search is continued till the last index of the array. In this example number 25 is found at index number 3.
index | 0 | 1 | 2 | 3 | 4 |
values | 10 | 12 | 20 | 25 | 30 |
Example 1:
Input: values[] = {5, 34, 65, 12, 77, 35)
target = 77
Output: 4
Example 2:
Input: values[] = [101, 392, 1, 54, 32, 22, 90, 93) target = 200
Output: -1 (not found)
Bubble sort algorithm:
(i) Bubble sort algorithm simple sorting algorithm. 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.
(ii) This comparison and passed to be continued until no swaps are needed, which indicates that the list of values stored in an array is sorted. The algorithm is a comparison sort, is named for the way smaller elements "bubble" to the top of the list.
(iii) Although the algorithm is simple, it is too slow and less efficient when compared to insertion sort and other sorting methods.
(iv) Assume list is an array of n elements. The swap function swaps the values of the given array elements.
Procedure :
(i) Start with the first element i.e., index = 0, compare the current element with the next element of the array.
(ii) If the current element is greater than the next element of the array, swap them.
(iii) If the current element is less than the next or right side of the element, move to the next element. Go to Step 1 and repeat until the end of the index is reached.
(iv) 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.
(v) The above pictorial example is for iteration-d. Similarly, remaining iteration can be done. The final iteration will give the sorted array. 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 |
A script is a text file containing the Python statements. Python Scripts are reusable code. Once the script is created, it can be executed6again and again without retyping. The Scripts are editable
i) Creating Scripts in Python:
1. Choose File → New File or press Ctrl + N in Python shell window.
2. An untitled blank script text editor will be displayed on screen
3. Type the following code in script editor.
a = 100
b= 350
C = a + b
print ("The sum=", c)
ii) Saving Python script:
1. Choose File → Save or press Ctrl+S.
2. Now, Save As dialog box appears on the screen.
3. In the Sare As dialog box, select the location where you want to save your Python code, and type the File name in File Name box. Python files are by default saved will extension • py. Thus, while creating Python Scripts using Pyrhons script editor, no need to specify the file extension.
4. Hinallyiclick save button to save your python script.
iii) Exccuthon Python Script:
1. Choose Run → Run module or Press F5.
2. If your code has any error, it will be shown in red color in the IDLE window, and Python describes the type of error occurred. To correct the errors, go back to Script editor, make corrections, save the file using Ctrl +s or File → Save and execute il again.
3, For all error line code, the output will appear in the IDLL window of Python.
1. The print () Function:
ln Python, the print() function is used to display result on the screen. The syntax for print ( ) is as follows:
Example:
print ("String to be displayed as output")
print (variable)
print ("String to be displayed as output", variable)
print ("String1", variable, "string 2", variable, "String 3",....)
Example:
>>> print("Welcome to python Programming'")
welcome to Python Programoming
>>>x = 5
>>> y = 6
>>> z= X+Y
>>> print (z)
>>> print ("The sum =", z)
The sum = 11
>>>print ("The sum of", x, "and", y, "is", z)
The sum of 5 and 6 is 11.
The print () evaluates the expression before printing it on the monitor. The print () displays an entire statement which is specified within print(). Comma(,) is used as a separator in print () to print more than one item.
input () function:
In Python, input) function is used to accept data as input at run time. The syntax for input () function is
Syntax:
Variable = input ("prompt String')
Where, prompt string in the Syntax is a statement or message to the user, to knowwhat input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the input device. The input() takes whatever is typed from the Keyboard and stores the entered data in the given Variable. If prompt string is not given in input() no message is displayed on the screen, then, the user will not know what is to be typed as input.
Example 1:
input () with prompt String
>>>City=input ("Enter your city:")
Enter your city: Madurai
>>>print ("I am from", city)
I am from Madurai
Example 2:
input() without prompt string
>>> city = input ()
Rajarajan
>>>print ("I am from", city)
I am from Rajarajan
in Example 2, the input () is not having any pronmpt string, thus the user will not know what is to be typed as input. If the user inputs irrelevant data as given in the above example then the output will be unexpected. So, to make your program more interactive, provide prompt string with input (). The input () accepts all data as string or characters but not as numbers. Ifa numerical value is entered, the input values should be explicitly converted into numeric data type. The int) function is used to convert string data as integer data explicitly.
Example 3:
X=int (input ("Enter Number 1:"))
Y= int (input ("Enter Number 2:" ))
print ("The Sum =", x + y)
Output:
Enter Number 1: 34
Enter Number 2:56
The Sum =90.
(i) for loop : The for loop usually known as a definite loop, because the programmer knows exactly how many times the loop will be executed.
(ii) Syntax:
for counter_variable in sequence:
statements - block 1
[else: # optional block
statements - block 2]
(iii) The for ... in statement is a looping statement used in Python to iterate over a sequence of objects, i.e., it goes through each item in a sequence. Here the sequence is the collection of ordered or unordered values or even a string.
(iv) range (): The range() is a built-in function,to generate series of values between two numeric intervals
(iv) The syntax of range() follows :
range (start, stop, [step])
Where,
start - refers to the initial value
stop - refers to the final values
step - refers to increment value, this is optional part.
Examples for range( ):
range (1,30,1) - will start the range of values from 1 and end at 29
range (2,30,2) - will start the range of values from 2 and end at 28
range (30,3,-3) - will start the range of values from 30 and end at 6.
range (20) - will consider this value 20 as the end value and starts the range count from 0 to 19
Example :
# Program to illustrate the use of for loop - to print single digit even number
for i in range (2,10,2):
print (i, end=' ')
Output :
2 4 6 8
for i in range (100, 1000):
if a%2==1:
print b
Output :
101,103,105,107,...........,997,999
Functions are named blocks of code that are designed to do one specific job.
Types of Functions :
(i) User-defined Functions
(ii) Built-in Functions
(iii) Lambda Functions
(iv) Recursion Function
User defined functions:
1. Functions defined by the users themselves are called user defined function.
2. Functions must be defined, to create and use certain functionality.
3.Function blocks begin with the keyword "def" followed by function name and parenthesis ().
Syntax:
def
return
def hello ():
print ("hello Python")
return
Built-in function: Functions which are using Python libraries are called Built-in function.
x = 20
y = 23.2
print('x=',abs(x))
print ('y=', abs(y))
Output:
x = 20
y = 23.2
Lambda function :
1. In Python, anonymous function is a function that is defined without a name.
2. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
3.Hence anonymous functions are also called as lambda functions.
Example:
Sum =lambda arg1, arg 2: arg 1 + arg 2
print ("The sum is:", sum (30,40))
print ("The sum is:", sum (-30,40))
Output:
The sum is: 70
The sum is: 10
Recursion Function: Function that calls itself is known as recursive.
Overview of how recursive function works :
(a) Recursive function is called by some external code.
(b) If the base condition is met then the program gives meaningful output and exits.
(c) Otherwise, function does some required processing and then calls itself to continue recursion.
Example:
def fact(n):
if n==0:
return 1
else:
return n* fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
Program:
def lcm(x, y):
if x>y:
greater = x
else:
greater = y
while (True):
if ((greater % x == 0) and (greater % y ==0))
lcm = greater
break
greater + = 1
return lcm
a = int (input ("Enter the first number:"))
b = int (input ("Enter the second number: "))
print ("The L.C.M of", a, "and", b, "is", lcm (a, b))
[OR]
Method II: (without using functions)
a = int (input ("Enter the first number:"))
b = int (input ("Enter the second number:"))
if a>b:
mini a
else:
min 1 = b
while (1):
if (min 1% a 0 and mini 1% b=0):
print ("LCM is:", mini)
break
mini = min 1+1
Output:
Enter the first number: 15
Enter the second number: 20
LCM is: 60
String Operators:
Python provides the following operators for string operations. These operators are useful to manipulate string.
(i) Concatenation (+):
Joining of two or more strings is called as Concatenation. The plus (+) operator is used to concatenate strings in python.
Example:
>>> "welcome" + "Python"
'welcome python'
(ii) Append (+ =):
Adding more strings at the end of an existing string is known as append. The operator += is used to append a new string with an existing string.
Example:
>>> str1 = "welcome to"
>>> str1 + = "Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating (*):
The multiplication operator (*) is used to display a string in multiple number of times.
Example:
>>> str1= "welcome "
>>> print (str1 *4)
Welcome Welcome Welcome Welcome
(iv) String slicing:
Slice is a substring of a main string.
A substring can be taken from the original string by using [ ] operator and index or subscript values. Thus [ ] is also known as slicing operator. Using slice operator, we have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the string. Python takes the end value less than one from the actual index specified.
Example: I
Slice a single character from a string
>>>str 1 = "THIRUKKURAL"
>>>print (str 1 [0])
T
(v) Stride when slicing string:
Example :
>>>str1 = "Welcome to learn python"
>>>print(str1[::-2])
Output :
nhy re teolW
The range( ) is a function used to generate a series of values in Python. Using range( ) function, you can create list with series of values. The range( ) function has three arguments.
Syntax:
range (start value, end value, step value)
where,
(i) start value - beginning value of series. Zero is the default beginning value.
(ii) end value - upper limit of series. Python takes the ending value as upper limit - l.
(iii) step value - It is an optional argument, which is used to generate different interval of values.
Example:
Generating whole numbers upto 10.
for x in range (1,11):
print(x)
Output:
1
2
3
4
5
6
7
8
9
10
Creating a list with series of values :
(i) Using the range( ) function, a list can be created with series of values, To convert the result of range( ) function into list, one more function called list ( ). The list ( ) function makes the result of range ( ) as a ist.
(ii) Syntax: List_Varibale = list ( range ( ))
(iii) Example
Generating first 10 even numbers
for x in range (2, 11, 2):
print (x)
Output:
2
4
6
8
10
(iv) In the above code, list( ) function takes the result of range( ) as Even_List elements. Thus, Even_List list has the elements of first five even numbers. Similarly, we can create any serie of values using range( ) function. The following example explains how to create a list with squares of first 10 natural numbers.
Example : Generating squares of first 10 natural numbers
for x in range(1,11) :
S=x**2
squares.append(s)
print (squares)
Output : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
The python supports the set operations such as Union, Intersection, difference and Symmetric difference.
i) Union:
It includes all elements from two or more sets
In python, the operator Iis used to union of two sets. The function union ( ) is also used to join two sets in python.
Example:
Program to Join (Union) two sets using union operator
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A l set_B
print (U _set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
Example:
Program to Join (Union) two sets using union function.
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_ U=set_ A.Union(set_ B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}
ii) Intersection:
(i) It includes the common elements in two sets
The operator & is used to intersect two sets in python. The function intersection( ) is also used to intersect two sets in python.
Example:
Program to insert two sets using intersection operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
Example:
Program to insect two sets using intersection function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print( set_A.intersection(set_B))
Output:
{'A', 'D'}
iii) Difference
It includes all elements that are in first set (say set A) but not in the second set (say set B)
The minus (-) operator is used to difference set operation in python. The function difference() is also sed to difference operation.
Example:
Program to difference of two sets using minus operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set B)
Output
{2,4}
Example:
Program to difference of two sets using difference function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference( set_B))
Output:
{2,4}
iv) Symmetric difference:
It includes all the elements that are in two sets (say sets A and B) but not the one that are common to two sets.
The caret (^) operator is used to symmetric difference set operation in python. The function symmetric_difference( ) is also used to do the same operation.
Example:
Program to symmetric difference of two sets using caret operator
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
Example:
Program to difference of two sets using symmetric difference function
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print( se_A.symmetric_ difference (set_B))
Output:
{2, 4, 'B', 'C'}
class Mystore:
_prod_code = [ ]
_prod_name = [ ]
_cost price = [ ]
_prod quant = [ ]
def getdata(self):
selt.p= int (input ("Enter no. of products you need to store:"))
for x in range (self.p):
self._prod_code. append (int (input ("Enter Product Code:")))
self._prod_name. append (str (input ("Enter Product Name:"))
self._ cost_price. append (int (input ("Enter cost price:"))
def display (self):
print ("stock in stores")
print ("---------------------")
print ("Product Code\t Product name\t cost price")
print ("------------------")
for x in range (self.p):
print (self._prod_code [x], "\t\t", self._prod_name [x], "It \t", self._cost price [x])
print ("------------------------------")
def print_bill (self):
total_price =0
for x in range (self.p):
q= int(input("Enter the quantity for the product code %d:" %self._prod_code [x]))
self. Prod_quant.append (q)
total_price = total_price + self. _cost_price|x]* self._prod_quant [x]
print ("Invoice Receipt")
print ("---------------")
print ("Product Code\t Product Name\t Cost Price\t Quantity\t Total Amount")
print ("----------------")
for x in range (self.p):
print (self._Prod_code [x), "\t \t", self_prod-name[x], "\t \t",
self._cost_price[x], "\t \t", self._prod-quant [x], "\t \t",
self._prod_quant[x]*self._cost price [x])
print ("-------------------")
print ("Total Amount =", total_price")
S=Mystore ()
S.getdata ()
S.display ()
S.print_bill ()
Output:
Enter no. of products you need to store: 5
Enter Product code: 101
Enter Product Name: Notebook
Enter cost price: 25
Enter Product code: 201
Enter Product Name: pencil
Enter cost price: 35
Enter Product code: 301
Enter Product Name: Pen
Enter cost price: 35
Enter Product code: 401
Enter Product Name: Colour Pencils
Enter cost price: 50
Enter Product code: 501
Enter Product Name: Sketches
Enter cost price: 120
Stock in stores
Product Code | Product Name | Cost Price |
101 | Notebook | 25 |
201 | Pencil | 35 |
301 | Pen | 35 |
401 | Colour pencils | 50 |
501 | Sketches | 120 |
Enter the quantity for the product code 101:10
Enter the quantity for the product code 201:15
Enter the quantity for the product code 301:10
Enter the quantity for the product code 401:20
Enter the quantity for the product code 501:10
Invoice Receipt
Product Code | Product Name | Cost Price | Quantity | Total Amount |
101 | Notebook | 25 | 10 | 250 |
201 | Pencil | 35 | 15 | 525 |
301 | Pen | 35 | 10 | 350 |
401 | Colour pencils | 50 | 20 | 1000 |
501 | Sketches | 120 | 10 | 1200 |
Total amount = 3325 |
Relational Algebra is divided into various groups
Unary Relational Operations.
(i) SELECT (symbol: σ)
(ii) PROJECT ( symbol: π)
Relational Algebra Operations from Set Theory:
(i) UNION (U)
(ii) INTERSECTION (∩)
(iii) DIFFERENCE (-)
(iv) CARTESIAN PRODUCT (X)
SELECT (symbol: σ)
(i) General from σ (R) with a relation R and a condition C on the attributes of R
(ii) The SELECT operation is used for selecting a subset with tuples according to a given condition.
(iii) Select filters out all tuples that do not satisfy C
STUDENT:
Studio | Name | Course | Year |
---|---|---|---|
CS1 | Kannan | Big Data | II |
CS2 | Gowri Shankar | R language | I |
CS3 | Lenin | Big Data | I |
CS4 | Padmaja | Python Programming | I |
σ course = "Big Data" (STUDENT)
Studio | Name | Course | Year |
---|---|---|---|
CS1 | Kannan | Big Data | II |
2 | Lenin | Big Data | I |
PROJECT (symbol: II)
(i) The projection eliminates all attributes of the input relation but those mentioned in the projection list.
(ii) The projection method defines a relation that contains a vertical subset of Relation.
Example: 1
IIcourse (STUDENT)
Result:
Course |
Big Data |
R language |
Python Programming |
Example 2
IIstudent,course (STUDENT)
Result:
Stud no | Course |
CS1 | Big Data |
CS2 | R language |
CS3 | Big Data |
CS4 | Python Programming |
UNION (Symbol: U)
(i) It includes all tuples that are in tables A or in B. It also eliminates duplicates. Set A Union Set B would be expressed as A U B
Example 3:
Table A | |
---|---|
Studio | Name |
CS1 | Kannan |
CS2 | Lenin |
CS3 | Padmaja |
Table A | |
---|---|
Studio | Name |
CS1 | Kannan |
CS2 | Gowrishakaran |
CS3 | Lenin |
Result:
Table A | |
---|---|
Studio | Name |
CS1 | Kannan |
CS2 | Gowri Shakaran |
CS3 | Lenin |
CS4 | Padmaja |
SET DIFFERENCE (Symbol: -)
(i) The result of A - B, is a relation which includes all tuples that are in A but not in B.
(ii) The attribute name of A has to match with the attribute name in B.
Example: 4
using Table B Example 3
Result:
Table A - B | |
---|---|
CS4 | Padmaja |
INTERSECTION (symbol: ∩) A ∩ B:
(i) Defines a relation consisting of a set of all tuple that are in both in A and B. However, A and.B must be union-compatible.
Example: 5
Using Table in Example 3
Result:
Table A - B | |
---|---|
CS1 | Kannan |
CS3 | Lenin |
PRODUCT OR CARTESIAN PRODUCT (Symbol: X)
(i) Cross product is a way of combining two relations. The resulting relation contains, both relations being combined.
(ii) A x B means A times B, where the relation A and B have different attributes.
(iii) This type of operation is helpful to merge columns from two relations.
Constraints ensure database integrity, therefore known as database integrity constraints. The different type of constraints are:
1. Unique Constraint:
(i) This constraint ensures that no two rows have the same value in the specified columns. For example UNIQUE constraint applied on Admno of student table ensures that no two students have the same admission number and the constraint can be used as:
CREATE TABLE Student:
(
Admno integer NOT NULL UNIQUE,
Name char (20) NOT NULL,
Gender char (1),
Age integer,
Place char (10),
);
(ii) The UNIQUE constraint can be applied only to fields that have also been declared as NOT NULL.
(iii) When two constraints are applied on a single field, it is known as multiple constraints. In the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno, the constraints are separated by a space and the end of the field definition a comma(,) is added. By adding these two constraints the field Admno must take some value ie. will not be NULL and should not be duplicated.
2. Primary Key Constraint:
(i) This constraint declares a field as a Primary key which helps to uniquely identify a record. It is similar to unique constraint except that only one field of a table can be set as primary key.
(ii) The primary key does not allow ULI values and therefore a field declared as primary key must have the NOT NULL constraint.
Example:
CREATE TABLE Student:
(
Admno integer NOT NULL PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);
3. Default Constraint:
(i) The DEFAULT constraint is used to assign a default value for the field. When no value is given for the specified field having DEFAULT constraint, automatically the default value will be assigned to the field.
Example:
CREATE TABLE Student:
(
Admno integer NOT NULL PRIMARY KEY,
Name char(20)NOT NULL, .
Gender char(1),
Age integer DEFAULT = "17':
Place char(10),
);
4. Check Constraint:
(i) This constraint helps to set a limit value placed for a field. When we define a check constraint on a single column, it allows only the restricted values on that field. Example showing check constraint in the student table:
CREATE TABLE Students
(
Admno integer NOT NULL PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer (CHECK< = 19),
Place char(10),
);
5. Table Constraint:
(i) When the constraint is applied to a group of fields of the table, it is known as Table constraint. The table constraint is normally given at the end of the table definition.
CREATE TABLE Student
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname)
);
We can write the csv file with quotes, by registering new dialects using csv.register_dialect() class of csv module.
Program:
import csv
info = [['SNO: 'Person: 'DOB'],
['1', 'Madhu,' '18/12/2001'],
['2', 'Sowmya', '19/2/1998'],
['3', 'Sangeetha', '20/3/1999'],
['4', 'Eshwar', '21/4/2000'],
['5', 'Anand', '22/5/2001']]
csv.register_dialect('MyDialect',quoting=csv.QUOTE_ALL)
with open('c:\\pyprg\\ch13\\person.csv', 'w') as f:
writer = csv.writer(f, dialect='myDialect')
for row in info:
writer. writerow(row)
f.close()
Output
file: "Person.csv"
"SNO","Person", "DOB", "1", "Madhu", "18/12/2001"
"2, "Sowmya", "19/2/1998", "3", "Sangeetha",
"20/3/1999", "4", "Eshwar", "21/4/2000"
"5", "Anand", "22/5/2001".
getopt() method returns value consisting of two elements. Each of these values are stored separately in two different list opts and args. opts contains list of splitted strings like made, path and args contains any string if at all not splitted because of wrong path or mode. args will be an empty array if there is no error in splitting strings by getopt().
Example:
The Python code which is going to execute the C++ file p4 in command line will have the getopt() method.
Syntax:
opts, args = getopt.getopt (argv, "i:", ['ifile ='])
where opts contains ('-i','c:\\pyprg\\p4')]]
-i:- option nothing but mode should be followed by
'c:\\pyprg\\p4' value nothing but the absolute path of C++ file,
Since the entire command-line commands are parsed and no leftover arguments, the second argunent args will be empty[].
HAVING clause is used to filter data based on7the group functions. This is similar to WHERE condition but can be used , only with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursorO
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER HAVING COUNT( GENDER> 3")
result = cursor.fetchall( )
co = [i[o] for i in cursor. description]
print(co)
print(result)
Output:
['gender', 'COUNT(GENDER)']
[('M', 5)]
(i) Home Button \(\rightarrow \) The Home Button will help one to begun navigating the chart. If you ever want to return back to the original view, you can click on this.
(ii) Forward/Back buttons \(\rightarrow \) These buttons can be used like the Forward and Back buttons in browser. Click these to move back to the previous point you were at, or forward again.
(iii) Pan Axis \(\rightarrow \) This cross-looking button allows you to click it, and then click and drag graph around.
(iv) Zoom \(\rightarrow \) The Zoom button lets you click on it, then click and drag a square would like to zoom into specifically. Zooming in will require a left click and drag. Zoom out with a right click and drag.
(v) Configure Subplots\(\rightarrow \) This button allows you to configure various spacing options with figure and plot.
(vi) Save Figure \(\rightarrow \)This button will allow you to save figure in various forms
Parameters :
Parameters are the variable in a function definition and arguments are the values which are passed to a function definition.
1. Parameter without Type:
(requires: b > = 0 )
(returns: a to the power of b)
let rec pow a b:=
if b = 0 then 1
else a*powa(b-1)
(i) In the above function definition variable 'b' is the parameter and the value which is passed to the variable 'b' is the argument. The precondition (requires) and postcondition (returns) of the function is given.
(ii) Note we have not mentioned any types (data types). Some language computer solves this type (data type) inference problem algorithmically, but some require the type to be mentioned.
2. Parameter with Type:
(requires: b > 0 )
(returns: a to the power of b )
let rec pow (a:int) (b:int): int :=
if b=0 then 1
else a * pow b (a-1)
(i) When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory. Generally, we can leave out these annotations, because it's simpler to let the compiler infer them.
(ii) There are times 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 sense. Explicitly annotating the types can help with debugging such an error message.
List is constructed by the placing expressions within square brackets separated by commas. Such an expression is called a list literal.
List can store multiple value. Each value can be of any type and can even be another list.
List is[10,20]
The elements of a list can be accessed in two ways. The first method of multiple assignments, Which unpacks a list into its elements and bind each element to a different name.
1st:=[10,20]
x,y:=1st
In the above example x will become 10 and y will become 20
A second method for accessing the elements in a list is by the element selections operators, also expressed using square brackets. Unlike a list literal a square brackets expression directly following another expression does not evaluate to a list value, but insted select an element from the value of the preceding expression.
lst[0]
10
lst[1]
20
In both example mentioned above mathematically we can represent list similar to a set.
1st [(0,10),(1,20)]
Scope:
The scope of a variable is that part of the code where it is visible.
Variable Scope:
Essentially, they're addresses to an object in memory. When we assign a variable with := to an instance, we're binding the variable to that instance - Multiple variables can be mapped to the same instance.
Lifetime Variable:
The lifetime of the variable is only till the end of the procedure. Also, the duration for which a variable is alive is called its 'lifetime'.
Insertion sort is a simple sorting algorithm, It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. This algorithm builds the final sorted list as per the previous algorithm as we have discussed.
Pseudo Code:
Step 1 - It is the first elements, it is already sorted.
Step 2 - Pick next element.
Step 3 - Compare with all elements in the sorted sub-list.
Step 4 - Shift all the elements in the sorted sub-List that is greater than the value to be sorted.
Step 5 - Insert the value.
Step 6 - Repeat until list is Sorted.
At the end of the pass, the insertion sort algorithm gives the sorted output in ascending order as shown below:
i=1
while (i < = 6):
for j in range (1,i):
print (j,end='\t')
print (end='\n')
i+=1
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
# program to find fibonacci series
def fibo (n):
if n < = 1:
return n
else:
return (fibo (n - 1) + fibo (n - 2))
n = int (input ("Enter How manu terms"))
for i in range (n):
print (fibo (i))
Program:
n=[]
for x in range (1, 11)
n = append (x)
for x, i in enumerate (n):
if(i %2! = 0):
del n [x]
print (n)