|
| 1 | +import math |
| 2 | +import matplotlib.pyplot as plt |
| 3 | +plt.figure() |
| 4 | +def draw_line(x1, y1, x2, y2): |
| 5 | + plt.plot([x1, x2], [y1, y2], color = 'r', lw = 2) |
| 6 | + |
| 7 | +def draw_h_tree(x0, y0, length, level, factor): |
| 8 | + if level == 0: |
| 9 | + return |
| 10 | + |
| 11 | + coord_c_x = x0 - length / 2. |
| 12 | + coord_c_y = y0 |
| 13 | + coord_d_x = x0 + length / 2. |
| 14 | + coord_d_y = y0 |
| 15 | + |
| 16 | + coord_a_x = x0 - length / 2. |
| 17 | + coord_a_y = y0 + length / 2. |
| 18 | + coord_e_x = x0 - length / 2. |
| 19 | + coord_e_y = y0 - length / 2. |
| 20 | + coord_b_x = x0 + length / 2. |
| 21 | + coord_b_y = y0 + length / 2. |
| 22 | + coord_f_x = x0 + length / 2. |
| 23 | + coord_f_y = y0 - length / 2. |
| 24 | + |
| 25 | + draw_line(coord_c_x, coord_c_y, coord_d_x, coord_d_y) |
| 26 | + draw_line(coord_a_x, coord_a_y, coord_e_x, coord_e_y) |
| 27 | + draw_line(coord_b_x, coord_b_y, coord_f_x, coord_f_y) |
| 28 | + |
| 29 | + length /= math.sqrt(factor) |
| 30 | + level -= 1 |
| 31 | + draw_h_tree(coord_a_x, coord_a_y, length, level, factor) |
| 32 | + draw_h_tree(coord_b_x, coord_b_y, length, level, factor) |
| 33 | + draw_h_tree(coord_e_x, coord_e_y, length, level, factor) |
| 34 | + draw_h_tree(coord_f_x, coord_f_y, length, level, factor) |
| 35 | + |
| 36 | +if __name__ == "__main__": |
| 37 | + draw_h_tree(0, 0, 2, 5, 4) |
| 38 | + plt.tight_layout() |
| 39 | + plt.show() |
0 commit comments