问题描述
我正在尝试编写一个可以将数字转换为任何基本系统的递归代码.例如,将整数 10 转换为二进制将转换为 1010
到目前为止我有这个,但我的输出之间有无".有人可以帮我写代码吗?
def convert(a,b):添加 = a%b如果 a
我的想法是 a%b 是要添加到数字末尾的数字,而 a//b 是递归部分,它使用前一个二进制数的答案,因此基数 2 中的 10 只是 convert(5,2) 并在末尾添加 0,因为 a//b=5 和 a%b=0 which = 1010
我正在为此制作一个 pip 包.
我建议你使用我的 bases.py https://github.com/kamijoutouma/bases.py 灵感来自于 bases.js
from bases import Bases基数 = 基数()bases.toBase16(200)//=>'c8'bases.toBase(200, 16)//=>'c8'bases.toBase62(99999)//=>'q0T'bases.toBase(200, 62)//=>'q0T'bases.toAlphabet(300, 'aAbBcC')//=>'阿爸'bases.fromBase16('c8')//=>200bases.fromBase('c8', 16)//=>200bases.fromBase62('q0T')//=>99999bases.fromBase('q0T', 62)//=>99999bases.fromAlphabet('Abba', 'aAbBcC')//=>300
参考https://github.com/kamijoutouma/bases.py#known-基本字母可用于哪些碱基
对于您的特定问题
如果您想要二进制并返回,您可以这样做
>>>从基地进口基地>>>基数 = 基数()>>>bases.toBase(200,2)'11001000'>>>bases.fromBase('11001000',2)200>>>bases.toBase2(200)'11001000'>>>bases.fromBase2('11001000')200玩得开心!!!
再次获取此库的可用基础列表,请参阅https://github.com/kamijoutouma/bases.py#known-basesalphabets
I am trying to write a recursive code that can convert a number to any base system. for example, the integer 10 into binary would convert to 1010
So far I have this but I'm having "None" in between my output. Can anyone help me with my code?
def convert(a,b):
add = a%b
if a<=1:
return a
else:
print(base(a//b,b), add)
my idea is that a%b is the number to add to the end of the number and a//b is the recursive part where it uses the answer of the previous binary number so 10 in base 2 is just convert(5,2) and add the 0 at the end since a//b=5 and a%b=0 which = 1010
I'm working on making a pip package for this.
I recommend you use my bases.py https://github.com/kamijoutouma/bases.py which was inspired by bases.js
from bases import Bases
bases = Bases()
bases.toBase16(200) // => 'c8'
bases.toBase(200, 16) // => 'c8'
bases.toBase62(99999) // => 'q0T'
bases.toBase(200, 62) // => 'q0T'
bases.toAlphabet(300, 'aAbBcC') // => 'Abba'
bases.fromBase16('c8') // => 200
bases.fromBase('c8', 16) // => 200
bases.fromBase62('q0T') // => 99999
bases.fromBase('q0T', 62) // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300
refer to https://github.com/kamijoutouma/bases.py#known-basesalphabetsfor what bases are usable
For your particular question
If your looking to go binary and back you can do
>>> from bases import Bases
>>> bases = Bases()
>>> bases.toBase(200,2)
'11001000'
>>> bases.fromBase('11001000',2)
200
>>> bases.toBase2(200)
'11001000'
>>> bases.fromBase2('11001000')
200
Have Fun !!!
And again for a list of usable bases with this library refer to https://github.com/kamijoutouma/bases.py#known-basesalphabets
这篇关于在python中使用递归将整数转换为base-x系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!