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.
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
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).
Related
I want to remove duplicate variable from logic gate. For example, suppose i have the following code:
from z3 import *
a = Bool('a')
b = Bool('b')
# c is the same variable as a
c = Bool('a')
or_gate = Or(a, b, c)
I want to check whether or_gate contain multiple of the same variable, if yes i want to leave only one and remove the rest.
In above example, i want the or gate to be Or(a, b) instead of Or(a, b, a). What is the best way to do it?
You can use .hash() method to do that.
if a.hash() == b.hash():
# they reference the same variable
I have a list and a function f which returns a 3-tuple. I would like to capture the first two return values, and with the third, append to lst. I know I can do the following:
a, b, c = f()
lst.append(c)
but I would like a way not to have the extraneous variable "c". I know I can also do:
lst.append(f()[2])
but I do not want to throw away the other two return values.
Any suggestions?
Edit: I appreciate the answers provided, but the question, put more clearly, is to find a neat one-liner.
Assign the return value to a local variable before you append the result.
No, you can't catch two values and append the third in one statement; you only get one "verb" per command.
result = f()
lst.append(result[2])
What you want to do is not possible with a "one liner" (without using semi-colon to fit two statements on a single line) unless you change your function definition.
Specifically, define f() in the following way:
def f(list_to_append_to):
a = ...
b = ...
c = ...
list_to_append_to.append(c)
return a, b
Then:
a, b = f(mylist)
If your problem is not saving yourself with writing one more line of code, but you would just want the function call, the assignment and the appendix in a single statement, you could use a wrapper function:
def append_and_assign(mylist, myfunc):
a, b, c = myfunc()
mylist.append(c)
return a,b,c
and so you can call:
a,b,c = append_and_assign(lst, f)
I have a problem that asks me to combine three numeric variables, for example, a = 1 , b = 2 , c = 3. We're supposed to make d = ' 1|2|3 '. I've done some scripting in BASH where "|" refers to piping. How would you accomplish this in Python, and what does "|" mean?
The vertical bar is merely a character. Treat this the same way you would a comma or a dash. Convert each integer to string, and concatenate them with the bar in between. This is merely an exercise in string manipulation; nothing particularly deep or tricky.
Not sure what exactly you are expected to do or mean by "combining". In Python you can combine variables into tuples so that you can have a "compound" or combined variable that you can use for lookup tables, etc.
a = 1
b = 2
c = 3
combined = (a,b,c)
now you can do things like x = {combined: "value"}
The solution hspandher is on the right track, but would work primarily for one set of three numeric variables. It might be more useful to create a function like this:
def numberCombiner(a, b, c):
return str(a)+"|"+str(b)+"|"+str(c)
numberCombiner(1,2,3)
Which would take in three numeric values and output the string you want. Then you can call/invoke the numberCombiner function on different values, like:
numberCombiner(2,3,4)
which would return
>>> '2|3|4'
Using format:
>>> a=1
>>> b=2
>>> c=3
>>> "{}|{}|{}".format(a,b,c)
'1|2|3'
Just create a list of all the variables, and join them using the pipe symbol.
"|".join(map(str, [a, b, c]))
Use a generator expression to convert your integer variables into strings, and join them with the vertical line symbol.
"|".join(str(v) for v in [a, b, c])
More about generator expression.
More about string joining.
Thanks to juanpa.arrivillaga for pointing out the generator expression syntax where the generator is used right away by an enclosing function. See comments for more information.
I have to perform a certain arithmetic operation between decimal numbers. The operations can be 'add', 'subtract' or 'multiply', and the desired operation will be passed in to our function along with the numbers.
The way I want to do this is that I want to store the ASCII values of the operations '+', '-' and '*' and then somehow use that to perform the operation between the two numbers.
def (a, b, op):
dict{'add':ord('+'), 'subtract':ord('-'), 'multiply':ord('*')}
return a dict[op] b # this statement does not work
Is there a way to achieve something like that in python ?
I know one alternative is to use:
from operator import add,sub,mul
and then use the imported values in the hash instead, but for this question I am interested in finding out if its possible to do it the way I asked in the original question. Thanks !
Yes there is an eval() function in python which takes string as input and returns the output , so you slightly need to change the approach, eval() is generally used as :
print eval("2 + 3")
>>> 5
So the new code looks something like :
def evaluate(a, b, op):
dict = {'add':'+', 'subtract':'-', 'multiply':'*'}
return eval(str(a)+ dict[op] +str(b))
print evaluate(2,3,"add")
>>> 5
No, this
a dict[op] b
is not valid Python.
Use the functions from operator.
I was reading the assignment statements in the Python docs ( http://docs.python.org/reference/simple_stmts.html#assignment-statements).
In that it is quoted that:
If the target is a target list enclosed in parentheses or in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.
After reading it, I thought of writing a sample like this:
a = 5
b = 4
a, b = a + b, a
print a, b
My assumption was that a and b both should have the value of 9.
However, I am proven wrong. 'a' has the value of 9 and 'b' has the value of 5.
Can some one help me understand this better? Why the older value of 'a' is assigned rather than the new one? As per the docs, a's value will be assigned first right? Am I missing something?
All the expressions to the right of the assignment operator are evaluated before any of the assignments are made.
From the Python tutorial: First steps towards programming:
The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
Emphasis mine.
Your code is functionally equivalent to the following:
a, b = 5 + 4, 5
print a, b
Python does not have a "comma operator" as in C. Instead, the comma indicates that a tuple should be constructed. The right-hand side of
a, b = a + b, a
is a tuple with th two items a + b and a.
On the left-hand side of an assignment, the comma indicates that sequence unpacking should be performed according to the rules you quoted: a will be assigned the first element of the tuple, b the second.
You can think of the assignments happening in parallel on copies rather than sequentially and in-place.
This is why in python you dont need a swap function:
a, b = b, a
works sufficiently without requiring a temp variable, c.