【问题标题】:Area of shapes in pythonpython中的形状区域
【发布时间】:2019-09-09 19:26:54
【问题描述】:

所以我有一个名为 the_rectangle 的函数,我运行了两次来创建两个矩形。但是,我希望 python 找出每个矩形的面积并通过打印确定哪个更大(“更大的矩形面积是:) 然后打印(“较小的矩形区域是:)。另外我希望它使用参数宽度和长度来查找每个区域的值。这可能吗?

import turtle
import math


def the_rectangle(width, length, color):
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()

def main():
    the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    the_rectangle(100, 250, "yellow")

main()

【问题讨论】:

  • 为什么不实现一个函数,在其中传递宽度和高度,并确定矩形的面积。稍后,您可以调用此函数来查看哪个矩形更大。另外,您使用的是什么版本的 Python?

标签: python turtle-graphics


【解决方案1】:

有很多方法可以完成您想要的,但对现有代码的最简单修改可能是让“the_rectangle”返回该区域。 您需要获取返回值并计算最大/最小面积。

如果你想让它成为一个更大规模的程序,你需要去创建类,就像其他答案中提到的那样。

import turtle
import math


def the_rectangle(width, length, color):
    # This function draws a rectangle and returns the area
    turtle.color(color)
    turtle.begin_fill()
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(90)
    turtle.end_fill()
    return width*length

def main():
    area_1 = the_rectangle(200, 100, "red")
    turtle.penup()
    turtle.forward(300)
    turtle.pendown()
    area_2 = the_rectangle(100, 250, "yellow")
    print("Largest rectangle is " + str(max(area_1,area_2)))
    print("Smallest rectangle is " + str(min(area_1,area_2)))

main()

【讨论】:

    【解决方案2】:

    试着让你的矩形成为一个类。这样您就可以将所有数据集中在一个地方。

    class Rectangle:
        def __init__(self, length, width, color): # Initialization
            self.length = length
            self.width = width
            self.color = color
    
        def draw(self, turtle): # Draws the rectangle
            turtle.color(color)
            turtle.begin_fill()
            turtle.forward(width)
            turtle.left(90)
            turtle.forward(length)
            turtle.left(90)
            turtle.forward(width)
            turtle.left(90)
            turtle.forward(length)
            turtle.left(90)
            turtle.end_fill()
    
        def area(self): # Calculates the area
             return self.length * self.width
    

    要使用这个类来比较区域,只需使用下面的代码。

    def main():
        rectangle1 = Rectangle(200, 100, "red")
        a1 = rectangle1.area()
        rectangle2 = Rectangle(100, 250, "yellow")
        a2 = rectangle2.area()
    
        print("The bigger rectangle's area is:", str(max(a1, a2)))
        print("The smaller rectangle's area is:", str(min(a1, a2)))
    
        # Draw the rectangles
        rectangle1.draw()
        turtle.penup()
        turtle.forward(300)
        turtle.pendown()
        rectangle2.draw()
    

    【讨论】:

      【解决方案3】:

      如果你不想更新现有的函数the_rectangle,你可以创建一个装饰器函数来打印矩形的面积,这个面积可以保存下来,以后用来和其他矩形的面积比较,看看哪个更小哪个更大。

      这是示例代码:

      def area(function):
          def wrapper(*args):
              print('Area of rectangle %d*%d is: %d' % (args[0], args[1], args[0]*args[1]))
              return function(*args)
          return wrapper
      
      @area
      def the_rectangle(width, length, color):
          ...
      

      【讨论】:

        【解决方案4】:

        如果您要确定哪个矩形更大,那么存储矩形(或其区域)将是最重要的。您可以根据尺寸计算绘制矩形之前或之后的面积:

        
        # This will allow you to create a rectangle and store its area
        # as a three-element tuple
        def area(l, w):
            # returns a three-element tuple to represent a rectangle
            return (l, w, l*w)
        

        现在,您可以获取返回的矩形并绘制它。我会使用 * 的参数解包来解包尺寸,然后你知道你将只复制长度和宽度来绘制它,从而减少你必须编写的额外代码量:

        def draw_rectangle(*dimensions, color="red"):
            dims = dimensions[:2]*2 # creates a list [l, w, l, w]
            for dim in dims:
                turtle.forward(dim)
                turtle.left(90)
        
        

        现在,要比较一个矩形,如果一个矩形的面积更大,则它确实比另一个更大,因此您可以取任意数量的矩形并使用itertools.combinations 将它们配对。然后你比较每一对,你可以打印出结果:

        from itertools import combinations
        
        def compare_recs(*rectangles):
            for r1, r2 in combinations(rectangles, 2):
                # The third element of your tuple, denoted by the index [2],
                # is your area, which is what you are comparing against here
                bigger, smaller = (r1, r2) if r1[2] >= r2[2] else (r2, r1)
                print(f"The bigger rectangle is {bigger}")
                print(f"The smaller rectangle is {smaller}")
        
        r1 = area(10, 20)
        r2 = area(10, 15)
        draw_rectangle(*r1, color='red')
        draw_rectangle(*r2, color='yellow')
        
        
        compare_recs(r1, r2)
        The bigger rectangle is (10, 20, 200)
        The smaller rectangle is (10, 15, 150)
        

        你可以用类来做这件事,但如果你是 Python 新手,我认为这是一个公平的起点。

        【讨论】:

          猜你喜欢
          • 2022-12-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-02
          • 2023-04-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多