This morning I was taking a break from work and watched the following video
And thought to myself, how would I go about doing something like that in python. Normally I dont do much in the way of graphics (beyond using things like matplotlib to make a pretty graph) so thought this would be a nice challenge.
So what did i use? I learnt just enough about the Tkinter python library to make a version of the animations in the video (for a badly implemented merge sort).
The code starts of by showing you the array of numbers its going to try and sort. Then as it performs a merge sort it first of all shows you which section its working on (black outlines) and how much it has sorted so far (red blocks)
Not much use but it was a bit of fun to play with for a while.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
from Tkinter import* import time import random w = 800 h = 600 slow = 0.05 def sort(data,startx,depth): time.sleep(slow) x= startx y =h bar = cv.create_rectangle(x,y,x+2*len(data),y-(y/depth),fill="blue") cv.update() x= startx y =h if len(data)>1: pivot = (len(data))/2 list1 = sort(data[0:pivot],startx,depth+1) list2 = sort(data[pivot:],startx+2*pivot,depth+1) list3 = [None]*(len(list1)+len(list2)) i = 0 j = 0 k = 0 for item in list3: fail = 0 if i<len(list1): if j<len(list2): fail = 1 if list1[i]>list2[j]: list3[k] = list2[j] j+=1 else: list3[k] = list1[i] i+=1 if fail == 0: if i == len(list1): list3[k] = list2[j] j+=1 else: if j == len(list2): list3[k] = list1[i] i+=1 k+=1 time.sleep(slow) bar = cv.create_rectangle(x,y,x+2*len(list3),y-(y/(2*depth)),fill="red") cv.update() return list3 else: return data x =0 y = h barWidth = 2 lst = [0]*(w/2) for item in lst: i = random.randrange(0, 5000, 1)/100.0 lst[lst.index(item)]=i print lst root = Tk() root.title("Sorting Algorithm Animation") cv = Canvas(width=w, height=h, bg='black') cv.pack() cv.update() x= 0 y =h for item in lst: bar = cv.create_rectangle(x, y, x+barWidth, y-(item*10), fill="red") x += barWidth cv.update() time.sleep(slow*10) lst = sort(lst,0,1) x= 0 y =h cv.delete(ALL) for bars in lst: time.sleep(slow/4) barSorted = cv.create_rectangle(x, y, x+barWidth, y-(bars*10), fill="green") x += barWidth cv.update() print lst root.mainloop() |