0% found this document useful (0 votes)
35 views

Practical # 2

This document introduces various primitive and non-primitive data structures in Python like integers, floats, strings, booleans, lists, tuples, dictionaries, sets and files. It discusses how to define, initialize, access and update each data structure and provides examples of built-in functions that can be used to manipulate elements in these data structures. The document also includes tasks for students to practice creating and modifying different data structures using relevant functions.

Uploaded by

yumna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Practical # 2

This document introduces various primitive and non-primitive data structures in Python like integers, floats, strings, booleans, lists, tuples, dictionaries, sets and files. It discusses how to define, initialize, access and update each data structure and provides examples of built-in functions that can be used to manipulate elements in these data structures. The document also includes tasks for students to practice creating and modifying different data structures using relevant functions.

Uploaded by

yumna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

PRACTICAL # 2

INTRODUCTION TO DATA STRUCTURES, FUNCTIONS AND RECURSION

EMAN SHAHID
DATA STRUCTURES

• Data structures are a way of organizing and storing data so that they can be
accessed and worked with efficiently. They define the relationship between
the data, and the operations that can be performed on the data.
PRIMITIVE DATA STRUCTURES
PRIMITIVE DATA STRUCTURES

These are the most primitive or the basic data structures. They are the building
blocks for data manipulation and contain pure, simple values of a data. Python
has four primitive variable types:
• Integers
• Float
• Strings
• Boolean
NUMBERS

• Python programming supports integers, floating point numbers


and complex numbers.
• Number objects are created when you assign a value to them
var1 = 1
var2 = 10
• You can delete a single object or multiple objects by using the del statement
del var
del var_a, var_b
• Python supports four different numerical types
• int (signed integers) − used for representing positive or negative
whole numbers with no decimal point.
• float (floating point real values) − they represent real numbers
and are written with a decimal point. Floats may also be in
scientific notation, with E or e indicating the power of 10 (2.5e2 =
2.5 x 102 = 250).
• complex (complex numbers) − are of the form a + bj, where a
and b are floats and ‘j’ represents the square root of -1 (which is
an imaginary number). The real part of the number is a, and the
imaginary part is b. Complex numbers are not used much in
Python programming.
NUMBER TYPE CONVERSION

• Type int(x) to convert x to a plain integer.


• Type float(x) to convert x to a floating-point number.
• Type complex(x) to convert x to a complex number with real part x and
imaginary part zero.
• Type complex(x, y) to convert x and y to a complex number with real part x
and imaginary part y. x and y are numeric expressions
BUILT IN FUNCTIONS
• Mathematical Functions

• Random Number Functions


• Random numbers are used for games,
simulations, testing, security, and privacy
applications.
BUILT IN FUNCTIONS
• Trigonometric Functions

• Mathematical Constants
LAB TASKS:

• Execute at least 3 functions from each:


• Mathematical Functions
• Random Functions
• Trigonometric Functions
• Mathematical Constraints (2)
STRINGS

• Strings are arrays of characters and elements of an array can be accessed


using indexing.
• String indices and accessing string elements
• Indices start with 0 from left side and -1 when starting from right side.
• string1 ="PYTHON TUTORIAL“
• String Slicing
• To cut a substring from a string is called string slicing. Here two indices are used
separated by a colon (:).
• A slice 3:7 means indices characters of 3rd, 4th, 5th and 6th positions. The second integer
index i.e. 7 is not included. You can use negative indices for slicing.
STRING SPECIAL
OPERATORS

• Assume string
variable a holds
'Hello' and
variable b holds
'Python'
STRING
FORMATTING
OPERATOR
BUILT-IN STRING METHODS
BOOLEAN

The simplest build-in type in Python is the bool type, it represents the truth
values False and True.
NON PRIMITIVE DATA STRUCTURES
NON PRIMITIVE DATA STRUCTURE

• Arrays
• List
• Tuples
• Dictionaries
• Sets
• Files
ARRAYS

• In Python, arrays
are supported by
the array module
and need to be
imported before
you start initializing
and using them.
Array functions
• array.insert(i, x)
Insert a new item with value x in the array before position i.
Negative values are treated as being relative to the end of the
array.
• array.pop([i])
• Removes the item with the index i from the array and returns it.
The optional argument defaults to -1, so that by default the last
item is removed and returned.
• array.remove(x)
Remove the first occurrence of x from the array.
• array.reverse()
Reverse the order of the items in the array.
• array.tobytes()
Convert the array to an array of machine values and return the bytes
representation (the same sequence of bytes that would be written to a file by
the tofile() method.)
New in version 3.2: tostring() is renamed to tobytes() for clarity.
• array.tofile(f)
Write all items (as machine values) to the file object f.
• array.tolist()
Convert the array to an ordinary list with the same items.
• array.tostring()
• array.count(x)
Return the number of occurrences of x in the array.
• array.fromfile(f, n)
Read n items (as machine values) from the file object f and append them to the
end of the array.
• array.append(x)
Append a new item with value x to the end of the array.
• array.fromlist(list)
Append items from the list.
• array.fromunicode(s)
Extends this array with data from the given unicode string.
• array.index(x)
Return the smallest i such that i is the index of the first occurrence of x in the
array.
LAB TASK:

• Execute at least 5 built-in functions of arrays of your own choice.


PYTHON LISTS

• The list is a most versatile datatype available in Python which can be written
as a list of comma-separated values (items) between square brackets.
• Important thing about a list is that items in a list need not be of the same
type.
CREATING LIST

• To build a list, just put some expressions in square brackets. The syntax is:
Syntax:
lst1 = [ ] # lst1 is the name of the list
lst2 = [expression1 , …. , expression_N]
Example:
lst1 = ['computersc', 'IT', 'CSE']
st2 = [1993, 2016]
lst3 = [2, 4, 6, "g", "k", "s"]
ACCESSING LISTS VALUES

• Example
lst1 = ['computersc', 'IT', 'CSE'];
lst2 = [1993, 2016];
lst3 = [2, 4, 6, "g", "k", "s"];
print ("lst1[0]", lst1[0])
print ("lst3[2:4]", lst3[2:4])
• Output:
lst1[0] computersc
lst3[2:4] [6, 'g']
UPDATING LIST ELEMENTS

Example:
lst1 = ['computersc', 'IT', 'CSE'];
print ("Second value of the list is:")
print (lst1[1])
lst1[1] = 'Robotics'
print ("Updated value in the second index of list is:")
print (lst1[1])
Output:
Second value of the list is:
IT
Updated value in the second index of list is:
Robotics
DELETE ELEMENTS FROM LISTS

To remove an element from the list, we can use the del-statement. The syntax for
deleting an element from a list is:
Syntax:
del list_name[index_val];
LAB TASK:

• Execute at least 5 built-in functions of list.


TUPLES

Tuples are immutable lists and cannot be changed in any way once it is created.
Some of the characteristics features of Tuples are:
•Tuples are defined in the same way as lists.
•They are enclosed within parenthesis and not within square braces.
•Elements of the tuple must have a defined order.
•Negative indices are counted from the end of the tuple, just like lists.
•Tuple also has the same structure where the values are separated by commas

Example:
tupl1 = ('computersc', 'IT', 'CSE');
ACCESSING VALUES IN TUPLES

Example:
tupl1 = ('computersc', 'IT', 'CSE');
tupl2 = (1993, 2016);
tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
print ("tupl1[0]", tupl1[0])
print ("tupl3[2:4]", tupl3[2:4])
Output:
tupl1[0] computersc
tupl3[2:4] (6, 8)
UPDATING TUPLES
Example:
tupl1 = (2, 3, 4);
tupl2 = ('ab', 'cd');
tupl3 = tupl1 + tupl2
print (tupl3)
Output:
(2, 3, 4, 'ab', 'cd')

Delete Elements From Tuples


• Syntax:
del tuple_name;
LAB TASK:

• Create tuples and manipulate it using built-in functions, operation and slicing.
DICTIONARY

• Dictionary is like a list but in a general form. A dictionary is a mapping between a


set of indexes or keys with a set of values, where each key maps to a value.
Combination of a key and its value is called a key-value pair or item.
• In Python dictionary, each key is separated by a colon (:) from its values. Commas
separate all the items, and the whole dictionary is enclosed within '{' and '}'. In the
dictionary, all the keys should have to be unique with data type as strings, tuples or
numbers and the values can be of any of these three types.
• Define a Dictionary In Python
dicto = {'Bookname' : 'Python', 'Price' : 210}

• Accessing Dictionary Values


dicto = {'Bookname' : 'Python', 'Price' : 210}
print (dicto['Bookname’])
Output:
Python
• Creating a new Dictionary
Example:
new_dict = dict()
print (new_dict)
or
new_dict = {}
print (new_dict)
Output:
{}
Example:
new_dict = dict()
new_dict['First'] = 10;new_dict['Second'] = 20;
• Updating Dictionary in Python
Example:
dicto = {'Bookname' : 'Python', 'Price' : 210}
#Adding new entries
dicto ['Author'] = 'TutorialsCloud’
dicto ['Discount']= '10 Percent’;
#Updating an Entry
dicto ['Price'] = 200;
• Deleting Elements From Dictionary
Deleting elements from a dictionary can be done either removing individual elements or use clear() to
clear the entire dictionary's content.
Example:
• dicto = {'Bookname' : 'Python', 'Price' : 210, 'Author': 'TutorialsCloud’}
• del dicto['Price’];# It deletes only the key with the name 'Price’
• dicto.clear(); # The above code removes all entries in dictionary & makes the
dictionary empty
• del dicto # The above code Deletes the entire dictionary
LAB TASK:

• Create dictionaries and manipulate it using built-in functions and operation.


SETS

• A set object is an unordered collection of distinct hashable objects. It is


commonly used in membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.
FILES

• Variables provide us a way to store data while the program runs, if we want out
data to persist even after the termination of the program, we have to save it to a
file.
• File Opening In Python
open() function is used to open a file in Python. It's mainly required two arguments,
first the file name and then file opening mode.
Syntax:
file_object = open(filename [,mode] [,buffering])
In the above syntax the parameters used are:
•filename: It is the name of the file.
•mode: It tells the program in which mode the file has to be open.
•buffering: Here, if the value is set to zero (0), no buffering will occur while
accessing a file, if the value is set to top one (1), line buffering will be performed
while accessing a file.
MODES OF
OPENING FILES
CREATING SETS

setx = set()
n = set([0, 1, 2, 3, 4, 5])

Iteration over sets


num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
ADDING MEMBERS

• color_set = set()
• Add a single member
color_set.add("Red")

• Add multiple items


olor_set.update(["Blue", "Green"])
• Remove item(s) from Python set:
pop(), remove() and discard() functions are used to remove individual item from a Python
set.

• Intersection of sets: by using ‘&’.


• Union of sets: by using ‘|’
• Set difference: by using ‘&’
• Symmetric difference: by using ‘^’
• Issubset: by using ‘<=‘
• issuperset: by using ‘>=‘
• Clear sets: clear()
FILE OBJECT ATTRIBUTES

If an attempt to open a file fails then open returns a false value, otherwise it
returns a file object that provides various information related to that file.
Example:
# file opening example in Python
fo = open("sample.txt", "w")
print ("File Name: ", fo.name)
print ("Mode of Opening: ", fo.mode)
print ("Is Closed: ", fo.closed)
Output:
File Name: sample.txt
Mode of Opening: w
Is Closed: False
FILE READING IN PYTHON

• For reading and writing text data different text-encoding schemes are used
such as ASCII (American Standard Code for Information Interchange), UTF-8
(Unicode Transformation Format), UTF-16.
• Once a file is opened using open() method then it can be read by a method
called read().
Example:
# read the entire file as one string
with open('filename.txt') as f:
data = f.read()
# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
print(line, end=' ')# process the lines
WRITING A FILE
IN PYTHON

• Writing file using


write() method
CLOSING A FILE:

• Closing a file
file_object.close();
TYPE CASTING
DATA TYPE CONVERSION

• When you change the type of an entity from one data type to another, this is
called "typecasting". There can be two kinds of data conversions
possible: implicit termed as coercion and explicit, often referred to as casting.
CHECKING DATA TYPE:

To check the type of an object in Python, use the built-in type() function, just
like in the lines of code below:
i = 4.0
type(i)
Output: float
IMPLICIT DATA TYPE CONVERSION

# A float
x = 4.0
# An integer
y=2
# Divide `x` by `y`
z = x/y # Check the type of `z`
type(z)
Output: float
EXPLICIT DATA TYPE CONVERSION

• This type of data type conversion is user defined, which means you have to
explicitly inform the compiler to change the data type of certain entities.
Note that it might not always be possible to convert a data type to another. Some built-in
data conversion functions that you can use here are: int(), float(), and str().
x=2
y = "The Godfather: Part "
fav_movie = (y) + str(x)
print(fav_movie)
Output: The Godfather: Part 2
LAB TASK:

• Write a program to create, read, write files.


FUNCTIONS
FUNCTIONS

• Using 'def' statement for defining a function


• To group a set of statements, programmers use functions, and they can be run
more than once in a program. They act like a pack of instructions that is
invoked by a name.
• Functions also let programmers compute a result-value and give parameters
that serve as function inputs that may change each time the code runs.
Functions prove to be a useful tool when the operations are coded in it and
can be used in a variety of scenarios.
• Functions are an alternative method of cutting-and-pasting codes, rather than
typing redundant copies of the same instruction or operation; which further
reduces the future work for programmers.
EXAMPLE

def avrg(first, *rests):


return (first + sum(rests)) / (1 + len(rests))
# Sample use, Putting values
print (avrg(1, 2))
print (avrg(1, 2, 3))
print (avrg(1,2,3,4))
Output:
1.5 2.0 2.5
ADVANTAGES OF PYTHON FUNCTIONS

• Maximizing code reusability


• Minimizing redundancy
• Procedural decomposition
• Make programs simpler to read and understand
RECURSION

• Recursion is a way of programming or coding a problem, in which a function


calls itself one or more times in its body. Usually, it is returning the return value
of this function call. If a function definition fulfils the condition of recursion, we
call this function a recursive function.
EXAMPLE
def factorial(n):

print("factorial has been called with n = " + str(n))


if n == 1:
return 1

else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res

print(factorial(5))
OUTPUT

• This Python script outputs the following results:


factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120

120
LAB TASKS:

• Write a program for Fibonacci series with simple function and recursion.
• Write a Python function to sum all the numbers in a list
• Write a Python program to reverse a string.
• Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.
• Write a Python program to check if a given key already exists in a dictionary.
CLASS TASKS:

• Write a Python program to sum all the items in a list.


• Write a Python script to concatenate following dictionaries to create a new
one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
DEADLINE FOR LAB SUBMISSION:
23/4/2018 FOR SECTION 1
25/4/2018 FOR SECTION 2

You might also like