SharedDragon Fractal.ipynbOpen in CoCalc
Dragon Fractal in Python

The Dragon Fractal

import numpy as np
import matplotlib.pyplot as plt
s = ''

def replace(x):
    return x.replace('V','m').replace('M','V').upper()[::-1]

def dragonNext(x):
    return x + 'V' + replace(x)

def iterateDragon(N):
    x = s
    for i in range(N):
        x = dragonNext(x)
    return x

def nextDir(curr,dir):
    if curr == 'E' and dir == 'V':
        return 'S'
    if curr == 'W' and dir == 'V':
        return 'N'
    if curr == 'S' and dir == 'V':
        return 'W'
    if curr == 'N' and dir == 'V':
        return 'E'
    if curr == 'E' and dir == 'M':
        return 'N'
    if curr == 'W' and dir == 'M':
        return 'S'
    if curr == 'S' and dir == 'M':
        return 'E'
    if curr == 'N' and dir == 'M':
        return 'W'

def strToDir(x):
    lst = 'N'
    for char in x:
        lst += nextDir(lst[-1],char)
    return lst

def points(N):
    str = iterateDragon(N)
    dir = strToDir(str)
    x,y = [0],[0]
    for char in dir:
        if char == 'N':
            x += [x[-1]]
            y += [y[-1]+1]
        if char == 'E':
            x += [x[-1]+1]
            y += [y[-1]]
        if char == 'S':
            x += [x[-1]]
            y += [y[-1]-1]
        if char == 'W':
            x += [x[-1]-1]
            y += [y[-1]]
    return np.array(x),np.array(y)

def dragon(N):
    x,y = points(N)
    plt.plot(x,y,color='black')
dragon(15)