from math import log, floor def to_base(num, base): if num == 0: return '0' largest_power = floor(log(num, base)) current_power = largest_power digits = [] while current_power >= 0: base_to_power = base ** current_power # Used in multiple calculations. this makes it simpler. # For each number that we could have to multiply by at this power, going down and including zero: for scalar in range(base - 1, -1, -1): if num >= scalar * base_to_power: digits.append(str(scalar)) # Append a string version of the scalar. num = num - scalar * base_to_power break # Break out of the loop when we find the biggest number that works. # This loop includes zero, and the number is always >= 0 * base_to_power. current_power = current_power - 1 return ''.join(digits) to_trinary = lambda x: to_base(x, 3) def test(): for base in range(2, 11): for num in range(0, 10): assert (num == int(to_base(num, base), base)) test()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question