I would like to make a function which convert an integer into exponents of base 27. The function should return a list with the multiple of the largest exponent in the first position and the final exponent in the last. So for example, 65 would return [2,11]. I've tried using int % b, where b is an increasing power of 27 within a loop. However it's turning out very complicated. Any help?
Asked
Active
Viewed 246 times
1
-
1http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python – Chad Miller Oct 08 '15 at 15:41
-
You're not seeking *exponents*. You're seeking *coefficients*. Namely, coefficients to be multiplied by successive powers of 27. You already know the exponents, which for the list in your example would be 1 and 0, respectively. – Rob Kennedy Oct 08 '15 at 15:47
-
@tobias, yes and not into letters – Oct 08 '15 at 15:48
-
@idjaw, ok but It seems over complicated and unnecessarily long and inefficient, so I didn't think it would help (i'm a beginner) – Oct 08 '15 at 15:48
2 Answers
3
def convert(x, base):
res = []
while x:
res.append(x%base)
x //= base # this line depends on Python's version!
res.reverse()
return res

Roman Dobrovenskii
- 935
- 10
- 23
-
3You can use `x, r = divmod(x, base)` to do both integer division and modulo in one step, then append `r` – tobias_k Oct 08 '15 at 15:45
-
1The `x //= base` line should be fine in any (non-ancient) Python version. – Mark Dickinson Oct 08 '15 at 15:46
-
2@tobias_k: Sadly, unless the numbers in question are huge, using `divmod` is almost always slower, because looking up and explicitly calling builtin functions has enormous overhead (at least in CPython), such that doing the same work with syntax is usually faster. For `x` below a hundred bits (give or take, depending on `base`), `q, r = x // base, x % base` is faster than `q, r = divmod(x, base)`, which sounds ridiculous, but this is Python, and performance doesn't have to make sense. – ShadowRanger Oct 08 '15 at 15:51
1
Try this:
def base_27(num):
if num == 0:
return []
q, r = divmod(num, 27)
result = base_27(q)
result.append(r)
return result

Paul Boddington
- 37,127
- 10
- 65
- 116
-
Nice, but could be shorter: `return base_27(num // 27) + [num % 27] if num else []` – tobias_k Oct 08 '15 at 15:55
-
@tobias_k Thanks. I barely know Python but I'm learning it to try to get the generalist badge. Is anything other than 0 basically true? – Paul Boddington Oct 08 '15 at 15:59
-
1Not everything. What evaluates to false are things like 0, empty string, empty collection, None, etc.; most other things evaluate to true. – tobias_k Oct 08 '15 at 16:14