代码之家  ›  专栏  ›  技术社区  ›  Noah Sprenger

将结果添加到列表并设置for循环

  •  2
  • Noah Sprenger  · 技术社区  · 7 年前

    对于学校作业,我编写了一个算法,使用Euler方法计算斜率。在它的一部分,我有一个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)
    

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

    2 回复  |  直到 7 年前
        1
  •  2
  •   blues    7 年前

    while 环这样地:

    t = 0
    while t < 10:
        t = t + 1
        # more code here
    
        2
  •  1
  •   Peppermint Paddy    7 年前

    这里有一个递归方法 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 调用或更简单一个函数,只要到达某个点就调用它自己 if slope.timestamp > until . 第一个电话是我的 initial_slope ( step_size until 只是常数)。

    线路 current_y = slope.slope + step_size * slope.slope 计算新的坡度值。然后,我用新的坡度值和更新时间创建一个坡度实例,并将其添加到列表中。

    斜率实例、斜率列表和常数通过函数的自调用传递到下一步 return find_slope(slopes, slope, step_size, until) . 返回不仅需要走下阶梯并收集新的坡度,还需要返回到起点,以便调用方可以接收到它。

    您可以使用

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

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