operators as variables

James Stroud jstroud at mbi.ucla.edu
Sun Dec 7 04:15:12 CET 2008


> macc_200 wrote:
>> Hi,
>> just starting programming and have an elementary question after 
>> playing around with lists but cannot find the answer with googling.
>> I have a list of variables and I would like some of those variables to 
>> be integers and some to be operators so the list would look something 
>> like [5 * 4 - 4 + 6] and then be able to evaluate the result (i.e. get 
>> 10).  How do you make the interpreter see the operator as that instead 
>> of a string and just echo the list back to me.

Your specification is ambiguous because you mention lists but wrote an 
evaluable expression inside of brackets. Others have answered the 
question you probably really are asking. For fun, though, I'm going to 
pretend you meant "list" and not whatever [5 * 4 - 4 + 6] is:

import operator

opdict = {'+' : operator.add,
           '-' : operator.sub,
           '*' : operator.mul,
           '/' : operator.div}

def take_two(aniterable):
   assert len(aniterable) % 2 == 0
   aniter = iter(aniterable)
   while True:
     try:
       yield aniter.next(), aniter.next()
     except StopIteration:
       break

def reductifier(alist):
   value = alist.pop(0)
   for op, operand in take_two(alist):
     value = opdict[op](value, operand)
   return value

reductifier([5, "*", 4, "-", 4, "+", 6])



More information about the Python-list mailing list