Takes in any non-negative integer and converts to the desired base-n for 1<=n<=10.
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:
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).
It's reliable in that this program doesn't require any obscure syntax or modules that may become outdated in the future.
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.
Here is another simpler solution: