DSA Lab - 1
DSA Lab - 1
LAB 01
Introduction to Data Structures using Python
Instructor: Dr Burhan Khan
______________________________________
FACULTY'S SIGNATURE & DATE
MARKS AWARDED:
_______________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (FAST-NUCES), KARACHI
INTRODUCTION
In this course you will learn about using Python specifically in the context of data structures.
In this lab we will cover the following objectives:
Generally, data structures can be divided into two categories in computer science: primitive
and non-primitive data structures. The former are the simplest forms of representing data
storing single value with immutability, whereas the latter are more advanced: they contain
the primitive data structures within more complex data structures to store collection of data.
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 and Boolean.
1. Integers
You can use an integer to represent numeric data, and more specifically, whole numbers from
negative infinity to infinity, like 4, 5, or -1.
2. Float
"Float" stands for 'floating point number'. You can use it for rational numbers, usually ending
with a decimal figure, such as 1.11 or 3.14.
Example: Take a look at the following chunk and try out some of the integer and float
operations!
3. String
Strings are collections of alphabets, words or other characters. In Python, you can create
strings by enclosing a sequence of characters within a pair of single or double quotes. For
example: 'cake', "cookie", etc. You can also apply the + operations on two or more strings to
concatenate them, just like in the example below:
x = 'Cake'
y = 'Cookie'
3. You can also slice strings, which means that you select parts of strings:
Range Slicing: z1 = x[2:] print(z1)
Print(z1)
5. Strings can also be alpha-numeric characters, but that the + operation still is used to
concatenate strings.
x = '4', y= '2'
x + y = '42'
Python has many built-in methods or helper functions to manipulate strings. Replacing a
substring, capitalizing certain words in a paragraph, finding the position of a string within
another string are some common string manipulations. Check out some of these:
6. Capitalize strings
str.capitalize('cookie')
7. Retrieve the length of a string in characters. Note that the spaces also count towards the
final result:
str1 = "Cake 4 U"
str2 = "404"
len(str1)
str2.isdigit()
10. Find substrings in other strings; Returns the lowest index or position within the string at
which the substring is found:
str1 = 'cookie'
str2 = 'cook'
str1.find(str2)
11. The substring 'cook' is found at the start of 'cookie'. As a result, you refer to the position
within 'cookie' at which you find that substring. In this case, 0 is returned because you start
counting positions from 0!
str1 = 'I got you a cookie', str2 = 'cook'
str1.find(str2)
4. Boolean
This built-in data type that can take up the values: True and False, which often makes them
interchangeable with the integers 1 and 0. Booleans are useful in conditional and comparison
expressions, just like in the following examples:
x = 4, y = 2
x == y
x>y
x=4
y=4
z = (x==y) #Comparision expression
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)
x = 4.0 # A float
y=2 # An integer
z = x/y # Divide `x` by `y`
type(z) # Check the type of `z`
This type of data type conversion is user defined, which means you must explicitly inform the
compiler to change the data type of certain entities.
x=2
y = "The Godfather: Part "
fav_movie = y + x
The above example gave you an error because the compiler does not understand that you are trying
to perform concatenation or addition, because of the mixed data types. You have an integer and a
string that you're trying to add together. There's an obvious mismatch. To solve this, you'll first need
to convert the int to a string to then be able to perform concatenation.
x=2
y = “The Godfather: Part”
fav_movie = (y) + str(x)
print(fav_movie)
Non-primitive types are the sophisticated members of the data structure family. They don't
just store a value, but rather a collection of values in various formats. In the traditional
computer science world, the non-primitive data structures are divided into: Arrays, Lists and
Files.
1. Array
First off, arrays in Python are a compact way of collecting basic data types, all the entries in
an array must be of the same data type. However, arrays are not all that popular in Python,
unlike the other programming languages such as C++ or Java. In general, when people talk of
arrays in Python, they are actually referring to lists.
However, there is a fundamental difference between them, and you will see this in a bit. For
Python, arrays can be seen as a more efficient way of storing a certain kind of list. This type
of list has elements of the same data type, though.
In Python, arrays are supported by the array module and need to be imported before you
start initializing and using them. The elements stored in an array are constrained in their data
type.
The data type is specified during the array creation and specified using a type code, which is
a single character like the, I you see in the example below:
2. List
Lists in Python are used to store collection of heterogeneous items. These are mutable, which
means that you can change their content without changing their identity. You can recognize
lists by their square brackets [ and ] that hold elements, separated by a comma ,. Lists are
built into Python: you do not need to invoke them separately.
x=[] #Empty List
print(type(x))
x1 = [1,2,3]
print(type(x1))
x2 = list([1,'apple',3])
type(x2)
print(x2[1])
x2[1] = 'orange'
print(x2)
Python provides many methods to manipulate and work with lists. Adding new items to a list,
removing some items from a list, sorting or reversing a list are common list manipulations.
Let's see some of them in action:
• Add 11 to the list_num list with append(). By default, this number will be added to
the end of the list.
list_num = [1,2,45,6,7,2,90,23,435]
list_char = ['c','o','o','k','i','e']
list_num.append(11)
# Add 11 to the list, by default adds to the last position
print(list_num)
[1, 2, 45, 6, 7, 2, 90, 23, 435, 11]
Use insert ( ) to insert 11 at index or position 0 in the list_num list
list_num.insert(0, 11) print(list_num)
[11, 1, 2, 45, 6, 7, 2, 90, 23, 435, 11]
Remove the first occurence of 'o' from list_char with the help of remove()
list_char.remove('o') print(list_char)
['c', 'o', 'k', 'i', 'e']
Remove the item at index -2 from list_char
list_char.pop(-2) # Removes the item at the specified position
print(list_char)
['c', 'o', 'k', 'e']
# In-place sorting
list_num.sort()
print(list_num)
[1, 2, 2, 6, 7, 11, 11, 23, 45, 90, 435]
Reverse list
list.reverse(list_num)
print(list_num)
[435, 90, 45, 23, 11, 11, 7, 6, 2, 2, 1]
➢ fruits.count('tangerine')
➢ fruits.index('banana')
➢ fruits.reverse()
➢ fruits
➢ fruits.append('grape')
➢ fruits.sort()
➢ fruits
➢ fruits.pop()
3. Tuples
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
Tuples are another standard sequence data type. The difference between tuples and list is
that tuples are immutable, which means once defined you cannot delete, add or edit any
values inside it. This might be useful in situations where you might pass the control to
someone else, but you do not want them to manipulate data in your collection, but rather
maybe just see them or perform operations separately in a copy of the data. Let's see how
tuples are implemented:
# Empty tuple
my_tuple = ()
print(my_tuple)
# Output: ()
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p','e','r','m','i','t')
# Output: 't'
print(my_tuple[-1])
# Output: 'p'
print(my_tuple[-6])
Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')
4. Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value. While values
can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
5. Sets
A set is created by placing all the items (elements) inside curly brackets, separated by comma
or by using the built in function set().
Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in
Python used to store collections of data. A set is a collection which is unordered,
unchangeable, and unindexed. Set items are unchangeable, but you can remove items and
add new items.
x_set = set(‘CAKE&COKE’)
y_set = set(‘COOKIE’)
print(x_set)
print(y_set)
Note:
In a linear data structure, the data items are organized sequentially or in other words linearly.
The data items are traversed serially one after another and all the data items in a linear data
structure can be traversed during a single run. However, in non-linear data structures the data
items are not organized sequentially which means the elements could be connected to more
than one element to reflect a special relationship among these items. All the data items in a
non-linear data structure may not be traversed during a single run.
Lab Report:
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Performance Does not meet expectation Meets expectation Exceeds expectation Applicable Marks
(0-1) (2-3) (4-5) /Not
Applicable
(NA)
1. Realization of Incapable of selecting Needs guidance to select relevant Selects relevant equipment to the
Experiment [c] relevant equipment to equipment to the experiment and experiment, develops setup
conduct the experiment,
to develop equipment connection diagrams of equipment
equipment connection or
wiring diagrams. or wiring diagrams. connections or wiring.
2. Individual or Distracts or discourages Cooperates with other group Actively engages and cooperates
Teamwork [b] other group members from members in a reasonable manner, with other group members in an
conducting the experiment, or as an individual, perform the effective manner, or actively
or look discouraged or experiment in a manner guided. perform an experiment in an
distracted as an individual. organized and professional
manner as an individual.
3. Conducting Unable to calibrate Calibrates equipment, examines Does proper calibration of
Experiment [a] appropriate equipment, and equipment moving parts, and equipment, carefully examines
equipment operation is operates the equipment with equipment moving parts, and
substantially wrong. minor error. ensures smooth operation and
process.
4. Laboratory Safety Disregards safety rules and Observes safety rules and Respectfully and carefully
Rules [c] procedures. procedures with minor deviation. observes safety rules and
procedures
5. Data Collection Does not know how to plan Plans data collection to achieve Plans data collection to achieve
[a] data collection to achieve experimental objectives, and experimental objectives, and
experimental goals; data collects complete data with minor conducts an orderlyand a
collected is incomplete and error. complete data collection.
contain errors.
6. Data Analysis [a] Unable to conduct simple Conducts simple computations Accurately conducts simple
statistical analysis on and statistical analysis using computations and statistical
collected data; no attempt to collected data with minor error; analysis using collected data;
correlate experimental reasonably correlates correlates experimental results to
results with known experimental results to known known theoreticalvalues;
theoretical values; incapable theoretical values; attempts to accounts for measurement errors
of explaining measurement account for measurement errors and parameters that affect
errors or parameters that and parameters that affect experimental results.
affect the experimental experimental results.
results.
7. Design of Unable to design the Able to design and partially Able to design and implement the
Experiment [d] complete solution of open- implement the complete solution complete solution of open-ended
ended problem with safety, of open-ended problem with problem with safety, health and
health and environment safety, health and environment environment related
related considerations. related considerations. considerations.
Total
Lab Engineer/Faculty
Name: __________________
Signature: ____________
Date: ____________________