ArrayList: Storing Points - Python Programming Exercise

In this exercise, you will develop a Python program that uses an ArrayList-like structure (a list) to store a collection of points, where each point is represented by a tuple or a custom class with X and Y coordinates. This exercise is perfect for practicing data structures, list manipulation, and geometric calculations in Python. By implementing this program, you will gain hands-on experience in handling data structures, list manipulation, and geometric calculations in Python. This exercise not only reinforces your understanding of data structures but also helps you develop efficient coding practices for managing user interactions.

 Category

Memory Management Techniques

 Exercise

Arraylist: Storing Points

 Objective

Develop a Python program that uses an ArrayList-like structure (a list) to store a collection of points, where each point is represented by a tuple or a custom class with X and Y coordinates. The program should allow adding, removing, and displaying points. Additionally, implement methods to calculate the distance between two points and find the point closest to a given point. Ensure proper handling of edge cases such as empty lists

 Example Python Exercise

 Copy Python Code
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)

 Share this Python Exercise

 More Python Programming Exercises of Memory Management Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  File Search Operations

    In this exercise, you will develop a Python program that searches for a specific word or phrase within a text file. This exercise is perfect for practicing fil...

  •  Implementing a Queue Using List

    In this exercise, you will develop a Python program to implement a queue using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Building a Stack Using Lists

    In this exercise, you will develop a Python program to implement a stack using a list. This exercise is perfect for practicing data structures, list manipulati...

  •  Working with Queue Collections

    In this exercise, you will develop a Python program to demonstrate the use of queue collections. This exercise is perfect for practicing data structures, queue...

  •  Queue and Stack for Reverse Polish Notation

    In this exercise, you will develop a Python program to evaluate expressions written in Reverse Polish Notation (RPN) using a queue and stack. This exercise is ...

  •  Working with ArrayList

    In this exercise, you will develop a Python program to demonstrate the use of an ArrayList-like structure. This exercise is perfect for practicing data structu...