Here's an integer to base n string function, and a generator function that counts in base n.
#!/usr/bin/env python
''' base `n` conversion and counting
See http://stackoverflow.com/q/33610302/4014959
Written by PM 2Ring 2015.11.10
'''
def int_to_base_n(i, base):
''' Convert integer `i` to base `base`
base must be <= 10
'''
digits = []
while i:
i, d = divmod(i, base)
digits.append(str(d))
if not digits:
return '0'
return ''.join(digits[::-1])
def base_n_counter(base):
''' An infinite iterator that counts in base `base`
base must be <= 10
'''
digits = [0]
yield '0'
while True:
digits[0] += 1
pos = 0
while digits[pos] == base:
digits[pos] = 0
pos += 1
if pos >= len(digits):
digits.append(1)
else:
digits[pos] += 1
yield ''.join([str(d) for d in reversed(digits)])
# Test
base = 2
counter = base_n_counter(base)
print 'base', base
for i in range(16):
print i, int_to_base_n(i, base), next(counter)
print
base = 6
print 'base', base
for i, s in enumerate(base_n_counter(base)):
print i, int_to_base_n(i, base), s
if i == base ** 2:
break
output
base 2
0 0 0
1 1 1
2 10 10
3 11 11
4 100 100
5 101 101
6 110 110
7 111 111
8 1000 1000
9 1001 1001
10 1010 1010
11 1011 1011
12 1100 1100
13 1101 1101
14 1110 1110
15 1111 1111
base 6
0 0 0
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 10 10
7 11 11
8 12 12
9 13 13
10 14 14
11 15 15
12 20 20
13 21 21
14 22 22
15 23 23
16 24 24
17 25 25
18 30 30
19 31 31
20 32 32
21 33 33
22 34 34
23 35 35
24 40 40
25 41 41
26 42 42
27 43 43
28 44 44
29 45 45
30 50 50
31 51 51
32 52 52
33 53 53
34 54 54
35 55 55
36 100 100
Both of these functions only work correctly if base <= 10
. However, it's easy to modify them to handle larger bases: replace the str(d)
with digit_string[d]
, where digit_string
is a string containing the desired digits.