这就是我要解决的问题:
Given a straight line with the starting point "O". Two hares begin simultaneously moving along this straight line away from this point. They started at different distances from point O.
我需要在编程语言Python中创建一个函数,它将显示出兔子与O点的距离。在
有以下价值观:
它显示兔子在两次跳跃之间休息的时间(多少时间单位)。跳跃本身持续0个单位。 众所周知,所有值都是整数:
我需要编写一个函数,它使用两个hare的所有命名值,并且可以显示
这是我的代码:
from fractions import Fraction
def meet_me(pos1, jump_distance1, sleep1, pos2, jump_distance2, sleep2):
if pos1 == pos2:
pos1 = pos2
elif (jump_distance1 / sleep1 > jump_distance2 / sleep2 and pos1 > pos2) or (jump_distance2 / sleep2 > jump_distance1 / sleep1 and pos2 > pos1):
pos1 = -1
elif jump_distance1 / sleep1 == jump_distance2 / sleep2:
pos1 = -1
else:
if pos1 > pos2:
while pos1 != pos2:
pos1 += Fraction(jump_distance1, sleep1)
pos2 += Fraction(jump_distance2, sleep2)
if pos2 > pos1:
pos1 = -1
break
elif pos2 > pos1:
while pos1 != pos2:
pos1 += Fraction(jump_distance1, sleep1)
pos2 += Fraction(jump_distance2, sleep2)
if pos1 > pos2:
pos1 = -1
break
return pos1
print(meet_me(1, 2, 1, 2, 1, 1)) # = > 3
print(meet_me(1, 2, 1, 1, 2, 1)) # => 3
print(meet_me(1, 2, 3, 4, 5, 5)) # => -1
print(meet_me(3, 5, 10, 4, 1, 2)) # => 8
print(meet_me(100, 7, 4, 300, 8, 6)) # => 940
print(meet_me(0, 1, 1, 1, 1, 1)) # => -1
print(meet_me(10, 7, 7, 5, 8, 6)) # => 45
print(meet_me(1, 7, 1, 15, 5, 1)) # => 50
我的预期输出是:
^{pr2}$我不明白我做错了什么。这是我得到的输出:
1
-1
-1
940
-1
25
50
这是我的建议
但是,它不会返回期望值,但请阅读我对该主题的评论(我认为解决方案是错误的)
总之,
如果没有,您可以修改我的代码(类似的代码应该可以正常工作)
我花了比我预期的时间更长的时间,但这是我的解决方案,它给出了你想要的答案。在
我看你有两个问题。首先,你要在它们移动之前检查它们是否相等,问题似乎表明这不应该发生
参见示例2:print(meet_me(1,2,1,1,2,1))#=>;3而不是1
第二个问题是,你把野兔当作一个不断移动的过程,而不是像问题所要求的那样移动然后休息。一只跑得慢的兔子可能落后于跑得快的兔子,在被甩在后面之前会超过它几次,所以你必须做一个更复杂的检查,看看它们是否永远不会相遇。在
相关问题 更多 >
编程相关推荐