import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],'('+a[1]+' '+b[1]+')' ))
temp = 0
cost = 0
index= 0
for i in T[0][1]:
if i == "(":
temp = temp + 1
elif i == ")":
temp = temp - 1
elif i == " ":
continue
else:
cost = cost + (temp*f[int(i)])
if i != "(" or ")" or " ":
index*=10
index+f[int(i)]
print(cost)
I am trying to make Huffman coding prefix-free cost code. my code works well, but when inputs are more than 9, it makes an error. I found when f[int(i)] is more than 10, it makes an error because the code reads it as 1 and 0. how can I fix this error?
> 43 13 12 16 9 7
230#correct
> 13 5 11 7 15 1 14 20 10 12 9
425#wrong
the cost can be calculate while building the huffman tree.
import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],0,str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],a[0]+b[0]+a[1]+b[1],'('+a[2]+' '+b[2]+')' ))
cost=heapq.heappop(T)[1]
print(cost)
Think "i" walk to the arrow, int(i) is 1, but the expect value is 10.
[(117, '(((2 9) (((5 1) 3) 0)) ((6 4) ((10 8) 7)))')]
^
You can check the code, it store the index value and caculate the cost after the walk through the full index string.
import heapq
f = [int(x) for x in input().split()]
T=[]
for i in range(len(f)):
heapq.heappush(T,(f[i],str(i)))
while len(T)>1:
a=heapq.heappop(T)
b=heapq.heappop(T)
heapq.heappush(T,(a[0]+b[0],'('+a[1]+' '+b[1]+')' ))
temp = 0
cost = 0
index= -1
for i in T[0][1]:
if i == "(":
temp = temp + 1
elif i == ")":
if index != -1:
cost = cost + (temp*f[index])
index = -1
temp = temp - 1
elif i == " ":
if index != -1:
cost = cost + (temp*f[index])
index = -1
else:
if index == -1:
index = int(i)
else:
index = 10 * index + int(i)
print(cost)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.