heap enhancements

rontoto jezkator at gmail.com
Fri Jan 3 20:13:12 EST 2020


Hi guys, the code is working, but I want know, what I can improve on this code. It is like implementation of the simulation of shipment clearance in the depot according to priority and available deliveries. How can I do it better? Can u show me? Thnx for your time.
Input:

24 K
13 H
25 R
1 M
-4 T0
15 G
4 C
-1 T1
-3 T2
12 Y

Code:

import sys
class MaxHeap:
    def __init__(self):
        self.heap =[]
    def bubble_up(self, i):
        while i > 0:
            j = (i - 1) // 2
            if self.heap[i] <= self.heap[j]:
                break
            self.heap[j], self.heap[i] = self.heap[i], self.heap[j]
            i = j
    def insert(self, k):
        self.heap += [k]
        self.bubble_up(len(self.heap) - 1)
    def peek(self):
        return self.heap[0]
    def size(self):
        return len(self.heap)
    def is_empty(self):
        return self.size() == 0
    def bubble_down(self, i):
        n = self.size()
        while 2 * i + 1 < n:
            j = 2 * i + 1
            if j + 1 < n and self.heap[j] < self.heap[j + 1]:
                j += 1
            if self.heap[i] < self.heap[j]:
                self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
            i = j
 
    def pop(self):
        element = self.heap[0]
        self.heap[0] = self.heap[-1]
        self.heap.pop()
        self.bubble_down(0)
        return element
 
y = sys.stdin.read().splitlines()
z = list()
for line in y:
    row=list(map(str, line.split()))
    z.append(row)
 
def checking(a):
    for char in a:
        if char not in "0123456789-":
            return False
    return True
 
for i in range (len(z)):
    for j in range (len(z[i])):
        d=z[i][j]
        if d.isdigit() is True:
            z[i][j]=int(z[i][j])
        q=checking(d)
        if q is True:
            z[i][j]=int(z[i][j])
H=MaxHeap()
for t in range (len(z)):
    if z[t][0]>0:
        H.insert(z[t])
    if z[t][0] < 0:
        print(z[t][1],sep="",end="")
        print(": ",end="")
        e=z[t][0]
        while e<0 and (H.is_empty()) is False:
            u=H.pop()
            print(u[1],end=" ")
            e=e+1
        print("")
print("Depo: ",end="")
while (H.is_empty()) is not True:
    u_1=H.pop()
    print(u_1[1],end=" ")



Output:

T0: R K H M
T1: G
T2: C
Depo: Y


More information about the Python-list mailing list