Python while循环中的两个False
我希望有人能帮助我的python代码。在本例中,我在左、右站点上查看峰值 我想知道当Python while循环中的两个False,python,Python,我希望有人能帮助我的python代码。在本例中,我在左、右站点上查看峰值 我想知道当h[x+1]
h[x+1]
然后x=x-1
和summit=False
时。我正在尝试编写第二个循环,但此解决方案不起作用
下面是我的代码:
import math
import random
w = [random.random()/3, random.random()/3, random.random()/3]
h = [1.+math.sin(1+x/6.)*w[0]+math.sin(-.3+x/9.)*w[1]+math.sin(-.2+x/30.)*w[2] for x in range(100)]
h[0] = 0.0; h[99] = 0.0
print(h)
def climb(x, h):
# keep climbing until we've found a summit
summit = False
# edit here
while not summit:
summit = True
if h[x + 1] > h[x]:
x = x + 1
summit = False
else:
if h[x + 1] < h[x]:
x = x - 1
#summit = False
#summit = False
return x
def main(h):
# start at a random place
x0 = random.randint(1, 98)
x = climb(x0, h)
print("Venla started at %d and got to %d" % (x0, x))
return x0, x
main(h)
导入数学
随机输入
w=[random.random()/3,random.random()/3,random.random()/3]
h=[1.+math.sin(1+x/6.)*w[0]+math.sin(-.3+x/9.)*w[1]+math.sin(-.2+x/30.)*w[2]表示范围(100)内的x
h[0]=0.0;h[99]=0.0
打印(h)
def爬升(x,h):
#继续爬山,直到我们找到山顶
summit=False
#编辑这里
虽然不是首脑会议:
summit=True
如果h[x+1]>h[x]:
x=x+1
summit=False
其他:
如果h[x+1]
不自己计算索引可能会更容易,但让我们为您这样做吧。然后循环所有值,如果找到满足要求的值,则离开该函数
def climb(x, h):
for idx, value in enumerate(h):
if h[idx-1] < value and value > h[idx+1]:
return idx
def爬升(x,h):
对于idx,枚举中的值(h):
如果h[idx-1]h[idx+1]:
返回idx
没有边界检查,因此我们假设可以在数据中找到顶点。我可能错了,但是while循环中的else语句,我认为它的意思是
h[x-1]
?嘿,Jax-Teller,我短路了这个阶段,现在我有了而不是summit:summit=True#如果h[x+1]>h[x]:x=x+1#右边更高,走到那里summit=False#然后继续走:x=x-1#右边更高,去那里#summit=False#summit=False返回x
最重要的一点是了解enumerate
的工作原理。其他一切都应该不言自明。