Blink
Blink

Reputation: 1504

Python loop not looping through xrange

One part of my program requires that I check to make sure two "things" don't overlap (occupy the same space, i.e., coordinates). For some reason it doesn't loop through the entire xranges. I am sure that it is a simple programming mistake, but I've reduced to program to a simple MWE and the problem persists!

import numpy as np

class foo(object):
    def __init__(self, yx):
        self.yx = yx

def overlap(fooFun):
    n = len(fooFun)
    for i in xrange(n):
        for j in xrange(n):
            if i != j: # Don't check itself
                print '----------------------'
                print 'i,j:', i, j
                print 'Comparing:', fooFun[i].yx, fooFun[j].yx
                if np.array_equal(fooFun[i].yx, fooFun[j].yx) == True:
                    print 'Overlap!'
                    return False
                else:
                    print 'No Overlap!'
                    return True

# Test functions/class
yx = np.array([[0, 0], [0, 1], [0, 0]])
n = len(yx)

fooGroup = []
for i in xrange(n):
    fooGroup.append(foo(yx[i]))

overlap(fooGroup)

Which results in:

----------------------
i,j: 0 1
Comparing: [0 0] [0 1]
No Overlap!

For some reason this does not loop through i = 0, 1, 2 and j = 0, 1, 2.

Upvotes: 0

Views: 156

Answers (1)

Winston Ewert
Winston Ewert

Reputation: 45039

A return statement causes the function to end right away. It skips everything. If you want to run through all the loops, you need to remove your return statements.

Upvotes: 1

Related Questions