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

Takes in any non-negative integer and converts to the desired base-n for 1<=n<=10.

Python, 44 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def base(num,base):
    """
    Input: num can be any base 10 integer, base can be any positive integer<=10.

    Output: num is returned as a string in the specified base integer.
    """
    from math import log
    
    # Create a list of all possible digits
    digits=[x for x in range(base)]
    
    # Solve for highest base power
    highestExponent=int(log(num,base))

    # Create base expansion list from greatest to least
    baseExpansionList=[base**x for x in range(highestExponent+1)]
    baseExpansionList.reverse()

    # Get digits in base
    newDigits=[]
    for x in baseExpansionList:
        tmp=getDigits(num,x,digits)
        num=num-(tmp*x)
        newDigits.append(tmp)

    # Convert newDigits to str format
    numStr=""
    for x in newDigits:
        numStr+=str(x)
    return numStr
            
def getDigits(num,baseNum,digitsList):
    """
    Input: num, baseNum, and digitsList must all come from base(num,base) as is
    currently specified.

    Output: returns each digit in the output number of base(num,base).
    """
    tmpList=[]
    for x in digitsList:
        if x*(baseNum)>num:
            tmpList.append(x)
    
    return max((set(digitsList)-set(tmpList)))  

This program is useful because:

  1. It provides an algorithm that is very intuitive and straight forward, thus making it easier for the user to employ the program as they desire (provided they understand why the algorithm works).

  2. It's reliable in that this program doesn't require any obscure syntax or modules that may become outdated in the future.

  3. It's easy to implement.

I chose this particular solution because the underlying algorithm is very intuitive.

I don't know any issues my recipe, but maybe the only downfall is the limitation that we are restricted to converting to base numbers less than or equal to 10.

1 comment

Marko Kukovec 10 years, 7 months ago  # | flag

Here is another simpler solution:

'''
Created on 20. sep. 2013

@author: Kukovec
'''

def __DecimalToAnyBaseArrayRecur__(array, decimal, base):
    array.append(decimal % base)
    div = decimal / base
    if(div == 0):
        return;
    __DecimalToAnyBaseArrayRecur__(array, div, base)

def DecimalToAnyBaseArray(decimal, base):
    array = []
    __DecimalToAnyBaseArrayRecur__(array, decimal, base)
    return array[::-1]

def Test():
    print DecimalToAnyBaseArray(1258, 16)
    print DecimalToAnyBaseArray(1258, 10)
    print DecimalToAnyBaseArray(1258, 8)
    print DecimalToAnyBaseArray(1258, 2)

if __name__ == "__main__":
    Test()

Output:

[4, 14, 10]
[1, 2, 5, 8]
[2, 3, 5, 2]
[1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0]