Count up in python with variable base

I would like to know how to make the equivalent of a range function in python, but with the ability to specify a base number. For example:

countUp(start=0, end=1010, base=2)
countUp(start=0, end=101, base=3)
countUp(start=0, end=22, base=4)

Example output for counting base 2:

[0, 1, 10, 11, 100, ...]

Is there a function that I'm missing that does this? Or what can I do instead?

+7
source share
3 answers

You can do this with a custom iterator:

I took the iterator code from here and the basic conversion from here

import string
class BaseRange:
    def __init__(self, low, high, base):
        digs = string.digits + string.letters
        self.current = low
        self.high = high
        self.base = base
    def __iter__(self):
        return self
    def next(self):  # Python 3 requires this to be __next__
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.int2base(self.current - 1, self.base)
    def int2base(self, 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)

A few examples run:

>>> for c in BaseRange(0, 10, 2):
    print(c)


0
1
01
11
001
101
011
111
0001
1001
0101
>>> for c in BaseRange(0, 10, 3):
    print(c)


0
1
2
01
11
21
02
12
22
001
101
+2
source

You are apparently confusing numbers with the representation of numbers.

... , ... , , "101" 2, , "5" 10.

range , , , - :

digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def int2str(x, base):
    if x < 0:
        return "-" + int2str(-x, base)
    return ("" if x < base else int2str(x//base, base)) + digits[x % base]
+8

, :

def my_range(start,end,base,step=1):

    def Convert(n,base):
       string = "0123456789ABCDEF"
       if n < base:
          return string[n]
       else:
          return Convert(n//base,base) + string[n%base]
    return (Convert(i,base) for i in range(start,end,step))

:

print list(my_range(4,20,2))
['100', '101', '110', '111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111', '10000', '10001', '10010', '10011']

, string = "0123456789ABCDEF" 16, , .

0

Source: https://habr.com/ru/post/1618187/


All Articles