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
Related
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 am looking for handling differing number of returned values from invoked functions in a set number of target variables. The following simplified snippet is a starting illustration:
def f1(): return 1,2,3
def f2(): return 4,5
a,b,c = f1()
a,b,c = f2() # How to massage this call: default of some sort?
So the objective would be to unpack either 2 or 3 results into three output variables.
Consider that the f() being invoked may be one of (many functions..) that mostly all return only two variables .. but there is a need to add a third parameter to maybe one or two of them.
The motivation here: an existing codebase that presently returns only two variables. But I need to add a third one. It would be helpful to leave the existing code mostly alone and simply handle the missing third parameter gracefully.
What construction could be used here?
Generally, you could save all of the returned values to a single variable and then access them using indexing.
x1 = f1() # x1[0] = 1, x1[2] = 2, etc.
x2 = f2()
For Python 3:
If you need to use a,b,c for separate pieces of code, you can pack the variables using:
a,b,*c = f1()
a,b,*c = f2()
This will capture all values beyond the first 2 returned by f1 or f2 as a list in c.
Any python:
If you are in version 2.7, you can take a few extra steps to ensure assigning c doesn't give an error. You capture the output of your function as a list, then extend the list to the length of your variables using None. After that, you can assign directly to a,b,c
# assumes you have 3 variables: a,b,c
res = list(f2())
res += [None]*(3-len(res))
a,b,c = res
You are unpacking the result of those two functions, instead of doing that perhaps you could assign the result to a single variable then test that for length. much like here: ValueError: need more than 2 values to unpack in Python 2.6.6
t = list(f2())
if len(t) > 2:
# Can use the third result!
c = t[2]
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).
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.