Python实现矩形欧几里得铺砖绘图:递归失效问题求助
问题分析与修复方案
你的代码递归未执行的核心原因是坐标偏移未正确应用、剩余矩形计算逻辑错误,以及递归参数传递混乱,导致后续递归无法正确定位和处理剩余区域。以下是修复后的代码和关键说明:
修复后的代码
import matplotlib.pyplot as plt def draw_euclidean_tiling(width, height, ax=None, offset_x=0, offset_y=0): # 初始化绘图轴 if ax is None: fig, ax = plt.subplots() ax.set_aspect('equal', adjustable='box') ax.set_xlim(0, width) ax.set_ylim(0, height) # 终止条件:宽高相等(剩余正方形)或其中一个为0 if width == 0 or height == 0: return if width == height: # 绘制最后一个正方形 rect = plt.Rectangle((offset_x, offset_y), width, width, fill=False) ax.add_patch(rect) return # 确定当前最大正方形的边长 square_size = min(width, height) # 计算能放多少个这样的正方形 count = max(width, height) // square_size if width > height: # 沿x轴方向放置count个正方形 for i in range(count): x = offset_x + i * square_size rect = plt.Rectangle((x, offset_y), square_size, square_size, fill=False) ax.add_patch(rect) # 递归处理剩余矩形:宽为width % height,高为height,位置在最右侧 remaining_width = width % height draw_euclidean_tiling(remaining_width, height, ax, offset_x + count * square_size, offset_y) else: # 沿y轴方向放置count个正方形 for i in range(count): y = offset_y + i * square_size rect = plt.Rectangle((offset_x, y), square_size, square_size, fill=False) ax.add_patch(rect) # 递归处理剩余矩形:高为height % width,宽为width,位置在最上方 remaining_height = height % width draw_euclidean_tiling(width, remaining_height, ax, offset_x, offset_y + count * square_size) # 仅在初始调用时显示图像 if ax is None: plt.show() # 测试示例:比如宽5,高3(对应连分数[1;1,2]) draw_euclidean_tiling(5, 3)
关键修复点
- 坐标偏移正确传递:每次递归都传入当前剩余矩形的左上角坐标(
offset_x,offset_y),确保所有矩形绘制在正确位置。 - 简化铺砖逻辑:根据宽高大小,沿长轴放置尽可能多的最大正方形,避免原代码中混乱的x/y循环逻辑。
- 剩余矩形计算准确:使用取模运算
width % height或height % width得到剩余区域的尺寸,符合欧几里得算法的核心逻辑。 - 清晰的终止条件:当宽高相等(绘制最后一个正方形)或其中一个为0时停止递归,避免无效调用。
使用说明
调用函数时直接传入矩形的宽和高即可,比如draw_euclidean_tiling(7, 4)会绘制7x4矩形的欧几里得铺砖过程,对应连分数展开的可视化。
内容的提问来源于stack exchange,提问作者goodlander01
相关产品推荐
相关产品推荐

