gpt4 book ai didi

python - 停止内部迭代并找到 2 个元组的范围

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

这是我的代码,我不知道如何解决,我阅读了一些有关的主题,并尝试使用中断,但不幸的是没有成功。问题是,p2到达end后,循环结束,但是第一个循环只读取了1个元素。

p1,p2 就像 2 辆汽车,它们从点 1,1 开始并按照自己的路线行驶。

如果数字是正数,我们到 y。如果数字是负数,我们将绝对值加到 x。

p1 = ['5', '-2', '-2', '2', '-4']
p2 = ['-3', '2', '-5', '5']
lenP1 = len(p1)-1
lenP2 = len(p2)-1
x1 = x2 = y1 = y2 = 1
p1Pos = (x1, y1) #Initial start point
p2Pos = (x2, y2) #Initial start point
for ir1,r1 in enumerate(p1): #Running on first list p1
if int(r1) > 0: #If number is possitve
y1 = y1+int(r1)
p1Pos = x1,y1

else:
x1 = x1+abs(int(r1))
p1Pos = x1,y1

for ir2,r2 in enumerate(p2): #Running on first list p2
if int(r2) > 0:
y2 = y2+int(r2)
p2Pos = x2,y2

elif int(r2) < 0:
x2 = x2+abs(int(r2))
p2Pos = x2,y2
if ir2 ==lenP2: #Checking if we read all integers,if so break.
break
else:
continue
break

结果应该是

p1Pos = (9,8)
p2Pos = (9,8)

所有点都从同一点 (1,1) 开始并在同一点结束。

总是一个以正数开头,另一个以负数开头。

我想找到那些 p1,p2 的路由范围。例如 example

我需要将 p1 和 p2(铅笔线)之间的所有范围保存为元组你建议我如何处理这个_

最佳答案

这应该满足您的要求:

p1 = ['5', '-2', '-2', '2', '-4']
p2 = ['-3', '2', '-5', '5']

p1Pos, p2Pos = ([1, 1], [1, 1])

def movement(p, steps):
steps = [int(i) for i in steps]
for step in steps:
if step > 0:
p[1] += step
else:
p[0] -= step
return tuple(p)


p1Pos = movement(p1Pos, p1)
p2Pos = movement(p2Pos, p2)

p1Pos
#(9, 8)
p2Pos
#(9, 8)

请注意,与元组不同,起始位置以列表形式启动,以使其可变。

关于python - 停止内部迭代并找到 2 个元组的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53335944/

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