###### tags: `程式設計` # 第 9 週 - 碎形 [**維基百科**](https://zh.wikipedia.org/wiki/%E5%88%86%E5%BD%A2) ## Module matplotlib `python -m pip install -U matplotlib` ## 謝爾賓斯基三角形(Sierpinski triangle) [**維基百科**](https://zh.wikipedia.org/wiki/%E8%AC%9D%E7%88%BE%E8%B3%93%E6%96%AF%E5%9F%BA%E4%B8%89%E8%A7%92%E5%BD%A2) ```python= import matplotlib.pyplot as plt import math def triangle(x, y, l, xlist, ylist) : if l <= 1 : xlist.append(x) ylist.append(y) return triangle(x, y, l // 2, xlist, ylist) triangle(x + l // 2, y, l // 2, xlist, ylist) triangle(x + l // 4, y + math.sin(math.pi / 3) * l / 2, l // 2, xlist, ylist) def main() : plt.figure() plt.xlim(0, 300) plt.ylim(0, 300) xlist, ylist = [], [] triangle(10, 10, 256, xlist, ylist) plt.plot(xlist, ylist, markersize = 1) plt.show() if __name__ == '__main__' : main() ``` ## 謝爾賓斯基地毯 [**維基百科**](https://zh.wikipedia.org/wiki/%E8%B0%A2%E5%B0%94%E5%AE%BE%E6%96%AF%E5%9F%BA%E5%9C%B0%E6%AF%AF) ```python= import matplotlib.pyplot as plt import math def rectangle(x, y, l, xlist, ylist) : if l <= 1 : xlist.append(x) ylist.append(y) return rectangle(x, y, l // 3, xlist, ylist)#左下 rectangle(x, y + l // 3, l // 3, xlist, ylist)#左中 rectangle(x, y + l // 3 * 2, l//3, xlist, ylist)#左上 rectangle(x + l // 3, y, l // 3, xlist, ylist)#中下 rectangle(x + l // 3, y + l // 3 * 2, l // 3, xlist, ylist)#中上 rectangle(x + l // 3 * 2, y, l // 3, xlist, ylist)#右下 rectangle(x + l // 3 * 2, y + l // 3, l // 3, xlist, ylist)#右中 rectangle(x + l // 3 * 2, y + l // 3 * 2, l // 3, xlist, ylist)#右上 def main() : plt.figure() plt.xlim(0, 300) plt.ylim(0, 300) xlist, ylist = [], [] rectangle(10, 10, 256, xlist, ylist) plt.plot(xlist, ylist, '.') plt.show() if __name__ == '__main__' : main() ``` ## 科赫曲線(雪花) [**維基百科**](https://zh.wikipedia.org/wiki/%E7%A7%91%E8%B5%AB%E6%9B%B2%E7%B7%9A) ```python= import matplotlib.pyplot as plt import math def line(x, y, d, l, xlist, ylist) : if l <= 1 : xlist.append(x) ylist.append(y) return #******** # #這邊自己寫~~是作業喔!!! # # ******** def main() : plt.figure() plt.xlim(0, 300) plt.ylim(0, 300) xlist, ylist = [], [] line() plt.plot(xlist, ylist, '.') plt.show() if __name__ == '__main__' : main() ```