KCS 353
KCS 353
LAB MANUAL
To be an excellent department that imparts value based quality education and uplifts
innovative research in the ever-changing field of technology.
Mission of Department
1. Students will have the successful careers in the field of computer science and
allied sectors as an innovative engineer.
2. Students will continue to learn and advance their careers through participation
in professional activities, attainment of professional certification and seeking
advance studies.
3. Students will be able to demonstrate a commitment to life-long learning.
4. Students will be ready to serve society in any manner and become a responsible
and aware citizen.
5. Establishing students in a leadership role in any field.
Program Outcomes
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations,
and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
Program Specific Outcomes
1. Ability to apply and analyze computational concepts in the areas related to
algorithms, machine learning, cloud computing, web designing and web
services.
2. Ability to apply standard practices and methodologies in software development
and project management.
3. Ability to employ fundamental concepts and emerging technologies for
innovative research activities, carrier opportunities & zeal for higher studies.
Course Outcomes
CO-1 To implement basic discrete structures algorithms.
To implement logical problems like Boolean algebra, poker hand problem and birthday
CO-3 problem.
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
Python Indentations
Example
if 5 > 2:
print("Five is greater than two!")
Python Comments
Comments can be used to explain Python code. Comments can be used to make
the code more readable. Comments can be used to prevent execution when testing
code.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Python Variables
Creating Variables
Variables are containers for storing data values. Unlike other programming languages, Python
has no command for declaring a variable. A variable is created the moment you first assign a
value to it.
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even change type after
they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Example
x = "John"
# is the same as
x = 'John'
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z
Output Variables
The Python print statement is often used to output variables. To combine text and a variable,
Python uses the + character:
Example
x = "awesome"
print("Python is " + x)
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Example
x=5
y = 10
print(x + y)
If you try to combine a string and a number, Python will give you an error:
Example
x=5
y = "John"
print(x + y)
Python Numbers
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z)
Float
Float or "floating point number" is a number, positive or negative, containing one or more
decimals.
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Random Number
Python does not have a random() function to make a random number, but Python has a built-in
module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1,10))
Python Strings
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
Example
print("Hello")
print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
Example
a = "Hello"
print(a)
Multiline Strings
Example
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters. However, Python does not have a character data type, a
single character is simply a string with a length of 1. Square brackets can be used to access
elements of the string.
Example: Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Example: Substring. Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Example: The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
String Format
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method! The format() method
takes the passed arguments, formats them, and places them in the string where the
placeholders {} are:
Example
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Python Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
is not Returns true if both variables are not the same object x is not y
>> Signed right Shift right by pushing copies of the leftmost bit in from the left,
shift and let the rightmost bits fall off
LAB 2
Implementation of decision, Loop in python.
a) Write a program to calculate factorial of a number.
b) Write a program to calculate sum of first n natural numbers where n is finite.
c) Write a program for cube sum of first n natural numbers where n is finite.
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops. An
"if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so
we print to screen that "b is greater than a".
Indentation
Python relies on indentation, using whitespace, to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater to b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:
Example
You can also have multiple else statements on the same line:
Example
The and keyword is a logical operator, and is used to combine conditional statements:
Example
Or
Example
if a > b or a > c:
print("At least one of the conditions is True")
Python Loops
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and continue with the next:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through all the items:
Example
Example
Exit the loop when x is "banana", but this time the break comes before the print:
With the continue statement we can stop the current iteration of the loop, and continue with
the next:
Example
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.
Example
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):
Example
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
for x in adj:
for y in fruits:
print(x, y)
LAB 3
A set is a collection which is unordered and unindexed. In Python sets are written with curly
brackets.
Example
Create a Set:
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Example
for x in thisset:
print(x)
Example
print("banana" in thisset)
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example
thisset.add("orange")
print(thisset)
Example
print(thisset)
To determine how many items a set has, use the len() method.
Example
print(len(thisset))
Remove Item
Example
thisset.remove("banana")
print(thisset)
Example
thisset.discard("banana")
print(thisset)
You can also use the pop(), method to remove an item, but this method will remove
the last item. Remember that sets are unordered, so you will not know what item that gets
removed.
Example
x = thisset.pop()
print(x)
print(thisset)
Example
thisset.clear()
print(thisset)
Example
del thisset
print(thisset)
Example
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference() Returns a set containing the difference between two or more sets
difference_update() Removes the items in this set that are also included in another,
specified set
symmetric_difference_update() inserts the symmetric differences from this set and another
update() Update the set with the union of this set and others
Python Set add() Method
The add() method adds an element to the set. If the element already exists, the add() method
does not add the element.
Syntax:
set.add(elmnt)
Example
fruits.add("orange")
print(fruits)
Syntax:
set.clear()
Example
fruits.clear()
print(fruits)
Syntax:
set.copy()
Example
x = fruits.copy()
print(x)
The difference() method returns a set that contains the difference between two sets.
Meaning: The returned set contains items that exist only in the first set, and not in both sets.
Syntax:
set.difference(set)
Example
Return a set that contains the items that only exist in set x, and not in set y:
z = x.difference(y)
print(z)
The difference_update() method removes the items that exist in both sets.
The difference_update() method is different from the difference() method, because
the difference() method returns a new set, without the unwanted items, and
the difference_update() method removes the unwanted items from the original set.
Syntax: set.difference_update(set)
Example
x.difference_update(y)
print(x)
The discard() method removes the specified item from the set. This method is different from
the remove() method, because the remove() method will raise an error if the specified item
does not exist, and the discard() method will not.
Syntax:
set.discard(value)
Example
fruits.discard("banana")
print(fruits)
The intersection() method returns a set that contains the similarity between two or more sets.
Meaning: The returned set contains only items that exist in both sets, or in all sets if the
comparison is done with more than two sets.
Syntax
Example
Return a set that contains the items that exist in both set x, and set y:
z = x.intersection(y)
print(z)
Example
Compare 3 sets, and return a set with items that is present in all 3 sets:
result = x.intersection(y, z)
print(result)
The intersection_update() method removes the items that is not present in both sets (or in all
sets if the comparison is done between more than two sets). The intersection_update() method
is different from the intersection() method, because the intersection() method returns a new
set, without the unwanted items, and the intersection_update() method removes the unwanted
items from the original set.
Syntax
Example
x.intersection_update(y)
print(x)
Python Set isdisjoint() Method
The isdisjoint() method returns True if none of the items are present in both sets, otherwise it
returns False.
Syntax
set.isdisjoint(set)
Example
z = x.isdisjoint(y)
print(z)
The issubset() method returns True if all items in the set exists in the specified set, otherwise it
retuns False.
Syntax
set.issubset(set)
Example
z = x.issubset(y)
print(z)
The issuperset() method returns True if all items in the specified set exists in the original set,
otherwise it retuns False.
Syntax: set.issuperset(set)
Example
print(z)
The pop() method removes a random item from the set. This method returns the removed
item.
Syntax
set.pop()
Example
fruits.pop()
print(fruits)
Python Set remove() Method
The remove() method removes the specified element from the set. This method is different
from the discard() method, because the remove() method will raise an error if the specified
item does not exist, and the discard() method will not.
Syntax
set.remove(item)
Example
fruits.remove("banana")
print(fruits)
The symmetric_difference() method returns a set that contains all items from both set, but not
the items that are present in both sets.
Meaning: The returned set contains a mix of items that are not present in both sets.
Syntax
set.symmetric_difference(set)
Example
Return a set that contains all items from both sets, except items that are present in both sets:
print(z)
The symmetric_difference_update() method updates the original set by removing items that
are present in both sets, and inserting the other items.
Syntax
set.symmetric_difference_update(set)
Example
Remove the items that are present in both sets, AND insert the items that is not present in both
sets:
x.symmetric_difference_update(y)
print(x)
The union() method returns a set that contains all items from the original set, and all items
from the specified sets. You can specify as many sets you want, separated by commas. If an
item is present in more than one set, the result will contain only one appearance of this item.
Syntax
set.union(set1, set2...)
Example
Return a set that contains all items from both sets, duplicates are excluded:
z = x.union(y)
print(z)
The update() method updates the current set, by adding items from another set. If an item is
present in both sets, only one appearance of this item will be present in the updated set.
Syntax
set.update(set)
Example
x.update(y)
print(x)
LAB 4
b. def is_symmetric(Relation):
if all(tup[::-1] in Relation for tup in Relation):
return True
return False
c. def is_transitive(relation):
for a,b in relation:
for c,d in relation:
if b == c and ((a,d) not in relation):
# print (a,b),(c,d) # uncomment for tests...
return False
return True
LAB 5
Write program to generate recursive sequence of a closed formula and also calculate its value at
particular non negative integer recursively for the following:
a. Polynomial 2n
b. Fibonacci sequence
c. Factorial
Example (a): Calculation of polynomial 2n
i. Closed form- Let f(n)=2n |n>=0
ii. Sequence: 1,2,4,8,16……….
iii. Recursive definition: Basic Step- f(0)=1
Recursive step: f(n)=2* f(n-1)
Program
(a) f(n)=2n (Closed form)
Generation of sequence
Generation of sequence
>>> n=input('enter your number')
>>> for i in range(n):
print(int((math.pow((1+math.sqrt(5)),i)- math.pow((1-math.sqrt(5)),i))/((math.pow(2,i)*math.sqrt(5)))))
if n == 0:
return 0 else:
if n==1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(i))
(c) F(n)=n!(closed form does not exist)
Generation of sequence:
>>>import math
print(math.factorial(i)) print("\n")
return 1 else:
return n * factorial(n - 1)
a. Addition modulo
for i in range(len(a)):
for j in range(len(a)):
b=(a[i]+a[j])%6
print(b)
print('\n')
Multiplication modulo
for i in range(len(a)):
for j in range(len(a)):
b=(a[i]*a[j])%6
print(b)
print('\n')
b. def closure(a):
for i in range(len(a)):
for j in range(len(a)):
if (((a[i]*a[j])%6) not in a): return False
return True
c. def identity(a):
for i in range(len(a)):
for j in range(len(a)-1):
if (((a[i]+a[j])==a[j])and a[i]+a[j+1]==a[j+1]): return a[i]
return(" identity not exixt")
d. # this is a function so return only one inverse if exist
def inverse(a, e): #a is the set and e is the identity element
for i in range(len(a)):
for j in range(len(a)):
if (((a[i]+a[j])==e)):
return a[i], "is inverse of",a[j]
return "inverse not exist"
# this program return all inverse if exist. It print nothing if no inverse exist
def inverse(a,e,k): #a is the set and e is the identity element,k is counter to check for any identity
for i in range(len(a)):
for j in range(len(a)):
if (((a[i]*a[j])==e)):
k=k+1;print a[i], "is inverse of",a[j]
if(k==0):
print "inverse not exist"
LAB 7
Write program for various number systems:
a. Decimal to binary, octal & hexadecimal
b. Binary to decimal, octal and hexadecimal
c. Octal to decimal, binary and hexadecimal
d. Hexadecimal to decimal, binary and octal
e. Logic gate simulation AND, OR, NOT, EXOR, NOR
def OR(a,b):
if a == 1:
return 1
elif b == 1:
return 1
else:
return 0
def NOR (a,b):
if a != b:
return 1
else:
return 0
LAB 8
Write program to:
a. Implement the following Boolean expression:
i. A’B+AB’
ii. (AB’+C)+ C’A
b. Implement full adder and half adder in python.
a. Implementation diagram
Implementation diagram
Output:
2 independent people in a group of 23 share a common birthday. ( 50.9)
3 independent people in a group of 87 share a common birthday. ( 50.0)
4 independent people in a group of 188 share a common birthday. ( 50.9)
5 independent people in a group of 314 share a common birthday. ( 50.6)
LAB 10
Write program to test:
a. Given relation is equivalence or not.
b. Given algebraic system is Abelian group or not.
Equivalence Relation
where these three properties are completely independent. Other notations are often used to
indicate a relation, e.g., or .
Algebraic Structure
A non empty set S is called an algebraic structure w.r.t binary operation (*) if it follows
following axioms:
Closure:(a*b) belongs to S for all a,b ∈ S.
Ex : S = {1,-1} is algebraic structure under *
As 1*1 = 1, 1*-1 = -1, -1*-1 = 1 all results belongs to S.
But above is not algebraic structure under + as 1+(-1) = 0 not belongs to S.