exiting recursive loop - python

时间:2017-11-13 06:13:22

标签: python loops recursion exit

I am writing a small collision check function. If 'is_collision" function return 'True' the function 'extend_until' should stop executing all the recursive functions and return the start point of the corresponding loop. I am not quite sure how this should be executed.

I have a discretization resolution of 1.0 unit along the length and hence starting initial if condition in 'extend until' function.

def is_collision(query):
    print "Collision occurred"
    return True


def extend_until(start, goal):
    if goal-start <= 1.0:
        if is_collision(goal):
            # if YES all recursion should stop and return.
            return start
    else:
        midpoint = (start+goal)/2
        extend_until(start, midpoint)
        extend_until(midpoint, goal)

    return goal

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print new_configuration

1 个答案:

答案 0 :(得分:0)

Is this good enough?

def is_collision(start, goal):
    if goal-start <= 1.0:
        print('Collision occurred')
        return True
    return False


def extend_until(start, goal):
    print("Start is: "+str(start))
    if is_collision(start, goal):
        # if YES all recursion should stop and return.
        return goal-start
    else:
        #midpoint = (start+goal)/2
        #extend_until(start, midpoint)
        start = start + 1
        return extend_until(start, goal)

if __name__ == '__main__':
    p1 = 0
    p2 = 4
    new_configuration = extend_until(p1, p2)
    print('New Configuration is: '+ str(new_configuration))

Output:-

Start is: 0
Start is: 1
Start is: 2
Start is: 3
Collision occurred
New Configuration is: 1