I’m having trouble debugging this code excerpt. Never mind the fact that it doesn’t actually return what the author wants, I already explained that, my question is different.
def factors(n):
result = []
for x in xrange(2,n):
print "\t%i,foo" % x
if n % x == 0:
isPrime = True
print "\t\t%i,bar" % x
for factor in result:
print "\t\t%i %% %i = %i" % (x,factor,x % factor)
if x % factor == 0:
isPrime = False
print "\t\t\t%i,foobar" % x
subFactors = factors(x)
result.extend(subFactors)
if isPrime:
result.append(x)
print ""
return result
def main():
factor = dict()
for i in xrange(1,100):
factor[i] = factors(i)
factor[i].insert(0,1)
factor[i].append(i)
print "%i: %s" % (i,factor[i])
if __name__ == "__main__":
main()
That code is infinite looping! Specifically, repeatedly outputs the following:
2,foo
2,bar
3,foo
4 % 2 = 0
4,foobar
Note that on the second iteration it doesn’t print the “bar” print statement, and the value of x changes from the “bar” print statement to the “mod” print statement.
I’m unable to explain this behavior to the author. Can one of you kind people?
The issue is that you’re extending the
resultlist while you’re iterating over its contents. Here are the two critical lines, without the other distracting bits around them:This has undefined behavior, according to the python spec. I’m pretty sure it is the cause of the infinite loop.