Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

Overview of Data Structure

The document provides an overview of data structures, including data types, categories of data structures, abstract data types, and built-in data structures in Python. It defines data types, primitive and complex data types. It categorizes data structures as primitive, simple, and complex. It describes abstract data types as programmer-defined types that specify operations independent of implementation. Finally, it outlines common built-in data structures in Python like lists, tuples, sets, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Overview of Data Structure

The document provides an overview of data structures, including data types, categories of data structures, abstract data types, and built-in data structures in Python. It defines data types, primitive and complex data types. It categorizes data structures as primitive, simple, and complex. It describes abstract data types as programmer-defined types that specify operations independent of implementation. Finally, it outlines common built-in data structures in Python like lists, tuples, sets, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

LESSON 1.

OVERVIEW OF DATA STRUCTURES

1. Overview of Data Structures

1.1 Data Types

Data items are represented within a computer as a sequence of binary digits. These
sequences can appear very similar but have different meanings since computers can store and
manipulate different types of data.

• Type - refers collection of values


• Data type – refer to given type along with a collection of operations for manipulating values
of given type.

Programming languages commonly provide data types as part of the language. These
data types are known as primitives:

• Simple Data Types – It consists of values that are in the most basic form and cannot be
decomposed into smaller parts.

Examples: Integer and real types because they are consisted of single numeric values.

• Complex Data Types – are constructed of multiple components consisting of simple types
or other complex types.

Example: objects, strings, list, and dictionaries in Python that contains multiple values.

There are cases that primitive types are not sufficient in solving large complex problems.
Thus, most of the programming languages allow for the construction of additional data type known
as user-defined types. They are defined by the programmer.

1.2 Data Structures

We define data structures a way in which certain data elements are logically related. It is a
class of data that can be characterized by its organization and the operation that are defined on
it. The logical relationship imposed by a data structure on the data elements implies that certain
operations may be applied on the elements, but not others. Thus the notion of a data structure
involves:
• a set of data elements (sometimes called data object –a term referring to a set of
elements).
• the way the data elements are logically related.
• a set of allowable operations on the elements of the data object.

Data structures can be viewed in 3 distinct ways, each levels being different from one another.

Abstract of Logical Level

On this level, we try to picture the organization of the data structure and specify general
accessing procedures and functions.

Implementation Level

From the word implement, we try to examine ways to represent the data elements in
memory and to implement the accessing procedures and functions using a particular
programming language.

Usage or Application Level

The last level examines the data structure in a case study in which the data structure
accurately represents the relationships in the data.

Categories of Data Structures

Data structure is divided into 3 different categories, the first being the primitive type or that
cannot be subdivided. The other two are formed by combining lower data structures.

1. Primitive Data Structure


• synonymous to simple data types (one whose values consists of a single entity
that cannot be subdivided).
2. Simple Data Structure
• built or constructed from one or more primitives.
3. Complex Data Structure
• formed by combining simple data structure in various ways.
Table 1.1 Categories of Data Structure

Primitive Simple Complex Data Structure


Data Data
Structure Structure Compound Data Structure File
Organizatio
Linear Non – Linear

Binary N-ary

int array list Binary Tree Graph Sequential

char string stack Binary Search General Tree Relative


Tree
real record queue M –way Indexed
Search Tree Sequential
Boolean
B Tree Multi Key

B *, B+ Trees

1.3 Abstract Data Types

An abstract data type (or ADT) is a programmer-defined data type that specifies a set of
data values and a collection of well-defined operations that can be performed on those values.
Abstract data types are defined independent of their implementation known as information
hiding. The information hiding separates the interaction with the ADTs though an interface or
defined sets of operations.
The four categories of set of operations

• Constructors – Create and initialize new instance of ADT


• Accessors - Returned data contained in an instance without modifying it.

Example

x = ‘hello world’

y = x.upper()

print(y)

• Mutators – Modify the contents of an ADT instance. Cannot be change anymore


once mutated unless other mutator is initialized.

Example

myList = [1,2,3,4,5]

myList.reverse()

print(myList)

• Iterators – Process individual data components sequentially.

Figure 1.1 Separating the ADT definition from its implementation

Important Definitions
Collection

A group of values with no implied organization or relationship between the individual


values. Sometimes we may restrict the elements to a specific data type such as a collection of
integers or floating-point values.

Container

Any data structure or abstract data type that stores and organizes a collection. The
individual values of the collection are known as elements of the container and a container with no
elements is said to be empty. Python provides a number of built-in containers, which include
strings, tuples, lists, dictionaries, and sets.

Sequence

A container in which the elements are arranged in linear order from front to back, with
each element accessible by position. Python provides two immutable sequences, strings and
tuples, and one mutable sequence, the list.

Sorted Sequence

One in which the position of the elements is based on a prescribed relationship between
each element and its successor. For example, we can create a sorted sequence of integers in
which the elements are arranged in ascending or increasing order from smallest to largest value.

1.4 Built-in Data Structures of Python

There are four collection data types in the Python programming language:

▪ List is a collection which is ordered and changeable. Allows duplicate members.


▪ Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
▪ Set is a collection which is unordered and unindexed. No duplicate members.
▪ Dictionary is a collection which is unordered, changeable and indexed. No duplicate
members.

List

A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.
▪ The list items can be access using the index.

Sample Code: Printing the value on index 1.

myList = [“Dogs”, “Cats”, “Birds”]

print(myList[1])

▪ The value of specific item can be changed by referring also to the index.

Sample Code: Changing the value of element in index 1.

mySubjects = [“Programming”,” Networking”,” Data Analytics”]

mySubjects[1] = “Artificial Intelligence”

print(mySubjects)

▪ The for loop is used to loop through loop.

Sample Code: Looping through the list.

numbers = [1,18,34,3,4,10,9]

for num in numbers

print(num)

▪ The in keyword is used to check it the item exist in the list.

Sample Code: This is to check if the “apple” exists in the list.

myFruits = ["apple", "banana", "cherry"]

if “apple” in myFruits:

print(“Yes, ‘apple’ is in this fruits list”)

▪ The len() method is used to determine the length of items in the list.

Sample Code: Printing the length of list.


myFruits = ["apple", "banana", "cherry"

print(len(myFruits))

▪ It is also possible to use the list() constructor to make a list.

Sample Code: Creating instance of a list.

myFruits = (("apple", "banana", "cherry"))

print(myFruits)

List Methods Built-in Functions

Method Description Sample Code

append() Adds an element at the end of the


list

clear() Removes all the elements from fruits = ['apple', 'banana', 'cherry',
the list 'orange']

fruits.clear()

copy() Returns a copy of the list fruits = ['apple', 'banana', 'cherry',


'orange']

x = fruits.copy()

count() Returns the number of elements fruits = ['apple', 'banana', 'cherry']


with the specified value
x = fruits.count("cherry")
extend() Add the elements of a list (or any fruits = ['apple', 'banana', 'cherry']
iterable), to the end of the current
list cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

index() Returns the index of the first fruits = ['apple', 'banana', 'cherry']
element with the specified value
x = fruits.index("cherry")

insert() Adds an element at the specified fruits = ['apple', 'banana', 'cherry']


position
fruits.insert(1, "orange")

pop() Removes the element at the fruits = ['apple', 'banana', 'cherry']


specified position
fruits.pop(1)

remove() Removes the item with the fruits = ['apple', 'banana', 'cherry']
specified value
fruits.remove("banana")

reverse() Reverses the order of the list fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

sort() Sorts the list cars = ['Ford', 'BMW', 'Volvo']

cars.sort()
Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.

Sample Code: Creating tuple

mySubjects=(“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

print(mySubjects)

▪ The items in in a tuple can be accessed by referring to the index number, inside a square
bracket.

Sample Code: Accessing the item or element in the position or index 0.

mySubjects=(“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

print(mySubjects[0])

The for loop is used to loop through a tuple.

Sample Code: Iterating the items thought the tuple.

mySubjects=(“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

for subject in mySubjects:

print(subject)

▪ The in keyword is used to determine if a value exists in a tuple.

Sample Code: Checks is “Math” exists in the tuple.

mySubjects=(“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

if “Math” in mySubjects:

print(“Yes, ‘Math’ is present in my Subjects”


▪ The len() method is used to determine the length of a tuple>

Sample Code: Printing the length of the tuple mySubjects.

mySubjects=(“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

print(len(mySubjects))

▪ In tuple, you cannot add, change or remove items.

Tuple Built-in Methods

Method Description Sample Code

count() Returns the number of times a thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8,


specified value occurs in a tuple 5)

x = thistuple.count(5)

print(x)

index() Searches the tuple for a specified thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8,


value and returns the position of 5)
where it was found
x = thistuple.index(8)

print(x)

Set

A set is a collection which is unordered and unindexed. In Python sets are written with
curly brackets.
Sample Code: Creating a Set. Since the set is undored and unindexed the items will appear
randomly.

mySubjects = (“English”,“Math”, “Science”, “Filipino”, “MAPEH”)

print(mySubjects)

The items in the list cannot be accessed by referring to the index since its unordered and
unindexed. But the for loop can be used to loop through set items and the in keyword to check if
the item exists.

Sample Code: The first code loops through the items in set and the second checks if the
item exists in the list.

fruits = {“apple”, “banana”, “cherry”}

for fruit in fruits:

print(fruit)

fruits = {“apple”, “banana”, “cherry”}

print( “banana” in fruits)

Once a set is created, you cannot change its items, but you can add new items. In adding
items to a set, the add() method is used to add one item and to add more items update() method
is used.

Sample Code: Add one item to a list.

fruits = {“apple”, “banana”, “cherry”}

fruits.add(“orange”)

print(fruits)
Sample Code: Add multiple items to a set.

fruits = {“apple”, “banana”, “cherry”}

fruits.update([“orange”, “mango”, “grapes”])

print(fruits)

The len() method is used to determine the length of a set.

Sample Code: Checks the length of a set.

fruits = {“apple”, “banana”, “cherry”}

print(len(fruits))

Remove Item in Set using the ff:

Method Description Sample Code

remove() Removes the item


but raise error if the
fruits = {“apple”, “banana”, “cherry”}
item to remove does
not exist fruits.remove(“banana”)

print(fruits)

discard() Removes the item fruits = {“apple”, “banana”, “cherry”}


but does not raise
fruits.discard(“banana”)
error if the item to
remove does not print(fruits)
exist
pop() Removes the item fruits = {“apple”, “banana”, “cherry”}
but removes only the
x = fruits.pop()
last item since set is
unordered and print(x)
undindexed.
print(fruits)

Set Methods

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

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

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets


intersection_update() Removes the items in this set that are not present in
other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two


sets

symmetric_difference_update() inserts the symmetric differences from this set and


another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Dictionary

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.

Sample Code: Creates and print dictionary.


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(car)

There are two ways the items can be accessed of a dictionary by referring its key name

Sample Code: Access the item inside square brackets

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car[“model”]

print(x)

Sample Code: Access the item using the get() method.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.get(“model”)

print(x)

The value of a specific item can be changed by referring to its key name

Sample Code: Changes the year from 1964 to 2018


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car[“1964”]= 2018

print(car)

The for loop is used through a dictionary. When looping through a dictionary, the return
value are the keys of the dictionary, but there are methods to return the values as well.

Sample Code: Returns the key

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for x in car:

print(x)

Sample Code: Returns the values of keys.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for x in car:

print(car[x])

You can also use the values() function to return values of a dictionary:
Sample Code: Returns the values.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for x in car.values():

print(x)

You can also return both the keys and values of a dictionary, by using the items() function.

Sample Code: Returns the the keys and values using the items() funciton

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

for x,y in car.items():

print(x,y)

The in keyword is used to check it the item exists in the dictionary.

Sample Code: Returns the the keys and values using the items() funciton

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

if “model” in cars:

print(“Yes, ‘model’ is here.”)


The len() method is used to determine how many ke-value pairs exists.

Sample Code: Returns the the keys and values using the items() funciton

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

print(len(car))

The items can be added to a dictionary by using new index key and assigning a value to it.

Sample Code: Add new items to a dictionary.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car[“color”] = “red”

print(car)

The items can be removed from a dictionary pop(), popitem(), and del.

The pop() method removes the item with the specified key name.

Sample Code

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop(“model”)
print(car)

The popitem() method removes the last inserted item (in versions before 3.7, a random item is
removed instead).

Sample Code

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.popitem(“model”)

print(car)

The del keyword removes the item with the specified key name:

Sample Code

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

del car[“model”]

print(car)

The del keyword can also delete the dictionary completely:

Sample Code: The print() function will cause an error since the enrite dictionary is
removed.

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

del car

print(car)

The clear() keyword empties the dictionary:

Sample Code

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.clear()

print(car)

To create an instance of dictionary, a dict() constructor is used to make a dictionary.

car = dict(brand="Ford", model="Mustang", year=1964)

print(car)

You might also like