我已经实现了贪心算法来解决埃及分数,但是我得到了一些意想不到的结果。这是我的代码
from math import ceil
from fractions import Fraction
def go(frac):
ret = []
while frac > 0:
if frac.numerator == 1:
ret.append(frac)
break
x = Fraction(1, ceil(frac.denominator / frac.numerator))
frac -= x
ret.append(x)
return ret
input1 = int(raw_input('numerator: '))
input2 = int(raw_input('denominator: '))
print go(Fraction(input1, input2))
我经常收到错误“TypeError:两个参数都应该是 Rational 实例”
我一直在记录,它在 while 循环的第一次迭代时崩溃。
编辑:详细的错误是:
File "egypt.py", line 19, in <module>
print go(Fraction(input1, input2))
File "egypt.py", line 10, in go
x = Fraction(1,ceil(frac.denominator / frac.numerator))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/fractions.py", line 158, in __new__
raise TypeError("both arguments should be "
TypeError: both arguments should be Rational instances
为什么是这样?谢谢你。