简体   繁体   中英

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

EDIT: After doing what @AlexForGill answered, I am getting Index Out of Bounds error for function 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

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 . The result of f1 is the updated index, which is assigned to x . This value is then passed into f2 , which also returns the updated index which is again assigned to x .

value2 is then appended to the accumulator list which is returned at the end of the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM