编写程序以确定Emma从起始位置跳到最后一片云所需的最小跳数。
这里是完整的问题:https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem
某些测试用例失败。
示例1:
输入:1. 50
预期产量:28
示例2:
输入:1. 100
预期输出:53
示例3:
输入:1. 100。
预期输出:54
示例4:
85
0 1 0 1 0 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 1 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 1 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 0 1 0
预期输出:46
下面给出的计划的4个测试案例都将失败。
下面编写的代码没有提供所需的输出是什么问题?
def jumpingOnClouds(c):
moves = 0
i=0
while i < len(c)-1:
if c[i] == 0:
try:
if c[i]==c[i+2]:
moves+=1
i+=2
except:
pass
try:
if c[i]==c[i+1]:
moves+=1
i+=1
except:
pass
return moves
答案 0 :(得分:0)
如果出现异常,则不会增加索引。因此,如果输入是这样的,则它可能会陷入无限循环:[0 1 0 0]。首先从0开始。然后转到索引2。在下一个迭代中,您将访问a [4]。您将捕获异常。但是该程序陷入了无限循环,并且由于您没有增加索引而永远不会结束。
这是您方法的改进版本:
def min_moves(a, n):
i = 0
moves = 0
while i < n-1:
if i+2 < n and a[i+2] == 0:
i += 2
moves += 1
continue
if i+1 < n and a[i+1] == 0:
i += 1
moves += 1
continue
return moves