CocoaChina 11-08
python-为什么此代码与查找公倍数无关?
index_new4.html
../../../zaker_core/zaker_tpl_static/wap/tpl_keji1.html

 

分配:

You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction ( i.e, toward positive infinity ) .

The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump.

The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump.

You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO.

我如何才能替换 while m

x1 = 0v1 = 3mul1 = 0 # Multiple of Kangaroo 1a = [ ] # Multiples of Kangaroo 1 Listx2 = 4v2 = 2mul2 = 0 # Multiple of Kangaroo 2b = [ ] # Multiples of Kangaroo 2 Listm = 0while m < 10000: # Limited search i = 0 mul1 += x1 + ( i*v1 ) a.append ( mul1 ) mul2 += x2 + ( i*v2 ) b.append ( mul2 ) i += 1 conj = list ( set ( a ) .intersection ( b ) ) # List of common elements if len ( conj ) > 0: # Checking if conj has some values for x in range ( len ( conj ) ) : print ( conj [ x ] ) # Prints common value break m += 1

我需要得到

YES

如果我输入

0342

我需要

如果我输入

0253

最佳答案

您可以通过一种更简单的方法解决此问题 .

假设小室以相同的速度跳跃 ( 两者每分钟具有相同的跳跃次数 , 只是每个跳跃的每次跳跃距离可以不同 ) , 您将具有以下内容 ( 以数学术语表示 ) :

x_final = x1 + v1 * num_jumpsx_final = x2 + v2 * num_jumps

做一些重组 ( 用数学术语 ) , 我们得到:

x1 + v1 * num_jumps = x2 + v2 * num_jumpsx1 - x2 = v2 * num_jumps - v1 * num_jumpsx1 - x2 = ( v2 - v1 ) * num_jumps ( x1 - x2 ) / ( v2 - v1 ) = num_jumps

现在有了价值

x1 = 0v1 = 3x2 = 4v2 = 2 ( x1 - x2 ) / ( v2 - v1 ) = num_jumps ( 0 - 4 ) / ( 2 - 3 ) = num_jumps ( -4 ) / ( -1 ) = num_jumps4 = num_jumps

在这里 num_jumps 是正数 , 因此它们将满足 .

x1 = 0v1 = 2x2 = 5v2 = 3 ( x1 - x2 ) / ( v2 - v1 ) = num_jumps ( 0 - 5 ) / ( 3 - 2 ) = num_jumps ( -5 ) / 1 = num_jumps-5 = num_jumps

这里 num_jumps 为负数 , 因此它们将永远不会见面 .

一个 Python 函数来解决这个问题:

def will_they_meet ( x1, v1, x2, v2 ) : num_jumps = ( x1 - x2 ) / ( v2 - v1 ) return 'YES' if num_jumps >= 0 else 'NO'

注意:如果 v1 和 v2 相等 ( ZeroDivisionError ) , 或者传递给函数的参数不是数字 , 则此代码可能会引发错误 . 您可能需要添加 try … except 块 , 以使其更强大 .

如您所见 , 不需要生成所有可能的位置 , 也不需要任何类型的循环 .

相关文章
评论
没有更多评论了
取消

登录后才可以发布评论哦

12 我来说两句…
打开 ZAKER 参与讨论