Прикреплённый файл «Treeops.py»
Загрузка 1 #!/usr/bin/python
2 # coding: utf8
3 import Tree
4 import pickle
5 import pygame
6 from math import *
7
8 def save(ATree, File, V=0):
9 for k in ATree:
10 print >> File, (k, ATree[k])
11 print >> File, ATree.V
12 return File
13
14 def load(ATree, File):
15 S=eval(File.readline())
16 while type(S) is not int:
17 ATree[S[0]]=S[1]
18 S=eval(File.readline())
19 return ATree
20
21 def restore(CTree, File, upkey=None, Buffer=[]):
22 S=Buffer and Buffer.pop() or eval(File.readline())
23 if type(S) is int or upkey!=None and S[0]>upkey:
24 Buffer.append(S)
25 return CTree()
26 T=CTree(S[0],S[1],restore(CTree, File, S[0]), restore(CTree, File, upkey))
27 return T
28
29 def draw(T,M,fw):
30 def drawtree(scr, T, seq):
31 Node1,Node2=font.render(str(T.key),1,fgt,bg),font.render(T.value,1,fgt,bg)
32 NR1,NR2=Node1.get_rect(),Node2.get_rect()
33 R,row=scr.get_rect(),int(log(seq+0.1,2))
34 cell=seq-2**row
35 X,Y=R.width/2**row*cell+R.width/2**(row+1),row*(CH+dCH)
36 if T.LT: pygame.draw.line(scr, fgl, (X,Y+dC2), drawtree(scr, T.LT, seq*2))
37 if T.GT: pygame.draw.line(scr, fgl, (X,Y+dC2), drawtree(scr, T.GT, seq*2+1))
38 scr.blit(Node1,(X-NR1.width/2,Y))
39 scr.blit(Node2,(X-NR2.width/2,Y+CH/2+dC2))
40 return (X,Y+dC2)
41
42 dCH,dCW,dC2=fw/4,1,1
43 pygame.init()
44 pygame.font.init()
45 font = pygame.font.Font(None, fw)
46 CW,CH=font.size("+"+"n"*M)
47 CH=CH*2+dC2
48 W=(CW+dCW)*2**(T.H)-1
49 H=(CH+dCH)*T.H
50 screen = pygame.display.set_mode((W,H))
51 fgt,fgl,bg=pygame.Color("wheat"),pygame.Color("green"),pygame.Color("midnightblue")
52 drawtree(screen, T, 1)
53 while pygame.event.wait().type not in (pygame.QUIT, pygame.KEYDOWN, pygame.KEYUP):
54 pygame.display.flip()
55 pygame.quit()
56
57 if __name__ == "__main__":
58 Num=24
59 # Генерация
60 T=Tree.gen(Num,Tree=Tree.AVLtree)
61 # Рисование
62 draw(T,len(str(Num)),24*24/Num)
63 # Запись
64 save(T,file("o","w")).close()
65 # Построение
66 T1=load(Tree.AVLtree(),file("o"))
67 print "load =",T==T1
68 draw(T1,len(str(Num)),24*24/Num)
69 # Чтение
70 T2=restore(Tree.AVLtree,file("o"))
71 print "restore =",T==T2
72 # Сериализация и десериализация
73 f=file("o.pikcle","w")
74 pickle.dump(T,f)
75 f.close()
76 f=file("o.pikcle")
77 T3=pickle.load(file("o.pikcle"))
78 print "pickle =",T==T3
Прикреплённые файлы
Для ссылки на прикреплённый файл в тексте страницы напишите attachment:имяфайла, как показано ниже в списке файлов. Не используйте URL из ссылки «[получить]», так как он чисто внутренний и может измениться.- [получить | показать] (2011-09-26 11:35:36, 5.7 KB) [[attachment:Tree.py]]
- [получить | показать] (2011-09-26 11:35:36, 1.2 KB) [[attachment:Treecount.py]]
- [получить | показать] (2011-09-26 11:35:36, 2.4 KB) [[attachment:Treeops.py]]
- [получить | показать] (2011-09-26 11:35:36, 1.7 KB) [[attachment:compare.py]]
Вам нельзя прикреплять файлы к этой странице.