[Tutor] Function for converting ints from base10 to base2?

Dick Moores rdm at rcblue.com
Thu Feb 22 03:08:34 CET 2007


At 05:17 PM 2/21/2007, Terry Carroll wrote:
>On Tue, 20 Feb 2007, Dick Moores wrote:
>
> > I was surprised to be unable to find a function in Python for
> > converting ints from base10 to base2. Is there one?
> >
> > I wrote one, but have I reinvented the wheel again? (Even if I have,
> > it was an interesting exercise for me.)
>
>I like the approach of mapping hex or octal digits posted by Alan and Bob,
>but, not thinking of that, this would be my straightforward approach:
>
>def computeBin(n):
>      """converts base10 integer n to base2 b as string"""
>      if n == 0: return '0'
>      sign = ['','-'][n<0]
>      num = abs(n)
>      seq = []
>      while (num != 0):
>          (num, bit) = divmod(num, 2)
>          seq.append(str(bit))
>      seq.append(sign)
>      return ''.join(reversed(seq))
>
>if __name__ == "__main__":
>     x = 1234567890
>     assert x == int(computeBin(x),2)
>     x = -1234567890
>     assert x == int(computeBin(x),2)

Thanks!

But there's syntax(?) there I've never seen before. "['','-'][n<0]". 
I see it works:

 >>> n = -6
 >>> ['','-'][n<0]
'-'
 >>> n = 98
 >>> ['','-'][n<0]
''

What's this called? I'd like to look it up.

Dick



More information about the Tutor mailing list