【发布时间】:2021-03-10 18:49:50
【问题描述】:
给定1 到F 的任意范围以及起点S 和终点G,这样我们唯一可以走的方向是L 左台阶和R 右台阶(也是任意的),创建一个通用解决方案,该解决方案将返回从S 到R 所需的步数如果可能否则返回not possible。
您被绑定到[1, F] 范围内,这意味着如果下一步移动大于F 或小于1,则您不能移动L 或R 步数
例子:
F = 100
S = 2
G = 1
L = 0
R = 1
Output: not possible
F = 10
S = 1
G = 10
L = 1
R = 2
Output: 6
Explanation: [1 -> 3(R) -> 5(R) -> 7(R) -> 9(R) -> 8(L) -> 10(R)]
我在课堂上遇到过这个问题,我们当前的主题是二分搜索和分而治之。这是我的方法,但这并不能解决一个隐藏的案例。
F = int(input())
S = int(input())
G = int(input())
L = int(input())
R = int(input())
count = 0
while S != G:
dist = abs(S - G) # Takes the current distance from S to G
if S > G:
if S-L > 0:
S -= L
count += 1
else:
S += R
count += 1
else:
if S+R <= F:
S += R
count += 1
else:
S -= L
count += 1
if dist == abs(S - G): # If distance doesn't change after trying
print("not possible") # a move, conclude that it is not possible.
break
if S == G: print(count)
【问题讨论】:
-
我投票结束这个问题,因为它没有显示任何努力
-
怎么样?如果我提出自己的代码不适用于所有情况,它会表现出努力吗?这个问题真的很简单吗?
-
用我的草稿代码更新了我的帖子。它适用于大多数情况,我不知道我的方法中缺少什么,但我希望这能显示出一些努力。
标签: python search integer binary-search divide-and-conquer