473,240 Members | 1,954 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,240 software developers and data experts.

lisper learning python, ... could you please comment my first python program?

Hi,
to extend my skills, I am learning python. I have written small
program which computes math expression like "1+2*sin(y^10)/cos(x*y)"
and similar, so far only + - * / ^ sin con tan sqrt are supported. But
my program is quite inextensible, I have to change the code to add new
functions... Could some fellow experienced pythonista give me some
tips how to make my program shorter, and more extensible?

to use it, try something like compute("1+x+sin(x)", {"x" : 10}), the
second param is environment so variables like x or y are looked for
value here...

below is the code.... thanks for any tips!

----- code here ----
import sys
import string
import math

def normalize(string):
tmp = "".join([c for c in string if c != " "])
return "(" + tmp + ")"

def most_nested_expression(string):
start = index = 0
end = len(string) - 1
level = max_level = 0
most_nested = False
for c in string:
if c == "(":
level += 1
if level max_level:
most_nested = True
max_level = level
start = index
elif c == ")":
level -= 1
if most_nested == True:
most_nested = False
end = index
index += 1
if level != 0:
raise IOError("mismatched parens")
if max_level == 0:
return (0, len(string), string)
else:
return (start + 1, end - start - 1, string[start + 1:end])

def is_reduced_expression(string):
for c in string:
if c == "^" or c == "*" or c == "/" or c == "+" or c == "-":
return False
return True

def find_first(string, operators):
positions = []
for op in operators:
pos = string.find(op)
if pos != -1:
positions += [pos]
if positions == []:
return None
else:
return min(positions)

def find_operator(string):
for ops in [["^"], ["*", "/"], ["+", "-"]]:
pos = find_first(string, ops)
if pos != None:
if string[pos + 1] == "+" or string[pos + 1] == "-":
return pos + 1
else:
return pos
return None

def left_operand(string, operator_pos):
left = None
operator = string[operator_pos]
candidates = [pos for pos in [string.rfind(op, 0, operator_pos)
for op in ["(", ")", "^", "*", "/",
"+", "-"]]
if pos != -1]
if candidates != []:
left = max(candidates)
if left == None:
if operator == "^" or operator == "*" or operator == "/":
raise IOError("invalid expression %s" % string)
else: # + or -
return ("0", operator_pos)
else:
if left + 1 == operator_pos:
if operator == "+" or operator == "-":
return ("0", left)
else:
raise IOError("invalid expression %s" % string)
else:
return (string[left + 1:operator_pos], left)

def right_operand(string, operator_pos):
right = None
candidates = [pos for pos in [string.find(op, operator_pos + 1)
for op in ["(", ")", "^", "*", "/",
"+", "-"]]
if pos != -1]
if candidates == []:
if operator_pos == len(string) - 1:
raise IOError("invalid expression %s" % string)
else:
return (string[operator_pos + 1:], len(string))
else:
right = min(candidates)
if operator_pos + 1 == right:
raise IOError("invalid expression %s" % string)
else:
return (string[operator_pos + 1:right], right)

def function_name(string, left_paren_pos):
candidates = [pos for pos in [string.rfind(op, 0, left_paren_pos)
for op in ["(", "^", "*", "/", "+",
"-"]]
if pos != -1]
if candidates == []:
return (None, None)
else:
left = max(candidates)
name = string[left + 1:left_paren_pos]
fun_names = ["sin", "cos", "tan", "sqrt"]

for f in fun_names:
if f == name:
return (left + 1, name)
return (None, None)

def reduce_step(string, index):
(left, exp_len, exp) = most_nested_expression(string)
#print "most nested %s" % exp
if is_reduced_expression(exp):
(left1, name) = function_name(string, left - 1)
if left1 != None:
return ((name, string[left:left + exp_len], None),
string[0:left1] + "$%s" % index + string[left +
exp_len + 1:],
True)
else:
return ((None, None, None), string[0:left - 1] + exp +
string[left + exp_len + 1:], False)
else:
operator_pos = find_operator(exp) + left
(left_op, left_mark) = left_operand(string, operator_pos)
(right_op, right_mark) = right_operand(string, operator_pos)
return ((string[operator_pos], left_op, right_op),
string[0:left_mark + 1] + "$%s" % index +
string[right_mark:],
True)

def reduce(string):
chain = []
index = 0
while string[0] == "(":
((function, left_op, right_op), new_string, is_expr) =
reduce_step(string, index)
if is_expr:
chain += [(function, left_op, right_op)]
index += 1
string = new_string
return chain

def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b

def translate_function(fn_str):
if fn_str == "+": return add
elif fn_str == "-": return sub
elif fn_str == "*": return mul
elif fn_str == "/": return div
elif fn_str == "^": return math.pow
elif fn_str == "sin": return math.sin
elif fn_str == "cos": return math.cos
elif fn_str == "tan": return math.tan
elif fn_str == "sqrt": return math.sqrt
else: raise IOError("unknown function %s" % fn_str)

def translate_operand(op_str):
if op_str[0] == "$":
result_idx = int(op_str[1:])
return lambda results, env: results[result_idx]
else:
try:
value = float(op_str)
return lambda results, env: value
except ValueError:
return lambda results, env: env[op_str]

def translate(chain):
res = []
for (fn_str, left_op_str, right_op_str) in chain:
fn = translate_function(fn_str)
left_op = translate_operand(left_op_str)
if right_op_str != None:
res += [(fn, [left_op, translate_operand(right_op_str)])]
else:
res += [(fn, [left_op])]
return res

def compute_value(chain, env, results):
assert len(chain) == len(results)
index = 0
for (fn, operand_fns) in chain:
operands = [op_fn(results, env) for op_fn in operand_fns]
results[index] = apply(fn, operands)
index += 1
return results[index - 1]

def compute(string, env):
print "input: %s" % string
string = normalize(string)
print "normalized: %s" % string
string_chain = reduce(string)
print "reduced: %s" % string_chain
chain = translate(string_chain)
print "translated: %s" % chain
return compute_value(chain, env, range(len(chain)))

Aug 26 '07 #1
4 1378
On Sun, 26 Aug 2007 15:56:08 +0000, neptundancer wrote:
Hi,
to extend my skills, I am learning python. I have written small
program which computes math expression like "1+2*sin(y^10)/cos(x*y)" and
similar, so far only + - * / ^ sin con tan sqrt are supported. But my
program is quite inextensible, I have to change the code to add new
functions... Could some fellow experienced pythonista give me some tips
how to make my program shorter, and more extensible?
Just a few comments at random. This is certainly not meant to be
exhaustive:

def normalize(string):
tmp = "".join([c for c in string if c != " "])
return "(" + tmp + ")"
Try this instead:

def normalize(astring):
return "(" + astring.replace(" ", "") + ")"
def most_nested_expression(string):
[snip code]
if level != 0:
raise IOError("mismatched parens")
You raise IOError quite often, but that's a misuse of it. IOError is a
subclass of EnvironmentError, and is meant to indicate (e.g.) a failed
read from a disk.

If you execute help(IOError) at the interactive prompt, you will see:

class IOError(EnvironmentError)
| I/O operation failed.
I suggest a better exception to use would be ValueError, or even create
your own:

class MyCustomError(ValueError):
pass

would be a minimal example.

def is_reduced_expression(string):
for c in string:
if c == "^" or c == "*" or c == "/" or c == "+" or c == "-":
return False
return True
Change that to:

for c in string:
if c in "^*/+-": return False
return True
[snip]

def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b
Replace the above four functions with:

from operator import add, sub, mul
from operator import truediv as div
def translate_function(fn_str):
if fn_str == "+": return add
elif fn_str == "-": return sub
elif fn_str == "*": return mul
elif fn_str == "/": return div
elif fn_str == "^": return math.pow
elif fn_str == "sin": return math.sin elif fn_str == "cos": return
math.cos elif fn_str == "tan": return math.tan elif fn_str ==
"sqrt": return math.sqrt else: raise IOError("unknown function %s" %
fn_str)

fn_map = {"+": add, "-": sub, "*": mul, "/": div,
"^": math.pow, "sin": math.sin } # etc.

def translate_function(fn_str):
try:
return fn_map[fn_str]
except KeyError:
raise ValueError("unknown function '%s'" % fn_str)
Hope that helps.
--
Steven.
Aug 26 '07 #2
Thanks a lot for comments! I am going to fix the source according to
your advices ;)

Nep

On Aug 26, 6:32 pm, Steven D'Aprano <st...@REMOVE-
THIScybersource.com.auwrote:
On Sun, 26 Aug 2007 15:56:08 +0000, neptundancer wrote:
Hi,
to extend my skills, I am learning python. I have written small
program which computes math expression like "1+2*sin(y^10)/cos(x*y)" and
similar, so far only + - * / ^ sin con tan sqrt are supported. But my
program is quite inextensible, I have to change the code to add new
functions... Could some fellow experienced pythonista give me some tips
how to make my program shorter, and more extensible?

Just a few comments at random. This is certainly not meant to be
exhaustive:
def normalize(string):
tmp = "".join([c for c in string if c != " "])
return "(" + tmp + ")"

Try this instead:

def normalize(astring):
return "(" + astring.replace(" ", "") + ")"
def most_nested_expression(string):
[snip code]
if level != 0:
raise IOError("mismatched parens")

You raise IOError quite often, but that's a misuse of it. IOError is a
subclass of EnvironmentError, and is meant to indicate (e.g.) a failed
read from a disk.

If you execute help(IOError) at the interactive prompt, you will see:

class IOError(EnvironmentError)
| I/O operation failed.

I suggest a better exception to use would be ValueError, or even create
your own:

class MyCustomError(ValueError):
pass

would be a minimal example.
def is_reduced_expression(string):
for c in string:
if c == "^" or c == "*" or c == "/" or c == "+" or c == "-":
return False
return True

Change that to:

for c in string:
if c in "^*/+-": return False
return True

[snip]
def add(a, b): return a + b
def sub(a, b): return a - b
def mul(a, b): return a * b
def div(a, b): return a / b

Replace the above four functions with:

from operator import add, sub, mul
from operator import truediv as div
def translate_function(fn_str):
if fn_str == "+": return add
elif fn_str == "-": return sub
elif fn_str == "*": return mul
elif fn_str == "/": return div
elif fn_str == "^": return math.pow
elif fn_str == "sin": return math.sin elif fn_str == "cos": return
math.cos elif fn_str == "tan": return math.tan elif fn_str ==
"sqrt": return math.sqrt else: raise IOError("unknown function %s" %
fn_str)

fn_map = {"+": add, "-": sub, "*": mul, "/": div,
"^": math.pow, "sin": math.sin } # etc.

def translate_function(fn_str):
try:
return fn_map[fn_str]
except KeyError:
raise ValueError("unknown function '%s'" % fn_str)

Hope that helps.

--
Steven.

Aug 26 '07 #3
On Aug 26, 5:56 pm, neptundan...@gmail.com wrote:
Hi,
to extend my skills, I am learning python. I have written small
program which computes math expression like "1+2*sin(y^10)/cos(x*y)"
and similar, so far only + - * / ^ sin con tan sqrt are supported. But
my program is quite inextensible, I have to change the code to add new
functions... Could some fellow experienced pythonista give me some
tips how to make my program shorter, and more extensible?
I understand that you are doing this as a learning exercise. Still, I
would
recommend you to have a look at the shlex module in the standard
library
and to pyparsing. Looking at their source code should should give you
some
idea. BTW, since you are familiar with Lisp, I would recommend you
IPython
for a better interactive experience.

Michele Simionato

Aug 26 '07 #4
On Aug 26, 7:40 pm, Michele Simionato <michele.simion...@gmail.com>
wrote:
On Aug 26, 5:56 pm, neptundan...@gmail.com wrote:
Hi,
to extend my skills, I am learning python. I have written small
program which computes math expression like "1+2*sin(y^10)/cos(x*y)"
and similar, so far only + - * / ^ sin con tan sqrt are supported. But
my program is quite inextensible, I have to change the code to add new
functions... Could some fellow experienced pythonista give me some
tips how to make my program shorter, and more extensible?

I understand that you are doing this as a learning exercise. Still, I
would
recommend you to have a look at the shlex module in the standard
library
and to pyparsing. Looking at their source code should should give you
some
idea. BTW, since you are familiar with Lisp, I would recommend you
IPython
for a better interactive experience.

Michele Simionato
thanks for the tip! Now I have IPython working nicely. The shell now
looks a little like Christmas tree but I think it can be reduced a
bit ;)
the ?var and auto completion is exactly what I was looking for!

Nep

Aug 26 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Allison Bailey | last post by:
Hi Folks, I'm a brand new Python programmer, so please point me in the right direction if this is not the best forum for this question.... I would like to open an existing MS Excel spreadsheet...
7
by: Ryan Walker | last post by:
Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that...
6
by: post400 | last post by:
Hi , I was just wondering ( yeah I know it's not the first time this question pops up ) what would be the best 2 or 3 books for someone who wants to learn Python , already experienced in other...
145
by: David MacQuigg | last post by:
Playing with Prothon today, I am fascinated by the idea of eliminating classes in Python. I'm trying to figure out what fundamental benefit there is to having classes. Is all this complexity...
7
by: stormslayer | last post by:
Folks: I've been considering a shift to python. I currently use c++builder (borland) or perl. I do computational models / statistics programming, and was interested in python b/c it a. has...
6
by: Avi Berkovich | last post by:
Hello, I was unable to use popen2.popen4 to grab python.exe's (2.3) output, for starts, it doesn't show the version information at the beginning and won't return anything when writing to the...
6
by: m_a_t_t | last post by:
Ok, I'm reading "The C Programming Language: 2nd Edition" and I'm on chapter 1.5.1 and here's the program you're sposed to make: #include <stdio.h> /* copy input to output; 1st version */...
1
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej...
2
by: Doran, Harold | last post by:
I am currently reading An Intro to Tkinter (1999) by F. Lundh. This doc was published in 1999 and I wonder if there is a more recent version. I've googled a bit and this version is the one I keep...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.