【问题标题】:Solve TypeError in Python/IPython解决 Python/IPython 中的 TypeError
【发布时间】:2017-04-19 03:41:59
【问题描述】:

我在使用以下功能时遇到问题

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: >>: 'float' 和 'int' 的操作数类型不受支持

注意事项: 这个 python 库仅在 2.7 中受支持,我使用 2to3 来使用它。库的其他部分按需要工作,所以我通常相信 2to3 工作。

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

【问题讨论】:

  • 我用 10101 测试了代码,它运行良好。有问题的输入是什么?
  • @MHornbacher bits=31
  • 我的结果:Windows 10 1607 python 2.7.3 和 Python 3.6.0 你的代码在 3 秒内没有返回错误

标签: python python-3.x python-2to3


【解决方案1】:

问题源于您试图在两种不同的数据类型(floatint)之间执行Binary Right Shift (>>)。据我所知,使用 (int(((t & -t) // (next & -next)) >> 1) - 1) 将浮点数转换为 int 应该可以工作。

【讨论】:

  • 不过,>> 的任何输入都不应该是可能为浮点数。你不能从& 中得到浮点数,// 不会给出浮点数,除非你给它浮点数。
  • 我认为他给了它浮动。一个通过 31 的测试用例与原始代码一起工作
  • If you gave this function a float, it would error out on |, not >>. 浮点数无法到达此函数中的任何 >> 运算符。
  • 那么我猜这个错误是在别处抛出的。由于 DMS 什么也没说,我认为它已修复。
猜你喜欢
  • 2014-02-20
  • 2011-09-10
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2023-03-09
  • 2023-03-18
  • 2021-07-10
相关资源
最近更新 更多