问题是假设一只兔子可以跳到最远50厘米。到达河对岸需要的最小跳跃次数是多少?
该函数应返回所需的最小跳跃次数,如果兔子无法到达河的另一侧,则返回-1。
rabbit((32, 46, 70, 85, 96, 123, 145)) # 3
然而
rabbit((40, 70, 150, 160, 180)) #-1 because 150-70 > 50
rabbit((30, 70, 75, 120, 160, 170, 180, 190, 200, 246, 258)) #7
def rabbit(rocks):
if len(rocks) <= 1:
return 0
elif rocks[1] - rocks[0] >= 50:
return -1
else:
return 1 + rabbit(rocks[2:])
当有一个&gt;步骤时,我无法得到-1。 50.为什么?
答案 0 :(得分:1)
else:
return 1 + rabbit(rocks[2:])
以上一行(至少)有两个问题:
rabbit
函数的返回值。rocks[2:]
总是跳两块石头?你应该根据岩石值来调整它。def rabbit(rocks, prev=0):
if rocks[0] - prev > 50:
return -1
p = rocks[0]
for i, x in enumerate(rocks):
if x - prev > 50:
ret = rabbit(rocks[i:], p)
if ret >= 0:
ret += 1
return ret
p = x
return 1
用法:
>>> rabbit((32, 46, 70, 85, 96, 123, 145))
3
>>> rabbit((40, 70, 150, 160, 180))
-1
>>> rabbit((30, 70, 75, 120, 160, 170, 180, 190, 200, 246, 258))
7
答案 1 :(得分:0)
这段代码怎么样?
import bisect
def rabbit(rocks, hop=50):
if not rocks:
raise ValueError('No rocks')
step = rocks[0]
steps = [step]
while True:
x = bisect.bisect_right(rocks, step + hop)
step = rocks[x - 1]
steps.append(step)
if x == len(rocks):
break
elif rocks[x] - step > hop:
raise ValueError('Too far between {0} and {1}'
''.format(rocks[x], step))
return steps
结果如下:
>>> rabbit([32, 46, 70, 85, 96, 123, 145])
[32, 70, 96, 145]
>>> rabbit([30, 70, 75, 120, 160, 170, 180, 190, 200, 246, 258])
[30, 75, 120, 170, 200, 246, 258]
>>> rabbit([40, 70, 150, 160, 180])
Traceback (most recent call last):
...
ValueError: Too far between 150 and 70
>>> rabbit([])
Traceback (most recent call last):
...
ValueError: No rocks
您可以按len(rabbit(rocks)) - 1
获得许多步骤。