0% found this document useful (0 votes)
11 views46 pages

Session 3

The document discusses the evaluation of expressions in computer science, focusing on infix and postfix notations, and the use of stacks for evaluating postfix expressions. It also covers the representation of sequences, including arrays, vectors, and lists, detailing their operations and performance characteristics. Additionally, it contrasts vectors with arrays and stacks, highlighting their dynamic resizing capabilities and access methods.

Uploaded by

Nikhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views46 pages

Session 3

The document discusses the evaluation of expressions in computer science, focusing on infix and postfix notations, and the use of stacks for evaluating postfix expressions. It also covers the representation of sequences, including arrays, vectors, and lists, detailing their operations and performance characteristics. Additionally, it contrasts vectors with arrays and stacks, highlighting their dynamic resizing capabilities and access methods.

Uploaded by

Nikhil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Session - 3

3.3 A Mazing Problem (8/8)


 The size of a stack
0 0 0 0 0 1
1 1 1 1 1 0
1 0 0 0 0 1
0 1 1 1 1 1
1 0 0 0 0 1
1 1 1 1 1 0
1 0 0 0 0 1
0 1 1 1 1 1
1 0 0 0 0 0
mp   m / 2 / p, or  p / 2 / m
m*p
*Figure 3.11: Simple maze with a long path
(p.116)
3.4 Evaluation of Expressions
(1/14)
 3.4.1 Introduction
◦ The representation and evaluation of expressions is
of great interest to computer scientists.
 ((rear+1==front) || ((rear==MAX_QUEUE_SIZE-1) && !front)) (3.1)
 x = a/b - c+d*e - a*c (3.2)
◦ If we examine expressions (3.1),
we notice that they contains:
 operators: ==, +, -, ||, &&, !
 operands: rear, front, MAX_QUEUE_SIZE
 parentheses: ( )
3.4 Evaluation of Expressions
(2/14)
 Understanding the meaning of these or any
other expressions and statements
◦ assume a = 4, b = c = 2, d = e = 3 in the statement
(3.2), finding out the value of x = a/b – c + d*e - a*c
 Interpretation 1: ((4/2)-2)+(3*3)-(4*2) = 0+8+9 = 1
 Interpretation 2: (4/(2-2+3))*(3-4)*2 = (4/3)*(-1)*2 = -
2.66666…
◦ we would have written (3.2) differently by using
parentheses to change the order of evaluation:
 x = ((a/(b - c+d))*(e - a)*c (3.3)
 How to generate the machine instructions
corresponding to a given expression?
precedence rule + associative rule
3.4
(3/14)
 Precedence
hierarchy and
associative for C
3.4 Evaluation of Expressions
(4/14)
Evaluating postfix expressions
◦ The standard way of writing expressions is
known as infix notation
 binary operator in-between its two operands
◦ Infix notation is not the one used by compilers
to evaluate expressions
◦ Instead compilers typically use a parenthesis-
free notation referred to as postfix

Postfix:
no
parentheses,
no
precedence
3.4 Evaluation of Expressions
(5/14)
 Evaluating postfix expressions is much
simpler than the evaluation of infix
expressions:
◦ There are no parentheses to consider.
◦ To evaluate an expression we make a single left-
to-right scan of it.
◦ We can evaluate
an expression
easily by using
a stack
Figure 3.14 shows
this processing
when the input is
nine character
string 6 2/3-4 2*+
3.4 Evaluation of Expressions (6/14)
 Representation
◦ We now consider the representation of both the
stack and the expression
3.4 Evaluation of Expressions
(7/14)
 Get Token
3.4 (8/14)
 Evaluation of
Postfix Expression
3.4 Evaluation of Expressions
(9/14)
string: 6 2/3-4 2*+

we make a single left-to-


right scan of it add the string with the
operator

6 2 / 3 - 4 2 *
+ 2 2
the answer is
notnot
an an
is not
an
is an
operator,
anoperator,
not not
an
is an
an
is
end
operator,
an of
operator,
string,
operator,
operator,
popoperator,
pop
put
two
put
twooperator,
put
operator,
pop pop
two
pop
put
two
the
putstack 1 4*2
2
3
4
intointo
the
6/2-3 + 4
elements
the
stack
into
elements
thethe
stack
stack
the
into
ofstack
of
into
elements
theelements
stack thethe
and
the
stack
stack
stack
get
answer
of of
stack 0 6/2-3+4*2
6/2-3
6/2
6
*2 top
STACK
now, top must
+1
-2
-1
3.4 Evaluation of Expressions
(10/14)
We can describe am algorithm for producing a
postfix expression from an infix one as follows
(1) Fully parenthesize expression
a/b-c+d*e-a*c
 ((((a / b) - c) + (d * e)) - (a * c))
(2) All operators replace their corresponding
right parentheses
((((a / b) - c) + (d * e)) - (a * c))
* * two
/ - + - passes
(3)Delete all parentheses
ab/c-de*+ac*-
 The order of operands is the same in infix and
postfix
3.4 Evaluation of Expressions (11/14)
 Example 3.3 [Simple expression]: Simple expression a+b*c,
which yields abc*+ in postfix.
icp isp

1
2 1
1 2
1
3 1
3
0 3

 Example 3.5 [Parenthesized expression]: The expression


a*(b+c)*d, which yields abc+*d*
in postfix
icp isp

1 1
3
2 30
0 0
1 1
2 1
2
1 match )2
1
1
9 1
3
3 3
1
0 1
3
3
3.4 Evaluation of Expressions
(12/14)
 Algorithm to convert from infix to postfix
◦ Assumptions:
 operators: (, ), +, -, *, /, %
 operands: single digit integer or variable of one
character
1. Operands are taken out immediately
2. Operators are taken out of the stack as long as their
in-stack precedence (isp) is higher than or equal to the
incoming precedence (icp) of the new operator
3. ‘(‘ has low isp, and high icp
op ( ) + - * / %
eos
Isp0 19 12 12 13 13 13 0
Icp20 19 12 12 13 13 13 0
precedence stack[MAX_STACK_SIZE];
/* isp and icp arrays -- index is value of precedence
lparen, rparen, plus, minus, times, divide, mod, eos */
static int isp [ ] = {0, 19, 12, 12, 13, 13, 13, 0};
static int icp [ ] = {20, 19, 12, 12, 13, 13, 13, 0};
3.4 Evaluation of Expressions
(13/14)
a * ( b +
c )
operand
/
operato
d
operato
operand
operato
operand
operato
operato
operand
eos
, print
r r , print r , print
r r , print
out out out out
pushthe
pop into
stack
the and 2 +
stack
printout
the
operator
isp of“)”,
“(
“/
“+““ pop
is
is 13
0
12and
and
and
andprint
the
the
theicp
icp
out
icpof
of
of “*
“*

“(is“ 13
until is“(”
20
13
1 (

output 0 */
to
a b c + * d / p
stac
now, top must k
-+1
1
3.4 Evaluation of Expressions
(14/14)
 Complexity: (n)
◦ The total time spent
here is (n) as the
number of tokens
that get stacked and
unstacked is linear
in n
◦ where n is the
number of tokens in
the expression
Sequences

 Suppose we have a collection S of n elements


stored in a linear order, so that we can refer to
the elements in S as first, second, third, and so
on.
 Such a collection is generically referred to as a
sequence.
 We can uniquely refer to each element e in S
using an integer in the range [0,n−1] that is
equal to the number of elements of S that
precede e in S.
 The index of an element e in S is the number of
elements that are before e in Vectors
S. The rank of an 17
Examples of sequences
 Array : implements a compile-time non-
resizeable array.
 Vector : implements an array with
fast random access and an ability to
automatically resize when appending
elements.
 Deque : implements a double ended queue
with comparatively fast random access.
 List : implements a doubly linked list.
 Forward_list : implements a singly linked
list
01/25/2025
01:24 PM
Vectors 19
Vectors
 Main vector operations:
 The Vector ADT ◦ elemAtRank(int r): returns the
extends the notion of element at rank r without
array removing it
◦ replaceAtRank(int r, Object o):
 An element can be replace the element at rank r
accessed, inserted or with o
removed by specifying ◦ insertAtRank(int r, Object o):
its index/rank insert a new element o to
have rank r
 An exception is thrown ◦ removeAtRank(int r): removes
if an incorrect rank is the element at rank r
specified (e.g., a  Additional operations size() and
negative rank) isEmpty()
01/25/2025
01:24 PM
Vectors 21
Array-based Vector
 Use an array V of size N
 A variable n keeps track of the size of the
vector (number of elements stored)
 Operation elemAtRank(r) is implemented in
O(1) time by returning V[r]

0 N-1
V
0 1 2 r n

01/25/2025
01:24 PM
Vectors 22
Array based Vector:
Insertion
 In operation insertAtRank(r,o) we need to
make room for the new element by shifting
forward the n - r elements V[r], …, V[n - 1]
 In the worst case (r = 0), this takes O(n) time

V
0 1 2 r n

V
0 1 2 r n

V o
0 1 2 r n
01/25/2025
01:24 PM
Vectors 23
Deletion
 In operation removeAtRank(r) we need to fill
the hole left by the removed element by
shifting backward the n - r - 1 elements V[r +
1], …, V[n - 1]
 In the worst case (r = 0), this takes O(n) time

V o
0 1 2 r n

V
0 1 2 r n

V
0 1 2 r n
01/25/2025
01:24 PM
Vectors 24
Performance
 In the array based implementation of a Vector
◦ The space used by the data structure is O(n)
◦ Size(), isEmpty(), elemAtRank(r) and
replaceAtRank(r,o) run in O(1) time
◦ insertAtRank(r,o) and removeAtRank(r) run in O(n)
time
 If we use the array in a circular fashion,
insertAtRank(0,o) and removeAtRank(0) run
in O(1) time
 In an insertAtRank(r,o) operation, when the
array is full, instead of throwing an exception,
we can replace the array with a larger one

01/25/2025
01:24 PM
Vectors 25
Stacks versus Vectors
• If you can only push_back and pop_back,
then this is LIFO access.
• What is the difference from a stack?
• Interface is different. For example, can
access elements in the middle in a vector

vs

26
Vectors vs Arrays
 Apart from usual index operator (“[ ]”), elements can be
accessed by member function at which performs range
checking.

 Unlike C++ arrays, STL vectors can be dynamically resized

 When an STL vector of class objects is destroyed, it


automatically invokes the destructor for each of its
elements. With C++ arrays, it is the obligation of the
programmer to do this explicitly.

 Several functions that operate on entire vectors, not just


on individual elements. E.g. : copy all or part of one vector
to another, compare the contents of two vectors, insert
and erase multiple elements.
27
Accessing vector elements
 Vectors support dynamic size change
 Contiguous blocks of memory unlikely to be

found, unlike array


 Arrays use index to traverse elements
 How can one traverse elements of a vector if

they are stored non-contiguously?


 How to keep track of the position of an

element though its index may keep


changing?

Using Position and Iterator ADTs


28
Position ADT
 Say vector contains an
element “Delhi” that we want
to keep track of
 The index of the element may
keep changing depending on
insert/delete operations
 A position s, may be
associated with the element
Delhi (say at time of insertion)
 s lets us access Delhi via
s.element() even if the index of
Delhi changes in the container,
unless we explicitly remove s
 A position ADT is associated
s
with a particular container.
Delh
i 29
Vector Summary
 Vector Operation Complexity for Different
Implementations
Array List
Fixed-Size or Expandable Singly or
Doubly Linked

RemoveAtRank(r), O(1) Best Case (r=0,n) ?


InsertAtRank(r,o) O(n) Worst Case
O(n) Average Case

elemAtRank(r), O(1) ?
ReplaceAtRank(r,o)

Size(), isEmpty() O(1) ?


01/25/2025
01:24 PM
Vectors 30
Lists

01/25/2025
01:24 PM
Vectors 31
Position ADT
 As in vectors, the Position ADT models the notion
of place within a data structure where a single
object is stored
 Positions provide a unified view of diverse ways
of storing data, such as
◦ a cell of an array
◦ a node of a linked list
 Member functions:
◦ Object& element(p): returns the element stored
at this position
◦ bool isNull(): returns true if this is a null position

01/25/2025
01:24 PM
Vectors 32
List ADT
ADT that captures linked
lists
 The List ADT models a • Accessor methods:
sequence of positions
storing arbitrary – first(), last()
objects – before(p), after(p)
◦ establishes a before/after • Update methods:
relation between
positions – replaceElement(p, o),
 It allows for insertion swapElements(p, q)
and removal in the – insertBefore(p, o),
“middle” insertAfter(p, o),
 Query methods: – insertFirst(o),
◦ isFirst(p), isLast(p) insertLast(o)
 Generic methods: – remove(p)
33
◦ size(), isEmpty()
List ADT
 Query methods:
◦ isFirst(p), isLast(p) :
 return boolean indicating if the given position is
the first or last, resp.
 Accessor methods
◦ first(), last():
 return the position of the first or last, resp.,
element of S
 an error occurs if S is empty
◦ before(p), after(p):
 return the position of the element of S
preceding or following, resp, the one at position
p
 an error occurs if S is empty, or p is the first or
last, resp., position
01/25/2025
01:24 PM
Vectors 34
List ADT
 Update Methods
◦ replaceElement(p, e)
 Replace the element at position p with e
◦ swapElements(p, q)
 Swap the elements stored at positions p & q
◦ insertBefore(p, o), insertAfter(p, o),
 Insert a new element o into S before or after, resp., position p
 Output: position of the newly inserted element
◦ insertFirst(o), insertLast(o)
 Insert a new element o into S as the first or last, resp.,
element
 Output: position of the newly inserted element
◦ remove(p)
 Remove the element at position p from S

01/25/2025
01:24 PM
Vectors 35
Exercise:

 Describe how to implement the


following list ADT operations using a
singly-linked list
◦ list ADT operations: first(), last(), before(p),
after(p)
nex
◦ For each operation, explain how it is t
implemented and provide the running time
• A singly linked list concrete
data structure consists of a
sequence of nodes
elem nod
• Each node stores e
• element
• link to the next node 

A B C D 01/25/2025
01:24 PM
Vectors 36
Exercise:
 Describe how to implement the following
list ADT operations using a doubly-linked
list
◦ list ADT operations: first(), last(), before(p),
after(p)
◦ For each operation, explain how it is
implemented and provide the running time

prev next
• Doubly-Linked List Nodes node
implement Position and store:
• element elem
• link to previous node
• link to next node heade trailer
r
• Special trailer and header
nodes

01/25/2025
element
01:24 PM
s 37
Vectors
Insertion
 We visualize operation insertAfter(p, X) which returns position q
p

A B C
p
p

A B q C

X
p q

A B X C
01/25/2025
q 01:24 PM
Vectors 38
Deletion
 We visualize remove(p), where p = last()
p

A B C D

A B C p

A B C
01/25/2025
01:24 PM
Vectors 39
Performance
 In the implementation of the List ADT by
means of a doubly linked list
◦ The space used by a list with n elements is O(n)
◦ The space used by each position of the list is
O(1)
◦ All the operations of the List ADT run in O(1)
time
◦ Operation element() of the
Position ADT runs in O(1) time

01/25/2025
01:24 PM
Vectors 40
STL list class
 Functions in the STL list class
◦ Size() - return #elts in list, empty() - boolean
◦ Front(), back() - return references to first/last elts
◦ Push_front(e), push_back(e) - insert e at front/end
◦ Pop_front(), pop_back() - remove first/last elt
◦ List() - creates an empty list
 Similarities & Differences with book’s List ADT
◦ STL front() & back() correspond to first() & last() except the
STL functions return the element & not its position
◦ STL push() & pop() are equiv to List ADT insert and remove
when applied to the beginning & end of the list
◦ STL also provides fcns for inserting & removing from
arbitrary positions in the list - these use iterators

01/25/2025
01:24 PM
Vectors 41
List Summary
 List Operation Complexity for different
implementations

List Singly-Linked List Doubly- Linked

first(), last(), after(p) O(1) O(1)


insertAfter(p,o),
replaceElement(p,o),
swapElements(p,q)

before(p), insertBefore(p,o), O(n) WC & AC O(1)


remove(p) O(1) BC
Size(), isEmpty() O(1) O(1)

01/25/2025
01:24 PM
Vectors 42
Sequence ADT
Generalizes vectors and lists

 The Sequence ADT is the  List-based methods:


union of the Vector and ◦ first(), last(),
List ADTs before(p), after(p),
 Elements accessed by replaceElement(p,
◦ Rank, or o), swapElements(p,
◦ Position q), insertBefore(p,
 Generic methods: o), insertAfter(p, o),
insertFirst(o),
◦ size(), isEmpty()
insertLast(o),
 Vector-based methods: remove(p)
◦ elemAtRank(r),  Bridge methods:
replaceAtRank(r, o),
insertAtRank(r, o), ◦ atRank(r), rankOf(p)
removeAtRank(r) 01/25/2025
01:24 PM
Vectors 43
Array-based
Implementation
elements
 We use a
circular
array storing
positions
 A position
object
stores:
0 1 2 3
◦ Element
◦ Rank positions
 Indices f and
l keep track
of first and S
last positions
f l
01/25/2025
01:24 PM
Vectors 44
Sequence
Implementations
Operation Array List
size, isEmpty 1 1
atRank, rankOf, elemAtRank 1 n
first, last, before, after 1 1
replaceElement, swapElements 1 1
replaceAtRank 1 n
insertAtRank, removeAtRank n n
insertFirst, insertLast 1 1
insertAfter, insertBefore n 1
remove n 1
01/25/2025
01:24 PM
Vectors 45
Thank You

You might also like