op c3 a9rations des file de priorit c3 a9s en python

Solutions on MaxInterview for op c3 a9rations des file de priorit c3 a9s en python by the best coders in the world

showing results for - "op c3 a9rations des file de priorit c3 a9s en python"
Emilia
25 Feb 2019
1class heap:
2    def __init__(self):
3        self.t=[]
4
5    def push(self, x):
6        t=self.t
7        t.append(x)
8        k=len(t)-1
9        while k:
10            m=(k-1)//2
11            if t[k]<t[m]:
12                t[k], t[m]=t[m], t[k]
13                k=m
14            else:
15                break
16    def pop(self):
17        t=self.t
18        if not t:
19            raise IndexError("pop from empty heap")
20        if len(t)==1:
21            return t.pop()
22        root=t[0]
23        t[0]=t.pop()
24        k=0
25
26        while True:
27            L=[i for i in [2*k+1, 2*k+2] if i<len(t)]
28            if not L:
29                break
30            mini=min(t[i] for i in L)
31            if t[k]<mini:
32                break
33            for i in L:
34                if t[i]==mini:
35                    t[i],t[k]=t[k], t[i]
36                    k=i
37                    break
38
39        return root
40
41
42from random import randrange
43
44
45n=6
46h=heap()
47
48
49for _ in range(n):
50    x=randrange(10,100)
51    h.push(x)
52    print(x, h.t)
53
54print()
55
56for _ in range(n):
57    print(h.pop())
58