[英]How to check if one list is equal to another list created using a class?
from math import pi
class Circle(object):
'Circle(x,y,r)'
def __init__(self, x=0, y=0, r=1):
self._r = r
self._x = x
self._y = y
def __repr__(self):
return 'Circle({},{},{})'.\
format(self.getx(), self.gety(),\
self.getr())
#silly, but has a point: str can be different from repr
def __str__(self):
return 'hello world'
def __contains__(self, item):
'point in circle'
px, py = item
return (self.getx() - px)**2 + \
(self.gety() - py)**2 < self.getr()**2
def getr(self):
'radius'
return self._r
def getx(self):
'x'
self._lst.append(self._x)
return self._x
def gety(self):
'y'
self._lst.append(self._y)
return self._y
def setr(self,r):
'set r'
self._r = r
def setx(self,x):
'set x'
self._x = x
def sety(self,y):
'set y'
self._y = y
def move(self,x,y):
self._x += x
self._y += y
def concentric(self, d):
d = self._list
def area(self):
'area of circle'
return (self.getr())**2*pi
def circumference(self):
'circumference of circle'
return 2*self.getr()*pi
My question is worded kinda awkwardly but what I am trying to do is check if 2 different circles have the same center (x,y)
.我的问题措辞有点笨拙,但我想做的是检查 2 个不同的圆圈是否具有相同的中心(x,y)
。 I think the easiest way to solve this would be to input the 2 points into a list but I am not sure how to compare the 2 lists as every time i try my code it adds everything to the same list我认为解决这个问题的最简单方法是将 2 个点输入到一个列表中,但我不知道如何比较这 2 个列表,因为每次我尝试我的代码时,它都会将所有内容添加到同一个列表中
Add the following method to your Circle
class.将以下方法添加到您的Circle
类。
def equal_center(self, other):
'check if another circle has same center'
return (self._x == other._x) & (self._y == other._y)
Usage用法
C1 = Circle(3, 5, 8)
C2 = Circle(3, 5, 10)
C3 = Circle(3, 2, 1)
C1.equal_center(C2) # True
C1.equal_center(C3) # False
I would recommend creating a function which takes two circle objects and returns if the coordinates are the same or not by comparing the x
and y
values of each object:我建议创建一个函数,它接受两个圆对象并通过比较每个对象的x
和y
值来返回坐标是否相同:
def same_center(circle_1, circle_2):
if circle_1.getx() == circle_2.getx() and circle_1.gety() == circle_2.gety():
return True
else:
return False
This solution is much easier than using lists and should be easy to implement.此解决方案比使用列表容易得多,并且应该易于实现。
If you have two instances of the class...如果你有两个类的实例......
a = Circle(0,0,1)
b = Circle(0,0,1)
You could add them to a list of circles...您可以将它们添加到圈子列表中...
circles = [a,b]
And loop through the list, checking their values...并遍历列表,检查它们的值......
for i in circles:
for j in filter(lambda x : x != i, circles):
if i._x == j._x and i._y == j._y:
return True #two circles have same center
This should work for n instances of the class, though if its only two you want to check这应该适用于该类的 n 个实例,但如果您只想检查它的两个
if a._x == b._x and a._y == a._y:
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.