python - 迭代函数以找到起始值以在一定数量的步骤中完成序列
问题描述
我目前正在尝试在 python 中编写一个函数,该函数接受两个值goal
,count
并迭代地搜索函数应该以所给出的步数开始的值,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
解决方案
该函数正在返回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
。您发布的文本的最后一句话有助于理解问题的含义。
推荐阅读
- amazon-web-services - AWS CodeDeploy:卡在安装步骤
- python - 哪个小部件最适合创建动态选项卡?
- angular - 如何在 Angular 7 中设置超时 KeyUp
- http - 在 Indy POST 之后访问 JSON 数据
- azure - 如何检查 Azure SQL 数据库中特定用户的所有访问权限?
- excel - 循环检查总和,具体取决于具有未知条目的几列
- android - 一个布局中的 TextView 内容进入另一个布局
- autodesk-forge - Forge Viewer 中模型的默认材质
- javascript - 'firebase' 不是内部或外部命令、可运行程序或批处理文件
- android-studio - Android Studio 显示主目录而不是项目