2017-04-19 94 views
-1

我有以下功能解决类型错误在Python/IPython的

def get_lexographically_next_bit_sequence(self, bits): 
    """ 
    Bit hack from here: 
    http://www-graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation 

    Generator even does this in poker order rank 
    so no need to sort when done! Perfect. 
    """ 
    t = (bits | (bits - 1)) + 1 
    next = t | ((((t & -t) // (bits & -bits)) >> 1) - 1) 
    yield next 
    while True: 
     t = (next | (next - 1)) + 1 
     next = t | ((((t & -t) // (next & -next)) >> 1) - 1) 
     yield next 

该函数返回的错误麻烦:

TypeError: unsupported operand type(s) for >>: 'float' and 'int'

注: 这个Python库仅在2.7和我支持使用2to3才能使用它。图书馆的其他部分按照需要工作,所以我一般有信心2to3工作。

我想在IPython 3.5中运行这个,我听说这样的一些错误可能发生在IPython中,所以我想知道它是否与此有关。

+0

我用10101测试了代码,它工作正常。问题的输入是什么? –

+0

@MHornbacher位= 31 –

+0

我的结果:Windows 10 1607 python 2.7.3和Python 3.6.0你的代码在3秒内没有返回错误 –

回答

0

此问题源于您尝试在两种不同数据类型(floatint)之间执行Binary Right Shift (>>)的事实。将float浮动到(int(((t & -t) // (next & -next)) >> 1) - 1)应该尽我所能。

+0

对于任何'>>'的输入都不应该* * *尽管如此,还是漂浮着。你不能从'&'中获得一个浮点数,并且'//'不会给浮点数,除非你给它浮点数。 – user2357112

+0

我认为他给了它漂浮。一个测试用例,有31个通过,与原代码 –

+0

一起工作[如果你给这个函数一个浮点数,它会在'|',而不是'>>'中出错。](http://ideone.com/8mId00)这个函数可以让float到达任何'>>'运算符。 – user2357112

相关问题