Comp 150, Dordal, Feb 17, 2006
Goals:
1 0 1 0 1 1 32 16 8 4 2 1To find out the number this represents, you multiply each power of 2 by the corresponding digit and add them all up:
1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 1*1 = 32 + 8 + 2 + 1 = 43much like 497 = 4*102+9*10 + 7.
If s is the string above, the indexing is as follows:
i: 0 1 2 3 4 5 s[i]: 1 0 1 0 1 1Unfortunately strings are indexed starting from the left end, and numbers are represented with the 2i column at position i starting from the right end. So one quick fix is to reverse the string (first converting it to a list because you can't directly reverse strings):
t = list(s) t.reverse() # unfortunately these two steps can't be combinedReversing the list t is the same as still thinking of it in the original order but now indexed right-to-left.
i: 5 4 3 2 1 0 t[i]: 1 0 1 0 1 1Now we just take the sum of (ith_digit)*(2i) using a for or while loop:
sum = 0 for i in range(0,len(t)): sum = sum + (ith_digit)*(2**i)There's one last catch: t[i] is a character and not a digit. But this works:
if t[i]=='0': digit = 0 # compact form of if/else elif t[i]=='1': digit=1 else: print "bad digit at column", i
while N > 0: digit = N % 2 N = N/2 print digitReplace printing the digit by putting the digit onto a list, and then reversing the list when you're done, and you have numtostr
That is, lab4 is initially imported with "import lab4", and reloaded with "reload(lab4)". The "from lab4 import *" is needed after each load or reload; its effect is to tell python that you want to refer to function foo in lab4.py as just foo(), and not lab4.foo().