0

This is newbie question. I am working on something called sagemath which is completely based on Python.

My code is two parts: The first part is:

var('a,b')
my_list=list(powerset([a,b]))
my_possible_products_list=[]
for i in my_list:
        if len(i)!=0:
            my_possible_products_list.append(prod(i))
print my_possible_products_list   

with an ouput

[a, b, a*b]

i.e, the result is a list of all possible product expressions on a set of two variables.

The second part:

for expression_compute in my_possible_products_list:
    for l in range(1,3):
        for a in divisors(l):
            for b in divisors(l):
                print expression_compute

with an output

a
a
a
a
a
b
b
b
b
b
a*b
a*b
a*b
a*b
a*b

The problem: I need to have numerical output, not using a and b, but using the values of a and b as divisors of the given l.

Any hint?

Thanks.

user31009
  • 103
  • 1

2 Answers2

1

Not sure if I understand the question here, but to my understanding you have the expression as a string and want to compute the value. For a and b as single entities it's easy, just cast to integer

a = "5"
print(int(a) + 1)  # Will print 6

for the product expression you could do as @iForest suggests using eval() but as he said that is evil. I would use the split method

expr = "3*5"
terms = expr.split('*') 
print(int(terms[0]) * int(terms[1]))  # Will print 15

hope this helps, otherwise I need more explanation of your problem

== Updates after @iForest comment ==

If it is the variables names as strings that are needed use locals()

a = 3
b = 5
variables = locals()
expr = "a*b"
terms = expr.split('*')
print(variables[terms[0]] * variables[terms[1]])  # Output 15

will work as long as you don't need to update the variables

Johan
  • 1,633
  • 15
  • 22
  • I think `expr` is something like `a*b`. – iForests Jan 09 '15 at 07:38
  • Ok, then perhaps `locals()` is the way to go since no updates to `a`or `b` are made. There is no good way to give example of this in comment field so will update my answer instead – Johan Jan 09 '15 at 08:11
0

Built-in function eval() can evaluate value of string.

a = 3
b = 5
print(eval("a * b"))        # Output 15

But yes, eval() is EVIL.

It's easy and quick to use, but be careful when you use it. You have to make sure the input string you eval() is OK. Read more about how to use / how dangerous here (8.9. Evaluating Arbitrary Strings As Python Expressions).

iForests
  • 6,757
  • 10
  • 42
  • 75