-1

I want to have a range() function that works in different bases (namely base 4).

I could do the following if the amount of digits are known:

for a in range(4):
    for b in range(4):
        print str(a) + str(b)

However the amount of digits needed to be generated is unknown. I'm thinking I will need recursion of some kind.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user2122589
  • 275
  • 1
  • 5
  • 17
  • 2
    The base/radix is purely a display concern, you just need a regular `range(16)` and a function that converts an `int` to a `str` of the appropriate format (`hex`, `oct` and `bin` are built in, but you'll need to write your own for base 4). – jonrsharpe Mar 19 '17 at 00:09
  • 1
    Possible duplicate of [How to convert an integer in any base to a string?](http://stackoverflow.com/questions/2267362/how-to-convert-an-integer-in-any-base-to-a-string) – Terry Jan Reedy Mar 19 '17 at 00:27

2 Answers2

3
import itertools
import string

digits_len = 2
digits_repr = string.digits[:4]
for digits in itertools.product(digits_repr, repeat=digits_len):
    print ''.join(digits)
Brian Rodriguez
  • 4,250
  • 1
  • 16
  • 37
0

Thanks to jonrsharpe's comment I came up with the following solution. Not elegant but does the job! Thank you!

import string
digs = string.digits + string.letters

def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1
    x *= sign
    digits = []
    while x:
        digits.append(digs[x % base])
        x /= base
    if sign < 0:
        digits.append('-')
    digits.reverse()
    return ''.join(digits)

base = 4
digits = 2

for x in range(base**digits):
    print int2base(x, base).zfill(digits) 
user2122589
  • 275
  • 1
  • 5
  • 17