從後面往前讀,讀到f, g, h再往前找答案,因為python的str可以用split,且可以無痛轉成int
總之就是從後面開始讀,算好就把數值替換掉
x = input()
x = x.split(' ')
for i in range(len(x)-1, -1, -1):
if x[i] == 'f':
n = x[i+1] * 2 - 3
del x[i]
x[i] = n
if x[i] == 'g':
n = x[i+1] * 2 + x[i+2] - 7
del x[i]
del x[i]
x[i] = n
if x[i] == 'h':
n = x[i+1] * 3 - x[i+2] * 2 + x[i+3]
del x[i]
del x[i]
del x[i]
x[i] = n
else:
x[i] = int(x[i])
print(x[0])
從後面往前讀,讀到f, g, h再往前找答案,因為python的str可以用split,且可以無痛轉成int
總之就是從後面開始讀,算好就把數值替換掉
def main(): x = input().split(' ') for i in range(len(x)-1, -1, -1): if x[i] == 'f': x[i] = x[i+1] * 2 - 3 del x[i+1:i+2] continue if x[i] == 'g': x[i] = x[i+1] * 2 + x[i+2] - 7 del x[i+1:i+3] continue if x[i] == 'h': x[i] = x[i+1] * 3 - x[i+2] * 2 + x[i+3] del x[i+1:i+4] continue x[i] = int(x[i]) print(x[0]) main()
AC 19ms 3.4MB