通过两个函数运行循环,将彼此输出作为输入

时间:2015-06-24 08:56:53

标签: python arrays algorithm function loops

我有两个功能,比如说

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...

有人可以提供方向吗?

编辑:在做了@AlexForGill回答之后,我得到函数f2的索引超出界限错误

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

1 个答案:

答案 0 :(得分:3)

以下是否适合您?

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循环在调用f1f2之间交替显示。 f1的结果是更新的索引,分配给x。然后将此值传递到f2,该值还会返回更新后的索引,该索引将再次分配给x

然后将

value2附加到累加器列表中,该列表在循环结束时返回。