[英]running loop through two functions taking each others output as input
I have two functions, say 我说有两个功能
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
and another function 和另一个功能
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
This output i+1 is again used for function f1, we do this till the we reach the end of array. 此输出i + 1再次用于函数f1,我们这样做直到我们到达数组的末尾。
I can't seem to get the logic on how to do this. 我似乎无法弄清楚如何做到这一点。
I define a function 我定义了一个函数
def final(arr):
x=0 #starting index
#need to use above two functions to return value2 as a list for each iteration...
Can someone provide some direction? 有人可以提供一些方向吗?
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
Would the following work for you? 以下是否适合您?
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
The while
loop alternates between calling f1
and f2
. while
循环在调用f1
和f2
之间交替。 The result of f1
is the updated index, which is assigned to x
. f1
的结果是更新的索引,它被分配给x
。 This value is then passed into f2
, which also returns the updated index which is again assigned to x
. 然后将该值传递给
f2
, f2
还返回更新的索引,该索引再次分配给x
。
value2
is then appended to the accumulator list which is returned at the end of the loop. 然后将
value2
附加到累加器列表,该列表在循环结束时返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.