我想知道如何在python中执行等效的range函数,但是能够指定基数.例如:
countUp(start=0, end=1010, base=2)
countUp(start=0, end=101, base=3)
countUp(start=0, end=22, base=4)
Run Code Online (Sandbox Code Playgroud)
基数2计数的示例输出:
[0, 1, 10, 11, 100, ...]
Run Code Online (Sandbox Code Playgroud)
是否有一个我缺少的功能呢?或者我该怎么做呢?
你显然把数字与数字的表示混淆了.
一些不具有碱...它的数表示,其具有基极...例如数字在基座2表示为"101"是相同的,与"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]
Run Code Online (Sandbox Code Playgroud)
您可以使用自定义迭代器来完成此操作:
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)
Run Code Online (Sandbox Code Playgroud)
一些示例运行产生:
>>> 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1310 次 |
最近记录: |