如何使用函数本身返回的值重复函数?
How to repeat a function with the values returned by the function itself?
我有这个函数,其中 returns 两个值,我想对这些返回值重复相同的操作。
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
newCurrValX, newCurrValY = fPoint
print(newCurrValX, newCurrValY)
以上函数 returns 值如下:
250.0 60.0
我想在 currCalcX 和 currCalcY 上应用这些值并重复函数 getFirstPoint()
直到返回 None
。
使用循环:
# dummy implementation - returns None if a or b is 0, ignores x and y
def getFirstPoint(x,y,a,b):
if a==0 or b==0:
return None
return a-1,b-1
x, y, currCalcX, currCalcY = 0,0,4,4 # add sensible values here
while True:
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
if fPoint is None:
print("Done")
break
currCalcX, currCalcY = fPoint
print(currCalcX, currCalcY)
输出:
3 3
2 2
1 1
0 0
Done
这里不需要递归 - 它不必要地堆积在函数堆栈帧上。如果需要太多递归(并且根本不需要),您可能会达到递归限制 - 请参阅 What is the maximum recursion depth in Python, and how to increase it? 了解递归限制说明。
我有这个函数,其中 returns 两个值,我想对这些返回值重复相同的操作。
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
newCurrValX, newCurrValY = fPoint
print(newCurrValX, newCurrValY)
以上函数 returns 值如下:
250.0 60.0
我想在 currCalcX 和 currCalcY 上应用这些值并重复函数 getFirstPoint()
直到返回 None
。
使用循环:
# dummy implementation - returns None if a or b is 0, ignores x and y
def getFirstPoint(x,y,a,b):
if a==0 or b==0:
return None
return a-1,b-1
x, y, currCalcX, currCalcY = 0,0,4,4 # add sensible values here
while True:
fPoint = getFirstPoint (x, y, currCalcX, currCalcY)
if fPoint is None:
print("Done")
break
currCalcX, currCalcY = fPoint
print(currCalcX, currCalcY)
输出:
3 3
2 2
1 1
0 0
Done
这里不需要递归 - 它不必要地堆积在函数堆栈帧上。如果需要太多递归(并且根本不需要),您可能会达到递归限制 - 请参阅 What is the maximum recursion depth in Python, and how to increase it? 了解递归限制说明。