Fix continued_fraction.py to work for negative numbers (#8985)

* Add doctests to continued_fraction.py for 0 and neg nums

* Fix continued_fraction.py to work for negative nums

Fix continued_fraction.py to work for negative nums by replacing int() call with floor()

* Move comment in doctest
This commit is contained in:
Tianyi Zheng 2023-08-18 13:53:17 -07:00 committed by GitHub
parent 945803f65d
commit e887c14f12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -6,6 +6,7 @@ https://en.wikipedia.org/wiki/Continued_fraction
from fractions import Fraction
from math import floor
def continued_fraction(num: Fraction) -> list[int]:
@ -29,11 +30,17 @@ def continued_fraction(num: Fraction) -> list[int]:
[0, 2, 4]
>>> continued_fraction(Fraction("415/93"))
[4, 2, 6, 7]
>>> continued_fraction(Fraction(0))
[0]
>>> continued_fraction(Fraction(0.75))
[0, 1, 3]
>>> continued_fraction(Fraction("-2.25")) # -2.25 = -3 + 0.75
[-3, 1, 3]
"""
numerator, denominator = num.as_integer_ratio()
continued_fraction_list: list[int] = []
while True:
integer_part = int(numerator / denominator)
integer_part = floor(numerator / denominator)
continued_fraction_list.append(integer_part)
numerator -= integer_part * denominator
if numerator == 0: