gpt4 book ai didi

python - 为什么这段与查找公倍数相关的代码不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:58 24 4
gpt4 key购买 nike

作业:

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 < 1000给定代码中的行以扩展搜索限制。

我在 Pycharm 上执行了给定的代码。我发现没有执行。

x1 = 0
v1 = 3
mul1 = 0 # Multiple of Kangaroo 1
a = [] # Multiples of Kangaroo 1 List
x2 = 4
v2 = 2
mul2 = 0 # Multiple of Kangaroo 2
b = [] # Multiples of Kangaroo 2 List
m = 0
while 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

如果我输入

0
3
4
2

我需要得到

NO

如果我输入

0
2
5
3

最佳答案

你可以用更简单的方法解决这个问题。

假设袋鼠以相同的速度跳跃(两者每分钟的跳跃次数相同,只是每只袋鼠每次跳跃的距离不同),你有以下(用数学术语):

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

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

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

现在有了值(value)

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

这里 num_jumps 是正数,所以他们会相遇。

x1 = 0
v1 = 2
x2 = 5
v2 = 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'

注意:如果 v1v2 相等(ZeroDivisionError)或者如果传递给函数的参数不相等,此代码可能会引发错误数字。您可能需要添加 try...except block 以使其更健壮。

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

关于python - 为什么这段与查找公倍数相关的代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com