Since we can't run it, we can only suggest adding print statements in strategic places to inspect variable values while it runs to determine what is happening that you were not expecting.