Search code examples
pythonrecursionmatplotlibindex-error

IndexError with matplotlib


I've been trying around with this piece of code to get it to draw a C-Curve(https://en.wikipedia.org/wiki/Lévy_C_curve), but somehow it keeps giving me this error:

IndexError: list index out of range

But the length of the list seems to be fine to me as it's set to n-1,so why does this error keep showing up?

I've had this exact same problem a little while ago when I tried something similar (the Sierprinski triangle), so I'd really appreciate some help.

import matplotlib.pyplot as plt
from math import *

def DrawC(direction, length, n):
    """Drawing the curve."""

    if n > 0:
        direction = direction + (pi / 4.0)
        DrawC(direction, length / sqrt(2.0), n-1)
        direction = direction - (pi / 2.0)
        DrawC(direction, length / sqrt(2.0), n-1)
    else:
        x = x_lst[-1] + length * cos(direction)
        y = y_lst[-1] + length * sin(direction)
        x_lst.append(x)
        y_lst.append(y)

n = int(raw_input('Generation of the curve: '))

x_lst = []
y_lst = [-150]


direction = pi / 2
length = 300
DrawC(direction, length, n)

plt.plot(x_lst, y_lst)
plt.title("C-curve")
plt.axis([-350, 350, -350, 350])
plt.show()

raw_input('Push the ENTER key: ')

Solution

  • The lists x_lst should not start empty.

    Whatever path is taken in your code, when x = x_lst[-1] + length * cos(direction) the list cannot be empty. This makes sense as you are building a list of points, so start with, for instance, [0] for x_lst. That gives me nice pictures anyway :-)