使用Python中的迭代器比较函数中的两个元素

发布于 2025-01-06 08:32:28 字数 4397 浏览 1 评论 0原文

我是 python 新手,在理解和在类中使用迭代器时遇到一个小问题。

def findLargest(shapes):
"""
Returns a tuple containing the elements of ShapeSet with the
   largest area.
shapes: ShapeSet
"""
bestName = shapes.List[:]
for i in shapes.List:
    if i.cmp(i+1)== -1:
        bestName.remove(memo)
    if i.cmp(i+1)==1:
        bestName.remove(i)
for element in bestName:
    stringout=''
    stringout= stringout + 'Element ' + str(element.name) + ' with an area of ' + str(element.area()) + ', '
return stringout

所以基本上,我想比较元素列表的面积并获得面积最大的元素元组。我的问题是将元素“i”与元素“i+1”进行比较。我不知道怎么称呼它。为了迭代,我定义了一个方法 iter 和 next() 来迭代 Shapes.List

有人可以帮助我,或者告诉我实现这个函数的好方法是什么。

感谢

以下完整代码


    from string import *

    class Shape(object):
def area(self):
    raise AttributeException("Subclasses should override this method.")

def cmp(self, other):
    if type(other) != Shape and type(other) !=Square and type(other) !=Triangle and type(other) !=Circle:
        return 'Not a shape!'
    if self.area > other.area:
        return 1
    if self.area == other.area:
        return 0
    if self.area < other.area:
        return -1

    class Square(Shape):
def __init__(self, h, name):
    """
    h: length of side of the square
    """
    self.side = float(h)
    self.name = name
def area(self):
    """
    Returns area of the square
    """
    return self.side**2

def __str__(self):
    return 'Square with side ' + str(self.side)

def __eq__(self, other):
    """
    Two squares are equal if they have the same dimension.
    other: object to check for equality
    """
    return type(other) == Square and self.side == other.side

    class Circle(Shape):
def __init__(self, radius, name):
    """
    radius: radius of the circle
    """
    self.radius = float(radius)
    self.name = name

def area(self):
    """
    Returns approximate area of the circle
    """
    return 3.14159*(self.radius**2)
def __str__(self):
    return 'Circle with radius ' + str(self.radius)
def __eq__(self, other):
    """
    Two circles are equal if they have the same radius.
    other: object to check for equality
    """
    return type(other) == Circle and self.radius == other.radius

   # Problem 1: Create the Triangle class

    class Triangle(Shape):
def __init__(self, base, height, name):
    self.base= float(base)
    self.height=float(height)
    self.name = name

def area (self):
    area=float(self.base*self.height)/2
    return area

def __str__(self):
    return 'Triangle with a base ' + str(self.base) +' and height ' + str(self.height)

def __eq__ (self, other):
    return type(other)==Triangle and self.base == other.base and self.height == other.height

    #Problem 2: Create the ShapeSet class

    class ShapeSet:
def __init__(self):
    """
    Initialize any needed variables
    """
    self.List = []
    self.index=0

def addShape(self, sh):
    """
    Add shape sh to the set; no two shapes in the set may be
    identical
    sh: shape to be added
    """
    if self==[]:
        self.List.append(sh)
    else:
        for shape in self.List:
            if shape == sh:
                return 'This shape already exist'
            if shape.area == sh.area and type(shape) == type(sh):
                return 'This shape already exist'
        self.List.append(sh)

def __iter__(self):
    """
    Return an iterator that allows you to iterate over the set of
    shapes, one shape at a time
    """
    return self

def next():
    if self.index>len(self.List-1):
        StopIteration
    else:
        self.index+=1
        return self.List[self.index-1]


def __str__(self):
    """
    Return the string representation for a set, which consists of
    the string representation of each shape, categorized by type
    (circles, then squares, then triangles)
    """
    triangleList=[]
    squareList=[]
    circleList=[]
    if self.List == []:
        return 'The set is empty'
    else:
        for element in self.List:
            if type(element)==Triangle:
                triangleList.append(element.name)
            elif type(element)==Square:
                squareList.append(element.name)
            elif type(element)==Circle:
                circleList.append(element.name)
        return 'circles: %s, square: %s, triangle: %s' % (circleList, squareList, triangleList)

I am new in python and I have a small problem to understand and use an iterator in a class.

def findLargest(shapes):
"""
Returns a tuple containing the elements of ShapeSet with the
   largest area.
shapes: ShapeSet
"""
bestName = shapes.List[:]
for i in shapes.List:
    if i.cmp(i+1)== -1:
        bestName.remove(memo)
    if i.cmp(i+1)==1:
        bestName.remove(i)
for element in bestName:
    stringout=''
    stringout= stringout + 'Element ' + str(element.name) + ' with an area of ' + str(element.area()) + ', '
return stringout

So basically, I want to compare the area of a list of element and get a tuple of elements with the biggest area. My problem is to compare my element "i" to the element "i+1". I don't know how to call it. To iterate I define a method iter and next() in order to iterate over the shapes.List

Someone could help me or maybe tell me what would be the good way to implement this function.

Thanks

full code bellow


    from string import *

    class Shape(object):
def area(self):
    raise AttributeException("Subclasses should override this method.")

def cmp(self, other):
    if type(other) != Shape and type(other) !=Square and type(other) !=Triangle and type(other) !=Circle:
        return 'Not a shape!'
    if self.area > other.area:
        return 1
    if self.area == other.area:
        return 0
    if self.area < other.area:
        return -1

    class Square(Shape):
def __init__(self, h, name):
    """
    h: length of side of the square
    """
    self.side = float(h)
    self.name = name
def area(self):
    """
    Returns area of the square
    """
    return self.side**2

def __str__(self):
    return 'Square with side ' + str(self.side)

def __eq__(self, other):
    """
    Two squares are equal if they have the same dimension.
    other: object to check for equality
    """
    return type(other) == Square and self.side == other.side

    class Circle(Shape):
def __init__(self, radius, name):
    """
    radius: radius of the circle
    """
    self.radius = float(radius)
    self.name = name

def area(self):
    """
    Returns approximate area of the circle
    """
    return 3.14159*(self.radius**2)
def __str__(self):
    return 'Circle with radius ' + str(self.radius)
def __eq__(self, other):
    """
    Two circles are equal if they have the same radius.
    other: object to check for equality
    """
    return type(other) == Circle and self.radius == other.radius

   # Problem 1: Create the Triangle class

    class Triangle(Shape):
def __init__(self, base, height, name):
    self.base= float(base)
    self.height=float(height)
    self.name = name

def area (self):
    area=float(self.base*self.height)/2
    return area

def __str__(self):
    return 'Triangle with a base ' + str(self.base) +' and height ' + str(self.height)

def __eq__ (self, other):
    return type(other)==Triangle and self.base == other.base and self.height == other.height

    #Problem 2: Create the ShapeSet class

    class ShapeSet:
def __init__(self):
    """
    Initialize any needed variables
    """
    self.List = []
    self.index=0

def addShape(self, sh):
    """
    Add shape sh to the set; no two shapes in the set may be
    identical
    sh: shape to be added
    """
    if self==[]:
        self.List.append(sh)
    else:
        for shape in self.List:
            if shape == sh:
                return 'This shape already exist'
            if shape.area == sh.area and type(shape) == type(sh):
                return 'This shape already exist'
        self.List.append(sh)

def __iter__(self):
    """
    Return an iterator that allows you to iterate over the set of
    shapes, one shape at a time
    """
    return self

def next():
    if self.index>len(self.List-1):
        StopIteration
    else:
        self.index+=1
        return self.List[self.index-1]


def __str__(self):
    """
    Return the string representation for a set, which consists of
    the string representation of each shape, categorized by type
    (circles, then squares, then triangles)
    """
    triangleList=[]
    squareList=[]
    circleList=[]
    if self.List == []:
        return 'The set is empty'
    else:
        for element in self.List:
            if type(element)==Triangle:
                triangleList.append(element.name)
            elif type(element)==Square:
                squareList.append(element.name)
            elif type(element)==Circle:
                circleList.append(element.name)
        return 'circles: %s, square: %s, triangle: %s' % (circleList, squareList, triangleList)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

难理解 2025-01-13 08:32:28

在您的班级中,实现 __cmp__ 而不是cmp,那么你可以使用Python内置函数,例如:

bestName = max(shapes.List)

In your class, implement __cmp__ instead of cmp, then you can use Python builtins, such as:

bestName = max(shapes.List)
一花一树开 2025-01-13 08:32:28

您可以使用 recipe 中的pairwise itertools 模块文档

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

for previous, current in pairwise(shapes.List):
    # etc

或者,您可以首先找到最大区域:

max_area = max(shapes, lambda s: s.area())

然后用它来查找所有元素与该区域:

result = [s for s in shapes if s.area() == max_area]

You could use the pairwise recipe from the itertools module documentation:

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

for previous, current in pairwise(shapes.List):
    # etc

Alternatively you could first find the maximum area:

max_area = max(shapes, lambda s: s.area())

Then use this to find all the elements with that area:

result = [s for s in shapes if s.area() == max_area]
混浊又暗下来 2025-01-13 08:32:28
class shape():
    def __init__(self,side_length):
        self.side_length=side_length
    def area(self):
        return self.side_length*self.side_length

shape_list=[shape(i) for i in [1,6,3,12,9]]
import heapq
largest_3=heapq.nlargest(3,shape_list,key=shape.area)

for shape in largest_3:
    print shape.side_length

12
9
6
class shape():
    def __init__(self,side_length):
        self.side_length=side_length
    def area(self):
        return self.side_length*self.side_length

shape_list=[shape(i) for i in [1,6,3,12,9]]
import heapq
largest_3=heapq.nlargest(3,shape_list,key=shape.area)

for shape in largest_3:
    print shape.side_length

12
9
6
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文