将结果添加到列表并设置forloop

2024-06-28 11:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

对于学校作业,我编写了一个算法,使用欧拉方法计算斜率。在其中的一部分,我有一个for循环,它将重复一个等式模式,直到最终结果得到满足。我需要的是一种方法,将每个结果添加到一个列表中,然后绘制列表中的每个项目。如果可能的话,我还需要一些帮助来设置for循环。你知道吗

以下是我所拥有的,请记住我在编码方面非常缺乏经验(请记住)

stpsz = input ("Define "h" Value (step size)")
tfinal = input ("Define Final "T" Value (stopping place)")
xnow = input ("Define "X0" as a Starting Value")

t = 0
while t > tfinal
    t = t + 1
    slopenow = (xnow * (1-xnow))

#Save slopenow (as a number, not variable) to a list of slopes ( I don't understand how to make a list like this)
#Save xnow (as a number, not variable) to a list of xs)

    xnext = (slopenow * stpsz)+(xnow)
    xnext = x now

#repeat while-loop until tfinal is reached)

我非常感谢你们所能给予的一切帮助。你知道吗


Tags: to方法列表forinputvaluesaveas
2条回答

这里有一个this方程的递归方法,让您了解我在评论中的意思。你知道吗

class Slope:
    def __init__(self, timestamp, slope):
        self.timestamp = timestamp
        self.slope = slope


def find_slope(slopes, slope, step_size, until):
    if slope.timestamp > until:
        return slopes
    current_y = slope.slope + step_size * slope.slope
    slope = Slope(slope.timestamp + 1, current_y)
    slopes.append(slope)
    return find_slope(slopes, slope, step_size, until)

if __name__=="__main__":
    initial_slope = Slope(0, 1)
    for current in find_slope([], initial_slope, 1, 3):
        print("slope: {slope}, timestamp: {timestamp}".format(**current.__dict__))

但是有多种方法可以解决这个问题,例如使用while或for循环。我也不得不承认你可以写一个简短的版本,但我认为冗长有助于你更好地理解。你知道吗

编辑

你的眼睛应该集中在这个功能上。。。你知道吗

def find_slope(slopes, slope, step_size, until):
    if slope.timestamp > until:
        return slopes
    current_y = slope.slope + step_size * slope.slope
    slope = Slope(slope.timestamp + 1, current_y)
    slopes.append(slope)
    return find_slope(slopes, slope, step_size, until)

这是一个recursive调用或更简单的函数,只要到达某个点,它就会调用自身。第一个调用是myinitial_slopestep_sizeuntil只是常量)。你知道吗

current_y = slope.slope + step_size * slope.slope计算新的斜率值。然后用新的slope值和更新的时间创建一个slope实例,并将其添加到列表中。你知道吗

slope实例、slope列表和常量通过函数return find_slope(slopes, slope, step_size, until)的自调用传递到下一步。返回不仅需要走下阶梯,收集新的斜坡,而且还需要返回到起点,以便调用者能够接收到它。你知道吗

您可以使用

 slopes = find_slope([], initial_slope, 1, 3)

把斜坡的清单拿回来。我用一个空列表初始化了它,该列表将填充坡度,稍后将从此函数返回。你知道吗

听起来你要找的是一个while循环。像这样:

t = 0
while t < 10:
    t = t + 1
    # more code here

相关问题 更多 >