[英]How to thread two functions where one output effect the others actions
[英]running loop through two functions taking each others output as input
我说有两个功能
def f1(arr,k):
#does something here with elements of array arr starting from index k and returns i..
#EDIT: we don't need value1 from f1,
i=k
while arr[i]==0:
i=i+1
return i
和另一个功能
def f2(arr,arr2,k):
# does something here with elements of array arr starting from index k (k is output from function f1)...
#EDIT: following is the code for f2:
pr=0
if arr[k]==1:
i=k
while (pr<10 and pr>-10) and (arr2[i+1]!=2):
pr=pr+(arr2[i+1]-arr2[i])
i=i+1
if arr[k]==2:
i=k
while (pr<10 and pr>-10) and (arr[i+1]!=1):
pr=pr+(arr2[i]-arr2[i+1])
i=i+1
return i+1, pr
此输出i + 1再次用于函数f1,我们这样做直到我们到达数组的末尾。
我似乎无法弄清楚如何做到这一点。
我定义了一个函数
def final(arr):
x=0 #starting index
#need to use above two functions to return value2 as a list for each iteration...
有人可以提供一些方向吗?
def final(arr,arr2):
x=0
plist=[]
while x < len(arr)-1:
x = f1(arr, x)
if x >= len(arr)-1: # guard clause for applying second function
break
x, value2 = f2(arr,arr2, x)
plist.append(value2)
return plist
以下是否适合您?
def final(arr):
x = 0
accumulator = []
while (x < len(arr)):
x, value1 = f1(arr, x)
if (x >= len(arr)): # guard clause for applying second function
break
x, value2 = f2(arr, x)
accumulator.append(value2)
return accumulator
while
循环在调用f1
和f2
之间交替。 f1
的结果是更新的索引,它被分配给x
。 然后将该值传递给f2
, f2
还返回更新的索引,该索引再次分配给x
。
然后将value2
附加到累加器列表,该列表在循环结束时返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.