oprav funkcnost skriptu. nektere polygony to nedetekuji, jinde udela ze dvou trojuhelniku jeden utvar, ktery vypada jako trojuhelnik, ale kvuli ctyrem bodum jej definuje jako 4gon. je to tedy velmi nepresne a nepouzitlne.
cely opraveny skript mi zapis sem.



import matplotlib.pyplot as plt
from shapely.geometry import LineString, Point, MultiLineString, Polygon
from shapely.ops import polygonize
import math
from collections import defaultdict

def get_circle_points(N):
    points = []
    for i in range(N):
        angle = 2 * math.pi * i / N
        x = math.cos(angle)
        y = math.sin(angle)
        points.append((x, y))
    return points

def input_line_segments():
    print("Enter the line segments as pairs of point indices (comma-separated).")
    print("For example: 1,3")
    print("Enter 'done' when finished.")
    segments = []
    while True:
        s = input("Enter line segment: ")
        if s.lower() == 'done':
            break
        try:
            idx1, idx2 = map(int, s.strip().split(','))
            segments.append((idx1 - 1, idx2 - 1))  # Adjusting for zero-based indexing
        except:
            print("Invalid input. Please enter two integers separated by a comma.")
    return segments

def compute_intersections(points, segments):
    lines = []
    for idx1, idx2 in segments:
        x1, y1 = points[idx1]
        x2, y2 = points[idx2]
        line = LineString([(x1, y1), (x2, y2)])
        lines.append(line)
    # Collect all intersection points
    intersection_points = []
    new_lines = []
    for i, line1 in enumerate(lines):
        for line2 in lines[i+1:]:
            if line1.crosses(line2):
                intersection = line1.intersection(line2)
                if intersection.geom_type == 'Point':
                    intersection_points.append(intersection)
    # Subdivide lines at intersection points
    for line in lines:
        # Collect points to split at (endpoints and intersections)
        split_points = [Point(line.coords[0]), Point(line.coords[1])]
        for pt in intersection_points:
            if pt.distance(line) < 1e-8:
                split_points.append(pt)
        # Sort points along the line
        split_points = sorted(split_points, key=lambda p: line.project(p))
        # Create new segments between split points
        for start, end in zip(split_points[:-1], split_points[1:]):
            new_line = LineString([start, end])
            new_lines.append(new_line)
    return new_lines

def classify_polygons(polygons):
    classification = defaultdict(int)
    for poly in polygons:
        num_sides = len(poly.exterior.coords) - 1  # subtract 1 because the first and last point are the same
        if num_sides >= 3:
            classification[num_sides] += 1
    return classification

def main():
    N = int(input("Enter the number of points on the circle: "))
    points = get_circle_points(N)
    segments = input_line_segments()
    
    # Plot original segments
    fig1, ax1 = plt.subplots()
    circle = plt.Circle((0, 0), 1, fill=False, color='black', linestyle='dashed')
    ax1.add_artist(circle)
    for idx, (x, y) in enumerate(points):
        ax1.plot(x, y, 'ko')
        ax1.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=12, ha='center', va='center')
    for idx1, idx2 in segments:
        x1, y1 = points[idx1]
        x2, y2 = points[idx2]
        ax1.plot([x1, x2], [y1, y2], color='blue')
    ax1.set_aspect('equal')
    ax1.set_title('Original Line Segments')
    
    # Compute intersections and subdivide lines
    new_lines = compute_intersections(points, segments)
    
    # Use polygonize to find the polygons formed
    polygons = list(polygonize(new_lines))
    
    # Classify polygons
    classification = classify_polygons(polygons)
    
    # Output counts
    print("\nPolygons found:")
    total_polygons = 0
    for num_sides in sorted(classification.keys()):
        count = classification[num_sides]
        print(f"{num_sides}-gon: {count}")
        total_polygons += count
    print(f"\nTotal number of polygons: {total_polygons}")
    
    # Plot polygons
    fig2, ax2 = plt.subplots()
    circle = plt.Circle((0, 0), 1, fill=False, color='black', linestyle='dashed')
    ax2.add_artist(circle)
    for idx, (x, y) in enumerate(points):
        ax2.plot(x, y, 'ko')
        ax2.text(x * 1.05, y * 1.05, str(idx + 1), fontsize=12, ha='center', va='center')
    # Plot the subdivided lines
    for line in new_lines:
        x, y = line.xy
        ax2.plot(x, y, color='gray', linewidth=1)
    # Plot the polygons with random colors
    from matplotlib.patches import Polygon as MplPolygon
    import random
    colors = ['red', 'green', 'blue', 'yellow', 'cyan', 'magenta', 'orange']
    for poly in polygons:
        coords = list(poly.exterior.coords)
        poly_patch = MplPolygon(coords, closed=True, fill=True, alpha=0.5, color=random.choice(colors))
        ax2.add_patch(poly_patch)
        # Label the polygon at its centroid
        centroid = poly.centroid
        num_sides = len(coords) - 1
        ax2.text(centroid.x, centroid.y, f"{num_sides}-gon", fontsize=10, ha='center', va='center')
    ax2.set_aspect('equal')
    ax2.set_title('Polygons Found')
    
    plt.show()

if __name__ == "__main__":
    main()