未绑定的整数类

时间:2014-04-10 07:40:15

标签: python python-2.7

我实现了一个UnboundInteger类,它表现为常规整数。 我们的想法是能够在任意大的范围内进行操作 对两边都没有任何限制的整数 支持的大小。

这是我的代码

class UnboundInteger(object):

def __init__(self, integer):
    self.integer = str(integer)


def __add__(self, other):
    carry = '0'
    temp = '0'
    result = ''

    if (len(self.integer) > len(other.integer)):
        num_of_zeros = len(self.integer) - len(other.integer)
        other.integer = '0' * num_of_zeros + other.integer

    elif (len(self.integer < other.integer)):
        num_of_zeros = len(other.integer) - len(self.integer)
        self.integer = '0' * num_of_zeros + self.integer

    for i in range(1, len(self.integer)+1):
        temp = str(int(self.integer[-i]) + int(other.integer[-i]) + int(carry))
        temp = '0' + temp
        temp = temp[-1]
        carry = temp[-2]
        result = temp + result

    return UnboundInteger(result)



@classmethod
def from_int(cls, integer):
    '''\
    Take in a integer and build the unbound integer object.
    '''
    ub_integer = cls(integer)
    return ub_integer

不幸的是我无法调试错误 请帮帮我

这是错误

    In [40]: reload(test)
Out[40]: <module 'test' from 'test.py'>

In [41]: a = test.UnboundInteger(1000000000000)

In [42]: b = test.UnboundInteger(20000000000)

In [43]: a + b
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-43-f96fb8f649b6> in <module>()
----> 1 a + b

/home/neel101/test.py in __add__(self, other)
     17             temp = '0' + temp
     18             temp = temp[-1]
---> 19             carry = temp[-2]
     20             result = temp + result
     21 

IndexError: string index out of range

或者解决此问题的更好方法。请让我知道!

1 个答案:

答案 0 :(得分:1)

这是因为你正在覆盖临时变量。

temp = '0' + temp
temp = temp[-1]
carry = temp[-2]

应该是这样的:

temp = '0' + temp
carry = temp[-2]
temp = temp[-1]