首页 > 解决方案 > 迭代函数以找到起始值以在一定数量的步骤中完成序列

问题描述

我目前正在尝试在 python 中编写一个函数,该函数接受两个值goalcount并迭代地搜索函数应该以所给出的步数开始的值,count直到它找到一个等于或大于的数字goal

这就是我到目前为止所拥有的,这要归功于 Sprizgola。

def find_start_forward(goal, count):
    """
    Function that iteratively searches forward from an initial
    start value of 0, computes the sequence until the last value is greater than or equal
    to the goal, and returns the start value of the sequence
    :param goal: The last number in the sequence
    :param count: How many steps to reach the goal
    :pre-conditions: goal >= 0 and count >= 0
    :return:
    """
    if count == 0:
        goal = goal
        return goal
    else:
        number = 0
        count = 0
        while True:
            number = number + 1
            goal_end = number * 2 + 5
            if goal_end >= goal:
                return number
            count += 1

电流输出:

print(find_start_forward(100,1))
>> 48
print(find_start_forward(7,2))
>> 1

我希望最终输出看起来像这样:

find_start_forward(100,1) It would find 48 is the first to follow the rules: * 2 + 5 is >= 100
48

find_start_forward(7,2) Finds what 2 steps from the start is >= 7
0

标签: pythoniteration

解决方案


该函数正在返回None,因为它没有在循环结束之前进入 if 子句。我用 while 循环修改了 for 循环,并将计数添加到每次迭代中:

def find_start_forward(goal, count):
    """
    Function that iteratively searches forward from an initial
    start value of 0, computes the sequence until the last value is greater than or equal
    to the goal, and returns the start value of the sequence
    :param goal: The last number in the sequence
    :param count: How many steps to reach the goal
    :pre-conditions: goal >= 0 and count >= 0
    :return:
    """
    if count == 0:
        goal = goal
        return goal
    else:
        start_value = 0

        while True:
            sequence_sum = start_value
            for i in range(count):
                goal_end = sequence_sum * 2 + 5
                if goal_end >= goal:
                    return start_value
                sequence_sum = goal_end

            start_value += 1

这些是输出

print(find_start_forward(100,1))
>> 48
print(find_start_forward(7,2))
>> 0
print(find_start_forward(100,4))
>> 2

编辑2:

这里是!基本上我已经创建了一个嵌套循环:一个 while 循环保持递增起始值,而 for 循环搜索以小于 的值完成序列的数字count您发布的文本的最后一句话有助于理解问题的含义。


推荐阅读