【发布时间】:2017-11-27 20:28:55
【问题描述】:
我正在尝试来自 Hackerrank 的相等堆栈问题:https://www.hackerrank.com/challenges/equal-stacks/problem。
谁能帮我理解以下两个代码的逻辑差异。第一个失败,另一个成功:
首先(我的解决方案):
n1, n2, n3 = map(int, input().split())
H1 = list(map(int, input().split()))
H2 = list(map(int, input().split()))
H3 = list(map(int, input().split()))
sum_h1 = sum(H1)
sum_h2 = sum(H2)
sum_h3 = sum(H3)
#print (sum_h1,sum_h2,sum_h3)
while not (sum_h1 == sum_h2 and sum_h2 == sum_h3):
if sum_h1 > sum_h2 or sum_h1 > sum_h3:
#t = H1.pop()
sum_h1 -= H1[0]
#print ("Checking:",sum_h1)
if sum_h2 > sum_h1 or sum_h2 > sum_h3:
#t = H2.pop()
sum_h2 -= H2[0]
if sum_h3 > sum_h1 or sum_h3 > sum_h2:
#t = H3.pop()
sum_h3 -= H3[0]
print (sum_h1)
第二个解决方案(正确):
n1, n2, n3 = map(int, input().split())
H1 = list(map(int, input().split()))[::-1]
H2 = list(map(int, input().split()))[::-1]
H3 = list(map(int, input().split()))[::-1]
sum_h1 = sum(H1)
sum_h2 = sum(H2)
sum_h3 = sum(H3)
#print (sum_h1,sum_h2,sum_h3)
while not (sum_h1 == sum_h2 and sum_h2 == sum_h3):
if sum_h1 > sum_h2 or sum_h1 > sum_h3:
t = H1.pop()
sum_h1 -= t
if sum_h2 > sum_h1 or sum_h2 > sum_h3:
t = H2.pop()
sum_h2 -= t
if sum_h3 > sum_h1 or sum_h3 > sum_h2:
t = H3.pop()
sum_h3 -= t
print (sum_h1)
我知道在第二个中我们正在反转输入数组。但这有什么不同吗?
我完全不解。
请帮我指出第一个代码的问题。
提前致谢。
【问题讨论】: