[Tutor] Sorting numbers in lexicographic order [recreational programming]
Christian Ebert
blacktrash@gmx.net
Tue, 5 Mar 2002 09:27:50 +0100
Danny Yoo at 21:12 on Saturday, March 2, 2002:
> Here's the solution I cooked up:
Really useful for me (so it would be wrong on useless python
;-)
> >>> def toBinary(n):
> .... if n == 0: return '0'
> .... digits = []
> .... while n != 0:
> .... digits.append(str(n % 2))
> .... n = n >> 1
> .... digits.reverse()
> .... return string.join(digits, '')
I don't know anything about binary or hexadecimal numbers
(yet), but by playing with ">>" in the interpreter I found
something without ">>" that _seems_ to return the same
results:
def numberToBinary(n):
if n == 0: return '0'
digits = []
while n != 0:
n, b = divmod(n, 2)
digits.append(str(b))
digits.reverse()
return string.join(digits, '')
Am I right or was I just lucky in feeding it the right
numbers?
Christian
--
Hyperion in Frankfurt
www.tko.ch/blacktrash
www.schauspielfrankfurt.de