pythonpython-3.xturtle-graphicspython-turtlefractals

Create a Sierpinksi Triangle using 0L-System with Python


I need to create a Sierpinksi Triangle using 0L-System with Python. See here: enter image description here I'm stuck here, I can't complete the triangle.

My code:

from turtle import *


def sierpinksi(size: int, n: int):
    if n == 0:        
        for i in range(0, 3):
            forward(size)
    else:

        sierpinksi(size//2, n-1) #F
        right(120)               #-

        sierpinksi(size//2, n-1) #G
        left(120)                #+
        sierpinksi(size//2, n-1) #F
        left(120)                #+
        sierpinksi(size//2, n-1) #G
        right(120)               #-
        sierpinksi(size//2, n-1) #F


sierpinksi(100, 2)
done()

My result: enter image description here


Solution

  • We can put a band-aid on your code by finishing the triangle after the fact and using floating division instead of integer division:

    from turtle import *
    
    ANGLE = 120
    
    def sierpinksi(size, n):
    
        def sierpinksi_recursive(size, n):
            if n == 0:
                for _ in range(3):
                    forward(size)
            else:
                sierpinksi_recursive(size/2, n-1)  # F
                right(ANGLE)                       # -
                sierpinksi_recursive(size/2, n-1)  # G
                left(ANGLE)                        # +
                sierpinksi_recursive(size/2, n-1)  # F
                left(ANGLE)                        # +
                sierpinksi_recursive(size/2, n-1)  # G
                right(ANGLE)                       # -
                sierpinksi_recursive(size/2, n-1)  # F
    
        sierpinksi_recursive(size, n)
    
        for _ in range(2):
            right(ANGLE)
            forward(size * 3)
    
    speed('fastest')  # because I have no patience
    sierpinksi(100, 3)
    done()
    

    But I believe the real problem is you've not embraced the spirit of the L-system, ignoring the starting production 'F-G-G' and not implementing the production rules. Your code does a lot of redundant drawing which makes it relatively slow. If instead we implement the L-system head on, we address all the issues:

    from turtle import *
    
    ANGLE = 120
    
    RULES = {
        'F': 'F-G+F+G-F',
        'G': 'GG',
        '+': '+',
        '-': '-',
    }
    
    def sierpinksi(string, size, n):
        if n:
            string = ''.join(RULES[c] for c in string)
            sierpinksi(string, size/2, n-1)
        else:
            for c in string:
                if c in 'FG':
                    forward(size)
                elif c == '+':
                    left(ANGLE)
                elif c == '-':
                    right(ANGLE)
    
    speed('fastest')  # because I have no patience
    sierpinksi('F-G-G', 300, 3)
    done()