Skip to content
Browse files

maths: Continued: Add digits property and properly cope with generators.

Now to fix the maths.
  • Loading branch information...
1 parent baf823f commit cfbc1453ade9efb34ccc8852726e86ae1bbe497a @MostAwesomeDude committed
Showing with 25 additions and 7 deletions.
  1. +25 −7 maths.py
View
32 maths.py
@@ -22,18 +22,17 @@ class Continued(object):
@classmethod
def from_int(cls, i):
instance = cls()
- instance.digits = [i]
+ instance.digitlist = [i]
return instance
@classmethod
def from_rational(cls, numerator, denominator):
instance = cls()
- instance.digits = []
while numerator != 1:
digit, numerator = divmod(numerator, denominator)
- instance.digits.append(digit)
+ instance.digitlist.append(digit)
numerator, denominator = denominator, numerator
- instance.digits.append(denominator)
+ instance.digitlist.append(denominator)
instance.normalize()
return instance
@@ -53,7 +52,7 @@ def generator():
yield i
i += 2
mod = 0
- instance.digits = generator
+ instance.make_digits = generator()
return instance
@classmethod
@@ -76,14 +75,21 @@ def generator(i):
iterator = itertools.cycle(repeating)
while True:
yield next(iterator)
- instance.digits = functools.partial(generator, i)
+ instance.make_digits = generator(i)
return instance
+ def __init__(self):
+ self.digitlist = []
+
def __repr__(self):
return str(self)
def __str__(self):
- return "Continued(%s)" % self.digits
+ if self.finite:
+ l = self.digitlist
+ else:
+ l = list(itertools.islice(self.digits, 10)) + ["..."]
+ return "Continued(%s)" % l
def __add__(self, other):
return self.combine(other, (0, 1, 1, 0, 1, 0, 0, 0))
@@ -100,6 +106,18 @@ def __div__(self, other):
def __truediv__(self, other):
return self.__div__(other)
+ @property
+ def digits(self):
+ """
+ Retrieve the digits of this continued fraction lazily.
+ """
+
+ if self.finite:
+ return self.digitlsit
+ else:
+ self.make_digits, retval = itertools.tee(self.make_digits)
+ return retval
+
def combine(self, other, initial):
if isinstance(other, int):
other = Continued.from_int(other)

0 comments on commit cfbc145

Please sign in to comment.
Something went wrong with that request. Please try again.