你能告诉我为什么列表变量在“while”循环后消失了吗?
@staticmethod def division(f, s): result = [] tr = [] if len(s) > len(f): return [Polynomial(0), Polynomial(f)] while len(f) >= len(s): r = [] k = 0 mf = 2*f[len(f)-1] ms = 2*s[len(s)-1] m = [] if mf < 0: mf *= -1 if ms < 0: ms *= -1 if mod(f[len(f)-1], mf) < mod(s[len(s)-1], ms): return [Polynomial(0), Polynomial(f)] while mod(f[len(f)-1], mf) >= k: k += mod(s[len(s)-1], ms) k -= mod(s[len(s)-1], ms) r.append([k/mod(s[len(s)-1], ms), len(f)-len(s)]) if f[len(f)-1] > 0 and s[len(s)-1] < 0 or f[len(f)-1] < 0 and s[len(s)-1] > 0: r[len(r)-1][0] *= -1 for i in xrange(r[len(r)-1][1]+1): m.append(0) m[len(m)-1] = r[len(r)-1][0] result.append(r[len(r)-1]) subtrahend = Polynomial.multiplication(Polynomial(m).Coefficients, Polynomial(s).Coefficients).Coefficients f = Polynomial.subtraction(f, subtrahend).Coefficients print result print result o = [] for i in xrange(result[0][1]+1): o.append(0) for i in xrange(len(result)): o[i] = result[i][0] o.reverse() if len(f) == 0: f = [0] return [Polynomial(o), Polynomial(f)]
f = Polynomial.subtraction(f, subtrahend).Coefficients
print result
print result
第一次打印显示正确的结果,但第二次打印(循环结束后)没有显示任何内容。如果我试着像这样重新定义它:
f = Polynomial.subtraction(f, subtrahend).Coefficients
print result
result = 'asdf'
print result
什么也没发生。结果变量仍为无。
答案 0 :(得分:3)
您的函数提前返回:
return [Polynomial(0), Polynomial(f)]
如果执行while
语句,则永远不会达到return
循环之后的代码,如果mod(f[len(f)-1], mf) < mod(s[len(s)-1], ms)
永远是True
,则会发生这种情况。