Homework Assignment # 5

Due Wednesday October 9, 2013 by 11:59 PM. See the following link for turnin instructions:

https://piazza.com/class/hkuo0jreo4q3wa?cid=39

[10 Points] Please have the following at the top of HW5.py (Please don't put you name on the homework for privacy reasons.)

# HW5.py # Homework 5 # # UT EID: XXX999, UTCS username: XXXXXXXX # CS313e, Fall 2013, Dr. P. Cannata # Department of Computer Science, The University of Texas at Austin -- Problem 1 [10 Points]: Write a python function called calc (we now know this will be an example of a general recursive function or effective decision procedure or algorithm) that will use a Stack (from Homework 4) to evaluate arithmetic expressions composed of just single digit integers, and "+" and "*" operators passed to the function as a string (e.g., calc("((1+2)*3)") ). You should assume that there are opening and closing parentheses at the beginning and end of the expression respectively e.g., calc("(1+1)") not calc("1+1"). You can also assume the expression is well formed, i.e., it contains no syntax errors. (You may find the "break" operation handy in your solution, see pages 151-152 in the textbook. Also, you can use the str() function to convert a number to a string, see page 71 of the textbook.) To jog your memory, here's what we did in class to help motivate the solution (if you weren't in class, this might not make much sense) : e = "(((2+3)*(4*7))*2)"

s1 = Stack()

for s in e:

print s

s1.push(s)

print s1

s1 = Stack()

s1.push("(")

s1.push("(")

s1.push("(")

s1.push("2")

s1.push("+")

s1.push("3")

print s1

# Because we see a ")" in the expression, now do the following:

v = eval(s1.pop() + s1.pop() + s1.pop())

s1.pop()

print v

s1.push(v)

print s1

[ 5 Points of Extra Credit] Have calc work for multi-digit integers, decimal numbers and "+", "*", "-", and "/" operators.

As an example:

print eval("(((12+33.3)*(1.4*701))/(2.2-1.1))")

print calc("(((12+33.3)*(1.4*701))/(2.2-1.1))")

would give:

40415.8363636

40415.8363636

You may want to reverse strings for this solution, you can do this as follows:

s="12+33.3"

r=s[::-1]

print s, r, r[::-1]

gives

12+33.3 3.33+21 12+33.3

Why does this work - from http://love-python.blogspot.com/2008/02/reverse-string-in-python.html

>>> foo = [2, 5, 1, 8]

Regular slice (returns all)

>>> foo[:]

[2, 5, 1, 8]

Slice with stride (returns every nth)

>>> foo[::2]

[2, 1]

Stride works inversely as well

>>> foo[::-2]

[8, 5]

Hence it can be used to reverse a string (stride backwards using step length of one)

>>> 'foobar'[::-1]

'raboof'

See also http://stackoverflow.com/questions/509211/pythons-slice-notation