Анимация просто не работает с помощью ноутбука Jupyter. Другие анимации работают без проблем, когда% matplotlib qt включен в код.
from matplotlib.patches import Rectangle
import random
import time
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def swap(A, i, j):
if (i != j):
A[i], A[j] = A[j], A[i]
def insertion_sort(L):
for i in range (1, len(L)):
j = i
while (j > 0) and (L[j] < L[j - 1]):
swap(L, j, j - 1)
j -= 1
yield L
def insertion_sort_animation(N):
L = []
for i in range (N):
L.append(i+1)
random.seed(time.time())
random.shuffle(L)
fig, ax = plt.subplots()
ax.set_xlim(0, N * 10)
ax.set_ylim(0, N + 20)
graf = []
for i in range (N):
prav = Rectangle((i * 10, 0), 10, L[i])
graf.append(prav)
for prav in graf:
ax.add_patch(prav)
text = ax.text(ax.get_xlim()[1] - 2*N, ax.get_ylim()[1] - 0.1 * N, "", fontsize = 12)
SortL = []
for L in insertion_sort(L):
SortL.append(list(L))
iteration = 0
def next_iter(A, g, i):
for i in range (N):
g[i].set_height(A[i])
i += 1
text.set_text("# of swaps = {}".format(i))
animation = anim.FuncAnimation(fig, next_iter, frames = SortL, fargs = (graf, iteration), repeat = False, interval = 1)
plt.show()
Код должен быть анимацией для вставки сортировки списка со случайными элементами в диапазоне n с использованием патча прямоугольников. Анимация даже не запускается.