Give the Python function XOR(a,b) that returns the XOR(a,b) where a and b are integers. Submit a complete Python program that uses XOR in file xor.py
This is confusing to me, am I being asked to find integers for a and b
or is it saying a and b begin as integers? I'm generally very confused by
python so this probably seems like a simple question but I do not know where
to even begin with writing the code.
I know the outline of the code should be
def XOR(a,b):
# Your code here
nbr1 = 67
nbr2 = 73
print (XOR(nbr1, nbr2))
The ^ operator in Python is XOR, so you can just do:
def XOR(a,b):
return a ^ b
nbr1 = 67
nbr2 = 73
print (XOR(nbr1, nbr2))
The XOR is just a mathematical function like multiplication, subtraction, addition etc. You might be more familiar with to the power of then XOR. For example, 5 to the 2nd power is 5^2 or XOR(5,2). You just have to create a def called XOR which takes two arguments and returns one of them raised to the other. It's not specified which argument should be taken as the power so you can just take the 2nd one maybe. This is the code:
def XOR(num1,num2):
return num1^num2
print(XOR(5,2))
#prints 25
a and b are integers to begin with. XOR is shorthand for "Exclusive Or" or "Exclusive Disjunctive." Basically, this means a or b, but not a and b ( remember that OR can mean a or b or a and b). It sounds like you are being to write a function that when given two values returns one of the values. You might try this:
import random
XOR(a, b):
list = [a , b ]
return random.choice(list)
Related
I have a very specific task to complete and I am honestly lost in it. The goal is to define function in Python, that would remove all 1s in binary input that do not have any 1 next to it. I will show you in example.
Let's have input 0b11010 -–> the output of this would be 0b11000. Another example 0b10101 --> output would be Ob00000.
The real twist is that I cannot use any for/while loop, import any library or use zip, lists, map etc. The function needs to be defined purely using bitwise operations and nothing else.
I was already trying to implement the concepts of operations, but those were only blind shots and got nowhere. Any help would be appreciated, thanks!
To break down the condition mathematically, the i-th bit of the output should be 1 if and only if:
The i-th bit of the input is 1.
And either the (i-1)-th bit or the (i+1)-th bit of the input is also 1.
Logically the condition is input[i] and (input[i-1] or input[i+1]) if the input is a bit vector. If the input is simply a number, indexing can be emulated with bit shifting and masking, giving this code:
def remove_lonely_ones(b):
return b & ((b << 1) | (b >> 1))
Testing shows that it works both on your examples and on edge cases:
print("{: 5b}".format(remove_lonely_ones(0b11111))) # prints 11111
print("{: 5b}".format(remove_lonely_ones(0b11010))) # prints 11000
print("{: 5b}".format(remove_lonely_ones(0b11011))) # prints 11011
print("{: 5b}".format(remove_lonely_ones(0b10101))) # prints 0
print("{: 5b}".format(remove_lonely_ones(0b00000))) # prints 0
I'm looking for an efficient way to compute the result of a (complex) mathematical function.
right now it looks comparable to:
def f(x):
return x**2
def g(x):
if not x: return 1
return f(x)*5
def h(x):
return g(x)
with concurrent.futures.ProcessPoolExecutor() as executor:
print(list(executor.map(h, params)))
since every function call is costly in Python, the code should already run faster if f(x) is merged with g(x). Unfortunately in that case the 'return ...' line of the g(x) function becomes very long already. Furthermore there are currently actually 6 functions defined in total, so the complete formula occupies several lines.
So, what's a clever way to compute the result of a physics formula?
EDIT:
Thank you so far, but my question is not really about this specific snippet of code but more about the way to implement physics formulas in Python. For example one could also define the expression as a string and evaluate it using eval() but that is obviously slower.
To be more specific I have a potential and want to implement it parallel. Therefore I call my version of "h(x)" using the map function of a ProcessPoolExecutor (with different values each time). But is it best practice to define the function as a function that calls other functions or uses variables? Is there a more efficient way?
def formula(x):
if not x :
return 1
return x*x*5
I don't think the line is in danger of being problematically long, but if you're concerned about the length of the return ... line you could use intermediate values, e.g.:
def g(x):
if x == 0:
return 1
x2 = x ** 2
return x2 * 5
As an aside, in this context it is incorrect to use the is operator as in x is 0. It does not check for numerical equality, which is what == does. The is operator checks that the two operands refer to exactly the same object in memory, which happens to have the same behaviour as == in this case because the Python interpreter is intelligently reusing number objects. It can lead to confusing errors, for example:
a = 1234
b = 1233
a == (b + 1) # True
a is (b + 1) # False
In practice, is is mainly used only to check if a value is None.
A new learner,I am encountering a problem while defining variable b-
def b():
b()
b = a * 2
print "If you double it..."
time.sleep(3)
print "..you have",b
-If input for b is 3,I am getting 33 as answer for multiplication.Please tell me what am I doing wrong.Any help is appreciated
The code originally posted, is, unfortunately, nonsense.
Python lets us define a function b() as b(), but we'll get a recursion error if we try to use it.
def b():
b()
b()
RuntimeError: maximum recursion depth exceeded
Instead of using b, you immediately redefine b = a* 2
Now if a is the char or string '3' from user input, then '3' * 2 being '33' is quite normal and to be expected. This could be avoided by calling a = int(a) to convert a to an integer number or a = float(a) to convert a to a floating point decimal number before doing the multiplication.
We can experiment with * in Python's shell to see what is happening:
3*2
answer: 6
'3'*2
answer: '33'
In the first case, the integer 3 is multiplied by the integer 2, and the answer is 6.
In the second case, the character '3' is multiplied by the integer 2, and Python defines this as a string with '3' appearing twice, i.e. '33'
Similarly:
3*'3'
answer: '333'
What is happening here is called operator overloading. Python calls different code that performs very different functions, all depending on what types are associated with the operator *. This allows for more compact code, at the expense of more work learning as a beginner.
The multiplication of strings to repeat them is occasionally quite useful:
print "We wish you a Merry Christmas!\n"*3 + "And a Happy New Year!"
We wish you a Merry Christmas!
We wish you a Merry Christmas!
We wish you a Merry Christmas!
And a Happy New Year!
My computer programming knowledge is very limited so bear with me if I don't use the jargons. I'm dealing with python and basically there are two functions A and C, of which I want to create another function B to convert output of A to a suitable input of C. Note here all the letters are integers.
Output of A: L=[[a,b,c],[d,e,f],...] #finite list
L[0]=[a,b,c]
Now the problem is that input of C is in the form of (projective) coordinates.
Input of C: (x:y:z)
So I'm trying to create this bridge called function B between A and C with the following properties
Input of B:[x,a,b]
Output of B:(x/b:a/b:1)
So x/b and a/b here are rational numbers.
I don't know how much of this will help but I'm essentially trying to convert something I know from a database into something usable. At the moment this is what I've got that will give me the output of A.
D = CremonaDatabase()
x = EllipticCurve("389a1"); x
N = x.conductor(); N
y = str(N); y
z = len(y); z
a = x.cremona_label()[z:]; a
P = D.allgens(N)[a]; P
It seems like a very crude way of doing things. But it gets me where I want to so far.
I'd appreciate if somebody can tell me where to start looking.
you pretty much answered your own question.
I'm not sure what X is or where it is defined, but im just going to assume it's taken care of
def b(input):
return [[x/coord[1], coord[0]/coord[1], 1] for coord in input]
For some bizarre reason, I am struggling to get my head around iterators/generators as used in Python (I write/use them with no problem in C++ - but somehow I can't seem to grok how to write one using Python).
I have a mathematical function of the form:
f(a,b) = ( v1(a) - v1(b) ) / ( v2(a) - v2(b) )
Where v1 and v2 are equal length 1D vectors.
I want to write a function (actually, a generator), that generates the output of f() as defined above.
Can anyone help?
[[Edit]]
My notation may have been confusing. I hope to clarify that. The function described above return a set of values. With the argument b taking on values, in the interval (a,b]
So for example if we call f(1,5), the function will return the following values (not functions -in case my clarification below causes further confusion):
f(1,1)
f(1,2)
f(1,3)
f(1,4)
f(1,5)
You can use generator expression:
def f(a, b):
return ((v1[a] - v1[i]) / (v2[a] - v2[i]) for i in xrange(a, b+1))
Or a generator function
def f(a, b):
for i in xrange(a, b+1)
yield (v1[a] - v1[i]) / (v2[a] - v2[i])
The generator may look like that, since there is no iteration (as kindall correctly noted).
def f(a, b):
yield (v1[a] - v1[b]) / (v2[a] - v2[b]) # be careful about division!
Couple notes:
there is nothing to iterate through, and generators are generally used in iterations,
be careful about divisions: in Python 2.x a / b returns integer if both a and b are integers (so 4 / 3 == 1) - you can avoid this by using floats or by from __future__ import division,