以下是我如何以以下形式分解数字n2 = m * n1 + r
:
>>> def decompose(number):
... # returns a generator of tuples (m, n1, r)
... for m in range(1, number+1):
... yield m, number // m, number % m
...
>>> for m, n1, r in decompose(5):
... print "5 = %s * %s + %s" % (m, n1, r)
...
5 = 1 * 5 + 0
5 = 2 * 2 + 1
5 = 3 * 1 + 2
5 = 4 * 1 + 1
5 = 5 * 1 + 0
或使用固定m
,这与常规相同divmod
:
>>> def decompose(number):
... return number // m, number % m
...
>>> m = 2
>>> n1, r = decompose(5)
>>> print "5 = %s * %s + %s" % (m, n1, r)
5 = 2 * 2 + 1
>>> m = 4
>>> n1, r = decompose(5)
>>> print "5 = %s * %s + %s" % (m, n1, r)
5 = 4 * 1 + 1
或更简单地使用lambda
:
>>> decompose = lambda number: divmod(number, m)
>>>
>>> m = 2
>>> decompose(5)
(2, 1)
>>> m = 4
>>> decompose(5)
(1, 1)
现在,举一个完整的例子:
>>> decompose = lambda number: divmod(number, m)
>>>
>>> class Phi_m(list):
... def __init__(self, items):
... list.__init__(self)
... # you need to know at least m numbers.
... assert len(items) >= m, 'Not enough data'
... list.extend(self, items)
... # this is a sparse list
... # http://stackoverflow.com/questions/1857780/sparse-assignment-list-in-python
... def __setitem__(self, index, value):
... missing = index - len(self) + 1
... if missing > 0:
... self.extend([None] * missing)
... list.__setitem__(self, index, value)
... def __getitem__(self, index):
... try:
... value = list.__getitem__(self, index)
... if value is not None:
... # the item is in the list, yeah!
... return value
... # the item is in the list because it was resized
... # but it is None, so go on and calculate it.
... except IndexError:
... # the item is not in the list, calculate it.
... pass
... print 'calculating Fm[%s]' % index
... A, B = decompose(index)
... value1 = self.__getitem__(A)
... value2 = self.__getitem__(A + 1)
... print 'Fm[A=%s] = %s, Fm[A+1=%s] = %s' % (A, value1, A+1, value2)
... print 'back to calculating Fm[%s]' % index
... # m * x[n1] + r * (x[n1 + 1] - x[n1]) = (m - r) * x[n1] + r * x[n1 + 1]
... # A = n1 ; B = r ; value1 = x[n1] ; value2 = x[n+1]
... value = (m - B) * value1 + B * value2
... self.__setitem__(index, value)
... return value
...
>>> x = Phi_m([0, 1, 1])
>>>
>>> x[5]
calculating Fm[5]
calculating Fm[3]
Fm[A=1] = 1, Fm[A+1=2] = 1
back to calculating Fm[3]
Fm[A=2] = 1, Fm[A+1=3] = 2
back to calculating Fm[5]
3
>>>
>>>