简体   繁体   English

贪心算法奇怪的行为

[英]Greedy algorithm odd behavior

I've implemented the Greedy algorithm to solve Egyptian fractions, however I'm getting some unexpected results. 我已经实现了Greedy算法来解决埃及分数,但是我得到了一些意想不到的结果。 Here's my code 这是我的代码

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))

I constantly am getting the error "TypeError: both arguments should be Rational instances" 我经常收到错误“TypeError:两个参数都应该是Rational实例”

I've been logging and it crashes upon the first iteration of the while loop. 我一直在记录,它在while循环的第一次迭代时崩溃了。

EDIT: the error in detail is: 编辑:错误的细节是:

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

Why is this? 为什么是这样? Thank you. 谢谢。

You have 2 problems in your code. 您的代码中有2个问题。

  1. you're dividing int with int which always returns an int ; 你将intint总是返回int ; in your case, you're dividing a / b where a < b so it'll always be rounded down to 0. 在你的情况下,你将a / b除以a / b a < b所以它总是向下舍入为0。
  2. Then, you ceil() that, which returns a float (0.0) which is something Fraction doesn't like;it wants int s. 然后,你ceil() ,它返回一个float (0.0),这是Fraction不喜欢的东西;它想要int s。

So try this instead: 所以试试这个:

Fraction(1, int(ceil(float(frac.denominator) / frac.numerator)))

The rest of the code looks good. 其余代码看起来不错。

Try changing this: 尝试改变这个:

x = Fraction(1, ceil(frac.denominator / frac.numerator))

to this: 对此:

x = Fraction(1,int(ceil(frac.denominator / float(frac.numerator))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM