ArrayList: almacenamiento de puntos en Python

En este ejercicio, desarrollarás un programa en Python que utiliza una estructura similar a ArrayList (una lista) para almacenar una colección de puntos, donde cada punto está representado por una tupla o una clase personalizada con coordenadas X e Y. Este ejercicio es perfecto para practicar estructuras de datos, manipulación de listas y cálculos geométricos en Python. Al implementar este programa, obtendrás experiencia práctica en el manejo de estructuras de datos, manipulación de listas y cálculos geométricos en Python. Este ejercicio no solo refuerza tu comprensión de las estructuras de datos, sino que también te ayuda a desarrollar prácticas de codificación eficientes para gestionar las interacciones con el usuario. Además, este ejercicio proporciona una excelente oportunidad para explorar la versatilidad de Python en aplicaciones del mundo real. Al trabajar con estructuras de datos, manipulación de listas y cálculos geométricos, aprenderás a estructurar tu código de manera eficiente, lo cual es una habilidad crucial en muchos escenarios de programación. Este ejercicio también te anima a pensar críticamente sobre cómo estructurar tu código para la legibilidad y el rendimiento, convirtiéndolo en una valiosa adición a tu portafolio de programación. Ya seas un principiante o un programador experimentado, este ejercicio te ayudará a profundizar tu comprensión de Python y mejorar tus habilidades para resolver problemas.



Grupo

Gestión de la memoria en Python

Objectivo

Desarrollar un programa Python que utilice una estructura similar a ArrayList (una lista) para almacenar una colección de puntos, donde cada punto esté representado por una tupla o una clase personalizada con coordenadas X e Y. El programa debe permitir agregar, eliminar y mostrar puntos. Además, implementar métodos para calcular la distancia entre dos puntos y encontrar el punto más cercano a un punto dado. Asegurar el manejo adecuado de casos extremos como listas vacías

Ejemplo Ejercicio Python

 Copiar Código Python
import math

class Point:
    """A class representing a point in 2D space with X and Y coordinates."""
    
    def __init__(self, x, y):
        """Initialize the point with given X and Y coordinates."""
        self.x = x
        self.y = y

    def __repr__(self):
        """Return a string representation of the point."""
        return f"Point({self.x}, {self.y})"

    def distance_to(self, other_point):
        """Calculate the Euclidean distance from this point to another point."""
        return math.sqrt((self.x - other_point.x) ** 2 + (self.y - other_point.y) ** 2)


class PointCollection:
    """A collection of points that supports adding, removing, displaying points, and finding distances."""
    
    def __init__(self):
        """Initialize the collection as an empty list."""
        self.points = []

    def add_point(self, point):
        """Add a point to the collection."""
        if isinstance(point, Point):
            self.points.append(point)
        else:
            print("Error: Only Point objects can be added.")

    def remove_point(self, point):
        """Remove a point from the collection."""
        try:
            self.points.remove(point)
        except ValueError:
            print("Error: Point not found in the collection.")

    def display_points(self):
        """Display all points in the collection."""
        if not self.points:
            print("No points to display.")
        else:
            for point in self.points:
                print(point)

    def calculate_distance(self, point1, point2):
        """Calculate the distance between two points in the collection."""
        if point1 in self.points and point2 in self.points:
            return point1.distance_to(point2)
        else:
            print("Error: Both points must be in the collection.")
            return None

    def find_closest_point(self, reference_point):
        """Find the point in the collection closest to a given point."""
        if not self.points:
            print("Error: The collection is empty.")
            return None
        closest_point = self.points[0]
        min_distance = reference_point.distance_to(closest_point)
        for point in self.points[1:]:
            distance = reference_point.distance_to(point)
            if distance < min_distance:
                closest_point = point
                min_distance = distance
        return closest_point


# Main function to demonstrate the functionality
def main():
    # Create a PointCollection instance
    collection = PointCollection()

    # Create some points
    point1 = Point(1, 2)
    point2 = Point(3, 4)
    point3 = Point(-1, -1)
    point4 = Point(5, 5)

    # Add points to the collection
    collection.add_point(point1)
    collection.add_point(point2)
    collection.add_point(point3)
    collection.add_point(point4)

    # Display all points
    print("Points in the collection:")
    collection.display_points()

    # Calculate the distance between two points
    print(f"\nDistance between {point1} and {point2}: {collection.calculate_distance(point1, point2)}")

    # Find the closest point to point1
    closest_point = collection.find_closest_point(point1)
    if closest_point:
        print(f"\nThe closest point to {point1} is {closest_point}.")

    # Remove a point from the collection
    collection.remove_point(point3)

    # Display points after removal
    print("\nPoints in the collection after removing one point:")
    collection.display_points()


# Run the program
if __name__ == "__main__":
    main()

 Output

Points in the collection:
Point(1, 2)
Point(3, 4)
Point(-1, -1)
Point(5, 5)

Distance between Point(1, 2) and Point(3, 4): 2.8284271247461903

The closest point to Point(1, 2) is Point(3, 4).

Points in the collection after removing one point:
Point(1, 2)
Point(3, 4)
Point(5, 5)

Comparte este ejercicios Python

Más ejercicios de Programacion Python de Gestión de la memoria en Python

¡Explora nuestro conjunto de ejercicios de programación en Python! Diseñados específicamente para principiantes, estos ejercicios te ayudarán a desarrollar una sólida comprensión de los fundamentos de Python. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte gradualmente a medida que adquieres confianza en la programación en Python.