Codingame《雷神力量第一章》:变量声明位置影响代码运行的原因?
关于《Power of Thor Episode 1》中变量声明位置影响程序运行的疑问解答
我在解决Codingame的《Power of Thor Episode 1》时遇到一个问题:已经写出能通过所有测试的代码,但把dirx和diry的声明移到while循环外部后,程序就无法正常运行,想搞清楚两种写法的差异和失效原因。
正确代码
light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()] tx = initial_tx ty = initial_ty # game loop while True: remaining_turns = int(input()) # The remaining amount of turns Thor can move. Do not remove this line. dirx = "" diry = "" if(ty > light_y): diry = "N" ty -= 1 elif(ty < light_y): diry = "S" ty += 1 if(tx > light_x): dirx = "W" tx -= 1 elif(tx < light_x): dirx = "E" tx += 1 # Write an action using print # To debug: print("Debug messages...", file=sys.stderr, flush=True) print(diry + dirx) # A single line providing the move to be made: N NE E SE S SW W or NW
失效代码(仅变量声明位置不同)
light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()] tx = initial_tx ty = initial_ty dirx = "" diry = "" # game loop while True: remaining_turns = int(input()) # The remaining amount of turns Thor can move. Do not remove this line. if(ty > light_y): diry = "N" ty -= 1 elif(ty < light_y): diry = "S" ty += 1 if(tx > light_x): dirx = "W" tx -= 1 elif(tx < light_x): dirx = "E" tx += 1 # Write an action using print # To debug: print("Debug messages...", file=sys.stderr, flush=True) print(diry + dirx) # A single line providing the move to be made: N NE E SE S SW W or NW
原因解析
这和作用域无关,核心是变量是否被循环重置:
- 正确代码中,
dirx和diry在每次循环开始时都会被重新赋值为空字符串。当Thor已经到达某一轴的目标位置时(比如tx等于light_x),对应的方向变量会保持为空,不会带上上一轮的旧值,最终输出的移动指令是正确的。 - 失效代码中,
dirx和diry只在循环外初始化一次。如果某一轮Thor需要朝某个方向移动(比如设dirx="E"),下一轮当Thor已经在该轴的目标位置时,代码不会给对应变量重新赋值,它会保留上一轮的旧值,导致输出错误的指令(比如本来应该输出"N",结果输出"NE")。
举个具体场景:假设Thor的x坐标已经和光源的x坐标一致,此时循环中tx相关的判断都不会触发,dirx如果是上一轮的"E",就会被保留,打印时就会把这个旧方向和当前正确的y方向拼接,生成错误的移动指令,自然通不过测试用例。
内容的提问来源于stack exchange,提问作者Vexarial
相关产品推荐
相关产品推荐

