Possible improvement to slice opperations.

Bengt Richter bokr at oz.net
Tue Sep 6 02:58:58 CEST 2005


On 05 Sep 2005 12:58:00 -0700, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

>Steve Holden <steve at holdenweb.com> writes:
>> Given that Python has a 1's-complement operator already I don;t see
>> why you can't just leave Python alone and use it,
>
>What's the meaning of the 1's complement operator (for example, what
>is ~1), when ints and longs are the same?

assert ~x == -1-x  # or -1^x

The only problem is seeing the result printed, since people insist
that hex(a) will be '-'[:a<0]+hex(abs(a))

which brings up base-complement representation for signed numbers,
where the first digit is always 0 or base-1 to indicate positive and negative:
(BTW, I found a bug when I dug this up from my disk, so a previous post with this
might have that bug (bad leading digit check wasn't sign-sensitive))

 >>> def basecompl(x, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'):
 ...     if not (2 <= B <= len(digits)): raise ValueError('bad base = %r'%B)
 ...     if not x: return digits[0]
 ...     s = []
 ...     while x and x != -1:
 ...         x, r = divmod(x, B)
 ...         s.append(digits[r])
 ...     if not s or s[-1] != (digits[0], digits[B-1])[x<0]:
 ...         s.append(digits[x<0 and B-1 or 0])
 ...     return ''.join(s[::-1])
 ...
 >>> def bcdecode(s, B=10, digits='0123456789abcdefghijklmnopqrstuvwxyz'):
 ...     if s == digits[0]: return 0
 ...     acc = s[0].lower() == digits[B-1] and -B**len(s) or 0
 ...     for i, c in enumerate(s[::-1]):
 ...         acc += digits.index(c)*B**i
 ...     return acc
 ...
 >>> bc = basecompl # easier to type ;-)

 >>> bc(~3L, 2)
 '100'
 >>> bc(-1-3L, 2)
 '100'
 >>> bc(-1^3L, 2)
 '100'
 >>> bc(~3L, 8)
 '74'
 >>> bc(-1-3L, 8)
 '74'
 >>> bc(-1^3L, 8)
 '74'
 >>> bc(~3L)
 '96'
 >>> bc(-1-3L)
 '96'
 >>> bc(-1^3L)
 '96'
 >>> bc(bcdecode(bc(~3L)))
 '96'
 >>> bc(bcdecode(bc(~3L, 2),2),2)
 '100'
 >>> bc(~3L, 16)
 'fc'
 >>> bc(-1-3L, 16)
 'fc'
 >>> bc(-1^3L, 16)
 'fc'
 >>> bc(3L)
 '03'

Regards,
Bengt Richter



More information about the Python-list mailing list