问题陈述很不清楚,你并没有真正提出一个明确的问题......当然,我们知道你会得到一个无限循环,原因很简单,在大多数情况下你没有真正的“破坏”陈述。
一般来说,我不明白算法的目标:你从 (1,1) 开始,你想通过只在 x 上添加 y 和/或在 y 上添加 x 来达到 (x,y) ?
如果是这样,我真的看不出它如何正常运行......
假设您有x=10 和y=63
然后你可以去(1+63, 1) = (64,1)或(1,63+10) = (1,73)。无论哪种情况,您都已经超越了初始目标 (10,63)。这就是为什么你从不输入两个 if 语句的原因。
你能澄清一下吗?
编辑
考虑到你的精确度,对我来说,第一件事是能够说明在达到的位置 (x,y) 是否仍有可能改进以实现目标 (xt,yt)。这个功能(非常明确)是一个建议:
def improvement_possible(xt, yt, x, y):
x_possible = True
y_possible = True
if x >= xt and y >= 0:
x_possible = False
if x <= xt and y <= 0:
x_possible = False
if y >= yt and x >= 0:
y_possible = False
if y <= yt and x <= 0:
y_possible = False
return x_possible, y_possible
然后我们可以递归地尝试所有路径,同时存储(1)路径序列和(2)到达的位置:
def find_path(xt, yt, x, y, path_sequences: list, reached: list, level=0):
print((level)*"-" + f"We are at ({x},{y})")
new_x = x + y
new_y = y + x
# Check if improvement is possible
dirs_to_test = ["x", "y"]
x_possible, y_possible = improvement_possible(xt, yt, x, y)
if not (x_possible or y_possible):
print(level*"-" + "======== No improvement possible at this point, we must stop ========")
return
if not x_possible:
print(level*"-" + "=> No improvement possible on X at this point")
dirs_to_test = ["y"]
if not y_possible:
dirs_to_test = ["x"]
print(level*"-" + "=> No improvement possible on Y at this point")
for new_dir in dirs_to_test:
print(level*"-" + f"Increasing on direction {new_dir}...")
path_sequences.append(path_sequences[-1] + [new_dir])
new_pos = (new_x, y) if new_dir =="x" else (x, new_y)
reached.append(new_pos)
find_path(xt, yt, new_pos[0], new_pos[1], path_sequences, reached, level+1)
对于一个目标为(10,12)、起点为(4,4)的非常简单的问题,它为reached列表提供了以下内容:
[(8, 4), (12, 4), (12, 16), (8, 12), (20, 12), (4, 8), (12, 8), (12, 20), ( 4, 12), (16, 12)]
因此,您可以手动检查 10 条可能的路径是否正确。顺便说一句,您可以评论它的对称性,考虑到起点,这是有道理的。
当谈到哪个更好时,这取决于您的标准。例如,(8, 12) 是否优于 (12, 8)