Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Growth rates of example functions

Data Structures

Array-Based Sequence Types


Python has various “sequence” classes, namely the built-in list, tuple, and str classes. There is
significant commonality between these classes, most notably: each supports indexing to access an
individual element of a sequence, using a syntax such as seq[k], and each uses a low-level concept
known as an array to represent the sequence.

However, there are significant differences in the abstractions that these classes represent, and in the
way that instances of these classes are represented internally by Python. These classes will become
building blocks uponcwhich we will develop more complex data structures like stacks, queues, etc

In addition to the above array-based sequence types, Python has an array module which can be used
to instantiate array objects. This module defines an object type which can compactly represent an
array of basic values: characters, integers, floating point numbers. Arrays are sequence types and
behave very much like lists, except that the type of objects stored in them is constrained. The type is
specified at object creation time by using a type code, which is a single character. The following
type codes are defined:
Type code C Type Python Type Minimum size in bytes
'b' signed char int 1
'B' unsigned char int 1
'u' Py_UNICODE Unicode character 2
Type code C Type Python Type Minimum size in bytes
'h' signed short int 2
'H' unsigned short int 2
'i' signed int int 2
'I' unsigned int int 2
'l' signed long int 4
'L' unsigned long int 4
'q' signed long long int 8
'Q' unsigned long long int 8
'f' float float 4
'd' double float 8

Methods:
• append() -- append a new item to the end of the array

• buffer_info() -- return information giving the current memory info

• count() -- return number of occurrences of an object

• extend() -- extend array by appending multiple elements from an iterable

• fromfile() -- read items from a file object

• fromlist() -- append items from the list

• frombytes() -- append items from the string

• index() -- return index of first occurrence of an object

• insert() -- insert a new item into the array at a provided position

• pop() -- remove and return item (default last)

• remove() -- remove first occurrence of an object

• reverse() -- reverse the order of the items in the array

• tofile() -- write all items to a file object

• tolist() -- return the array converted to an ordinary list

• tobytes() -- return the array converted to a string

Attributes:
• typecode -- the typecode character used to create the array

• itemsize -- the length in bytes of one array item

Example:
from array import array
m = array('d',[10.4,11.4,8.90])
for x in m:
print (x)

l = array('l')
u = array('u', 'hello \u2641')
l = array('l', [1, 2, 3, 4, 5])
d = array('d', [1.0, 2.0, 3.14])

Stacks
A stack is a collection of objects that are inserted and removed according to the last-in, first-out
(LIFO) principle. A user may insert objects into a stack at any time, but may only access or remove
the most recently inserted object that remains (at the so-called “top” of the stack). The name “stack”
is derived from the metaphor of a stack of plates in a spring-loaded, cafeteria plate dispenser. In this
case, the fundamental operations involve the “pushing” and “popping” of plates on the stack.
When we need a new plate from the dispenser, we “pop” the top plate off the stack,
and when we add a plate, we “push” it down on the stack to become the new top
plate.

They are used in many applications, including the following:


Example 1: Internet Web browsers store the addresses of recently visited sites in a stack. Each time
a user visits a new site, that site’s address is “pushed” onto the stack of addresses. The browser
then allows the user to “pop” back to previously visited sites using the “back” button.
Example 2: Text editors usually provide an “undo” mechanism that cancels recent editing
operations and reverts to former states of a document. This undo opertion can be accomplished by
keeping text changes in a stack.

The Stack Abstract Data Type


Stacks are the simplest of all data structures, yet they are also among the most important. They are
used in a host of different applications, and as a tool for many more sophisticated data structures
and algorithms. Formally, a stack is an abstract data type (ADT) such that an instance S supports the
following two methods:
S.push(e): Add element e to the top of stack S.
S.pop( ): Remove and return the top element from the stack S; Attempting to pop an empty
stack gives an undefined result. Thus, a precondition of the pop() operation is that the stack s
is not empty.
Additionally, let us define the following accessor methods for convenience:
S.top( ): Return a reference to the top element of stack S, without removing it; an error
occurs if the stack is empty.
S.isempty( ): Return True if stack S does not contain any elements.
len(S): Return the number of elements in stack S; in Python, we implement this with the
special method len .

Besides the precondition assertions mentioned in the explanation of the stack ADT operations
above, we can also state some axioms to help us understand the stack ADT. For example, consider
the following axioms.
For any stack s and element e, pop(push(s,e)) = s.
For any stack s and element e, top(push(s,e)) = e.
For any stack s, and element e, empty?(push(s,e)) = false.
The first axiom tells us that the pop() operation undoes what the push() operation achieves.
The second tells us that when an element is pushed on a stack, it becomes the top element
on the stack.
The third tells us that pushing an element on an empty stack can never make it empty.
By convention, we assume that a newly created stack is empty, and that there is no a priori bound
on the capacity of the stack. Elements added to the stack can have arbitrary type.
Example:

Implementing a Stack Using a Python List


class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if self.isEmpty(self):
print('Stack is empty')
return self.items.pop()
def peek(self):
if self.isEmpty(self):
print('Stack is empty')
return self.items[len(self.items)-1]
def size(self):
return len(self.items)

Alternative:
Apart from implementing from first principles, we can also use the built in Stack class from the
pythonds module.
from pythonds.basic.stack import Stack
s=Stack()
print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())

Group Assignment: Due 8 March and submitted via TSIME


Use a stack data type to check if HTML tags in an input file are properly closed. Each time we
encounter an opening tag, we push that tag onto S, and each time we encounter a closing tag, we
pop a tag from the stack S
Use the example HTML file below but your script should accept any html file and determine
whether the tags are properly closed:
<html>
<head>
<title>Sample "Hello, World" Application</title>
</head>
<body bgcolor=white>
<table border="0" cellpadding="10">
<tr>
<td>
<img src="images/springsource.png">
</td>
<td>
<h1>Sample "Hello, World" Application</h1>
</td>
</tr>
</table>
<p>This is the home page for the HelloWorld Web application. </p>
<p>To prove that they work, you can execute either of the following links:
<ul>
<li>To a <a href="hello.jsp">JSP page</a>.
<li>To a <a href="hello">servlet</a>.
</ul>
</body>
</html>

You might also like