Welcome, guest | Sign In | My Account | Store | Cart

This algorithm converts a base c number into a base b number. Parameters c and b are arbitrary are not constrained by any bounds. The input n is a list and the output is a list.

Python, 7 lines
1
2
3
4
5
6
7
mod = lambda n,m: n%m
def baseExpansion(n,c,b):
    i = len(n)
    base10 = sum([pow(c,i-k-1)*n[k] for k in range(i)])
    j = int(ceil(log(base10 + 1,b)))
    baseExpanded = [mod(base10//pow(b,j-p),b) for p in range(1,j+1)]
    return baseExpanded

Example:

>>> baseExpansion([1,2,3],5,3)
[1,1,0,2]

4 comments

Steven D'Aprano 12 years, 5 months ago  # | flag

This recipe doesn't actually work.

>>> baseExpansion('123', 5, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in baseExpansion
TypeError: can't multiply sequence by non-int of type 'float'
Alexander James Wallar (author) 12 years, 5 months ago  # | flag

Oh sorry, the input is not a string. It is a list.

Try this:

>>> baseExpansion([1,2,3],5,3)
[1.0, 1.0, 0.0, 2.0]
Alexander James Wallar (author) 12 years, 5 months ago  # | flag

@Steven Try this for a string

from math import *
def baseExpansion(n,c,b):
    j = 0
    base10 = sum([pow(c,len(n)-k-1)*int(n[k]) for k in range(0,len(n))])
    while floor(base10/pow(b,j)) != 0: j = j+1
    return [floor(base10/pow(b,j-p)) % b for p in range(1,j+1)]
Alexander James Wallar (author) 12 years, 5 months ago  # | flag

@Steven:

I have redone the algorithm so you can input and output a string