Liam Clarke wrote:
Just looking at this - i = 456
s = ''
while i:
s = str(i % 2) + s
i/=2
This works, far simpler than mine, which is always infuriating, but my question is, how exactly?
if I have the number 15, when it divides by 2, it will become 7. Yet no error is introduced into the binary. Argggg. Driving me nuts trying to figure out how. I thought maybe a larger odd number would do it, but no.
Can anyone shed some more light on this?
Let's step over it : i = 15 # = 1111b s = str(i % 2) + s # 15 % 2 = 1 so now s = "1" i = i / 2 # i = 7 where's the 1 missing? s has got it
s = 7 % 2 = 1 so now s = "11" i = 7/2 = 3 ... and so on...
Remember when you do the base-conversion by hand:
(ASCII-ese graphics, use fixed font)
15 | 2
----
1 7 | 2
----
1 3 and so on...
You're basically doing the same thing
Perhaps that code could be improved by not using strings: ### Warning, untested code! ### i = 15 power = 0 f = 0
while i > 0: f = f+ (i%2)**power i /= 2 power += 1
I don't know if that's faster, but I see it as a more "mathematic" way to do it.
Bye Ismael _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
