Jan-04-2020, 03:40 AM
Hi guys, the code is working, but I want know, what I can improve on my code. It is like implements 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
[/input]
[input]
24 K
13 H
25 R
1 M
-4 T0
15 G
4 C
-1 T1
-3 T2
12 Y
[/input]
import sys chain = sys.stdin.read().splitlines() array_z = list() for line in chain: row=list(map(str, line.split())) array_z.append(row) #every line in input changes into 2D array def checking(chain): "checking if characters are numbers or not" for char in chain: if char not in "0123456789-": return False return True class MaxHeap: def __init__(self): """heap __init__ constructor""" self.heap =[] def bubble_up(self, i): """"bubble the element up if condition is ok """ 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): """insert element in heap""" self.heap += [k] self.bubble_up(len(self.heap) - 1) def peek(self): """return the biggest element""" return self.heap[0] def size(self): """return quantity of elements in heap""" return len(self.heap) def is_empty(self): """is heap empty?""" return self.size() == 0 def bubble_down(self, i): """bubble down the element""" 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): """delete the biggest element and change the heap""" element = self.heap[0] self.heap[0] = self.heap[-1] self.heap.pop() self.bubble_down(0) return element for i in range (len(array_z)): for j in range (len(array_z[i])): if checking(array_z[i][j]) is True: array_z[i][j]=int(array_z[i][j]) Heap=MaxHeap() for a in range (len( array_z)): if array_z[a][0]>0: Heap.insert( array_z[a]) if array_z[a][0] < 0: print( array_z[a][1]+": ",end="") #print name of delivery index_of_package= array_z[a][0] while index_of_package<0 and Heap.is_empty() is False: delivery_package=Heap.pop() print(delivery_package[1],end=" ") #print name of package in delivery index_of_package+= 1 print("") print("Depo: ",end="") while Heap.is_empty() is False: depo_package=Heap.pop() print(depo_package[1],end=" ") #print name of package in depo
Output:T0: R K H M
T1: G
T2: C
Depo: Y