i need to find out whether two circles which are c1 and c2 touch each other externally and at only one point by using Circle class.
I created method which is touches. The method should return a boolean value and it needs to be called like this c1.touches(c2)
this formula to check circles touch or intersect with each other formula
this is my code
import math
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def touches(self):
dist_between_centers = math.sqrt((self.c1.x - self.c2.x)^(2 + (self.c1.y - self.c2.y)^2))
if dist_between_centers == (self.c1.r + self.c2.r):
print("True")
elif dist_between_centers > (self.c1.r + self.c2.r):
print("False")
else:
print("False")
c1 = Circle(2,3,12)
c2 = Circle(15, 28, 10)
c1.touches(c2)
However i am getting error like this, TypeError: touches() takes 1 positional argument but 2 were given
Seems like you mix up with usage self, c1 and c2 in def touches
You should pass c2 as parameter to def touches(circle). Inside method you should refer the first circle as self rather self.c1 and the second as circle rather than self.c2
Final code like this
import math
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def touches(self, circle):
dist_between_centers = math.sqrt((self.x - circle.x)^2 + (self.y - circle.y)^2)
if dist_between_centers == (self.r + circle.r):
print("True")
elif dist_between_centers > (self.r + circle.r):
print("False")
else:
print("False")
c1 = Circle(2, 3, 12)
c2 = Circle(15, 28, 10)
c1.touches(c2)
I am trying to create some custom Python classes for my application. When I try to debug my code I can not pick the instances of my custom classes, I receive the error "Object XXX is not picklable".
I found this page https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled but I don't understand how I should implement the methods that make my class picklable.
For example how would you modify the following classes so that I can pick instances of them?
class Point3D:
def __init__ (self, x, y, z):
self.x = x
self.y = y
self.z = z
def move(self, vector):
self.x += vector.x
self.y += vector.y
self.z += vector.z
return
def isValidPoint(self):
isNotValid = False
isNotValid = math.isnan(self.x) or math.isnan(self.y) or math.isnan(self.z)
return not isNotValid
And
class PointCloud3D:
def __init__ (self):
self.points = []
def getNumberOfPoints(self):
return len(self.points)
def addPoint(self, point):
self.points.append(point)
return
def addPointCloud3D(self, additionalPointCloud3D):
for self.point in additionalPointCloud3D:
self.addPoint(point)
def getCloudCenter(self):
numberOfPoints = self.getNumberOfPoints()
centersSumX = 0
centersSumY = 0
centersSumZ = 0
for point in self.points:
centersSumX = centersSumX + point.x
centersSumY = centersSumY + point.y
centersSumZ = centersSumZ + point.z
centerX = centersSumX/numberOfPoints
centerY = centersSumY/numberOfPoints
centerZ = centersSumZ/numberOfPoints
center = Point3D(float(centerX), float(centerY) , float(centerZ))
return center
While here you can find the code that I am trying to debug:
from classDatabase import Point3D, PointCloud3D
testPoint1 = Point3D(1.5, 0.2, 2.3)
testPoint2 = Point3D(3.5, 1.2, 5.3)
testPointCloud3D = PointCloud3D()
testPointCloud3D.addPoint(testPoint1)
testPointCloud3D.addPoint(testPoint2)
Finally a screenshot of the issue:
The perfect, but impossible, scenario would be:
class example(object):
def __init__(self,x,y):
self.x = x
self.y = y
def foo(self, x = self.x, y = self.y):
return x + y
It doesn't work because self isn't defined. I have done lots of research, looked on decorators, descriptors, metaclasses, almost everything. The solution may be the most obvious and known to all, but I couldn't find it. I could manage two workarounds, as follows:
def prep(argslist, argsprovided, attributes):
argsout = []
for name in argslist:
if name in argsprovided:
argsout.append(argsprovided[name])
else:
argsout.append(getattr(attributes,name))
return argsout
class example(object):
# I can create a default instance or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
# I can wrap a function to use the self argument
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
# I can wrap 'joo' alongside with foo, and make 'wrapper' return a list
def joo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + 2*w
# I can use my custom 'prep' function to to the job
def foo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + w
# Creates a default instance and a custom one
c = example()
d = example(2,2,2,2)
# I can use 'foo' with the instance's default values with both wrapping and 'prepping'
print(c.wrapper()())
print(d.wrapper()())
print(c.foo())
print(d.foo())
# I can use 'foo' with a mix of default values and provided values with both wrapping and 'prepping'
print(c.wrapper()(1,2,3))
print(d.wrapper()(1,2,3))
print(c.foo(y = 3,z = 4,w = 5))
print(d.foo(y = 3,z = 4,w = 5))
The code prints out:
4
8
4
8
7
8
13
14
I have a huge class with lots of functions, every one needs the behavior of 'foo'. My prep solution is too time consuming. After profiling the code, I figured it spent 12 seconds inside prep only. What is a clever and less time consuming way of doing this? I'm completely lost.
I'm not sure it will help but how about using None as a default value and use a clause to determine the value. For example:
def foo(self, x=None, y=None):
real_x = x if x != None else self.x
real_y = y if y != None else self.y
return real_x + real_y
I found six ways of doing what I wanted. After profiling the code, the result was:
afoo foo noo1 noo2 wrap1 wrap2
6.730 28.507 3.98 4.097 10.256 3.468
6.407 28.659 4.096 3.924 9.783 3.529
6.277 28.450 3.946 3.889 10.265 3.685
6.531 30.287 3.964 4.149 10.077 3.674
As you will see ahead, noo1, noo2 and wap2 are quite similar on code. The conventional method afoo is not that efficient. My custom method foo is terrible and wrap1 was just tested for the sake of completeness.
afoo.py
The drawback is that you need an extra line for each function argument.
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def afoo(self, x = None, y = None, z = None, w = None):
x = x if x != None else self.x
y = y if y != None else self.y
z = z if z != None else self.z
w = w if w != None else self.w
return x + y + z + w
c = example(2,2,2,2)
for i in range(0, 10000000):
c.afoo(1,2,3,4)
foo.py
This one is the slower method.
def prep(argslist, argsprovided, attributes):
argsout = []
for name in argslist:
if name in argsprovided:
argsout.append(argsprovided[name])
else:
argsout.append(getattr(attributes,name))
return argsout
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def foo(self, **kwargs):
[x,y,z,w] = prep(['x','y','z','w'],kwargs,self)
return x + y + z + w
c = example(2,2,2,2)
for i in range(0, 10000000):
c.foo(x = 1,y = 2,z = 3,w = 4)
wrapper1.py
By far less efficient than wrapper2.py.
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
c = example(2,2,2,2)
for i in range(0, 10000000):
c.wrapper()(1,2,3,4)
wrapper2.py
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def wrapper(self):
def foo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
return foo
c = example(2,2,2,2)
k = c.wrapper()
for i in range(0, 10000000):
k(1,2,3,4)
noo1.py
class example(object):
# I can create a default class or a custom one
def __init__(self,U,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def noo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
self.noo = noo
c = example(2,2,2,2)
for i in range(0, 10000000):
c.noo(1,2,3,4)
noo2.py
class example(object):
# I can create a default class or a custom one
def __init__(self,x = 1,y = 1,z = 1,w = 1):
self.x = x
self.y = y
self.z = z
self.w = w
def __call__(self):
def noo(x = self.x, y = self.y, z = self.z, w = self.w):
return x + y + z + w
self.noo = noo
c = example(2,2,2,2)
c()
for i in range(0, 10000000):
c.noo(1,2,3,4)
When testing these codes I included the prep function in all of them, just to be shure they had the same basic structure, and thus the time difference would be from the loops.
from threading import *
from random import *
class Ant(Thread):
def __init__(self, x, y):
Thread.__init__(self)
self.x = x
self.y = y
def move(self, x, y):
self.x = x
self.y = y
class Ant_farm():
def __init__(self, x, y):
self.x = x
self. y = y
self.matrix = matrix(x, y)
self.condition = Condition()
def move(self, ant):
with self.condition:
x1, y1 = next_post(ant)
while self.matrix[x1][y1]:
self.condition.wait()
self.matrix[ant.x][ant.y] = False
ant.move(x1, y1)
self.matrix[ant.x][ant.y] = True
self.condition.notify_all()
def next_pos(self, ant):
while True:
choice = {0: (ant.x, ant.y - 1),
1: (ant.x + 1, ant.y),
2: (ant.x, ant.y + 1),
3: (ant.x - 1, ant.y)}
x1, y1 = choice[randrange(0, 4)]
try:
self.matrix[x1][y1]
except IndexError:
pass
else:
return x1, y1
def __str__(self):
res = '\n'
for i in range(self.x):
aux = ''
for j in range(self.y):
aux += str(self.matrix[i][j]) + ' '
aux += '\n'
res += aux
return res
def matrix(x, y):
return [[False for j in range(y)] for i in range(x)]
if __name__ == '__main__':
ant_farm = Ant_farm(7, 7)
for i in range(4):
# t = Ant(target = ant_farm.move)
pass
I want to run move function inside Ant threads. I tried to do:
t = Ant(target = ant_farm.move)
But the interpreter says this:
TypeError: init() got an unexpected keyword argument 'target'
I understand the error, but I don't know how to do what I said.
I need to make some functions that perform basic algebraic operations and a couple of other things on quaternions(these are basically complex numbers of the form a + xi + yj + z*k). I first created a class which contain some attributes, and whenever i create an instance with it I get a quaternion. However, when I tried implementing the functions I mentioned before I keep getting error messages. Anyway, here is my code in its full:
from math import *
class Quaternion(object):
def __init__(self, re, xc, yc, zc):
self.a = re
self.x = xc
self.y = yc
self.z = zc
def __str__(self):
return str(self.a) + "+" + str(self.x) + "i" + "+" + str(self.y) + "j" + "+" + str(self.z) + "k"
def add(self, q):
self.a = self.a + q.a
self.x = self.x + q.x
self.y = self.y + q.y
self.z = self.z + q.z
def mul(self, q):
self.a = self.a*q.a - self.x*q.x - self.y*q.y - self.z*q.z
self.x = self.a*q.x + self.x*q.a + self.y*q.z - self.z*q.y
self.y = self.a*q.y + self.y*q.a + self.z*q.x - self.x*q.z
self.z = self.a*q.z + self.z*q.a + self.x*q.y - self.y*q.x
def conjugate(self):
self.a = self.a
self.x = -1 * self.x
self.y = -1 * self.y
self.z = -1 * self.z
def norm(self):
return sqrt((self.a)**2+(self.x)**2+(self.y)**2+(self.z)**2)
def reciprocal(self):
p1 = self.conjugate()
self.a = p1.a * (1/(self.norm())**2)
self.x = p1.x * (1/(self.norm())**2)
self.y = p1.y * (1/(self.norm())**2)
self.z = p1.z * (1/(self.norm())**2)
def main():
p = Quaternion(2, 0, -3, 0)
q = Quaternion(0, 1, 1, -2)
print "p =", p
print "q =", q
print "p + q =", p.add(q)
print "p * q =", p.mul(q)
print "conjugate of p is", p.conjugate()
print "norm of p is", p.norm()
print "reciprocal of p is", p.reciprocal()
print "p x reciprocal(p) =", p.mul(p.reciprocal)
if __name__ == '__main__':
main()
Now, whenever I run the module(so it then executes the commands under the main function), I get this:
p = 2+0i+-3j+0k
q = 0+1i+1j+-2k
p + q = None
p * q = None
conjugate of p is None
norm of p is 9.11043357914
reciprocal of p is
The only thing it does right is printing out the two quaternions p and q, but none of the other functions/methods seem to be working properly(the norm does give a value, but it isnt the right one for some reason).
Before I forget, let me quickly say what each functions needs to do:
add(self, q) needs to add 2 quaternions together.
mul(self, q) needs to multiply 2 quaternions.
conjugate(self) needs to transform a given quaternion a + xi + yj + zk into this form: a - xi - yj - zk.
norm(self) and reciprocal(self) need to respectively return the norm and reciprocal of the quaternion
You are performing the math correctly in principle, but you are not returning a new object where you should be.
For example, let's look at add(). When you sum two objects, you are expecting the return value to be a third object of the same type, which you are printing. Your add() function does not return anything (in Python this is equivalent to returning None), and instead unexpectedly modifies the object it is called on. Instead, do this:
def add(self, q):
return Quaternion(self.a + q.a,
self.x + q.x,
self.y + q.y,
self.z + q.z)
Do the same for the other methods. If you want to use + and * operators in your code, change the method names to __add__ and __mul__. To do in-place addition and multiplication using += and *= operators, sort of like your current methods are doing, rename the current methods to __iadd__ and __imul__, but don't forget to return self at the end.
You get the None values because you did not specify a return value. Add a
return self
at the end of add, mul, conjugate and reciprocal. (If it is intended that these methods change the value of p, and do not just compute a new Quaternion while leaving p untouched.)