mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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:
parent
945803f65d
commit
e887c14f12
|
@ -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:
|
||||
|
|
Loading…
Reference in New Issue
Block a user