如何在 Python 中使用基数为 5 的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2288482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:16:26  来源:igfitidea点击:

How can I work with base 5 numbers in Python?

pythonmath

提问by Pepijn

Possible Duplicate:
convert integer to a string in a given numeric base in python

可能的重复:
在python中将整数转换为给定数字基数的字符串

I want to work with base 5 numbers, or any other non standard base for that matter.

我想使用基数为 5 的数字,或任何其他非标准基数。

I found out int('123', 5)works, but I need to go the other way around.

我发现了int('123', 5)作品,但我需要反过来。

Should I write my own number class to accomplish this?

我应该编写自己的数字类来完成这个吗?

Maybe I'm just thinking in the wrong direction...

也许我只是想错了方向......

采纳答案by John La Rooy

def to_base_5(n):
    s = ""
    while n:
        s = str(n % 5) + s
        n /= 5
    return s

回答by Shane Holloway

I had fun with this a while ago for a python-dev thread. The original post can be found at http://mail.python.org/pipermail/python-dev/2006-January/059925.htmlThis particular algorithm can perform floating point bases as well.

不久前,我在一个 python-dev 线程中玩得很开心。原始帖子可以在http://mail.python.org/pipermail/python-dev/2006-January/059925.html找到。 这个特定的算法也可以执行浮点运算。

#!/usr/bin/env python
import math

def ibase(n, radix=2, maxlen=None):
    r = []
    while n:
        n,p = divmod(n, radix)
        r.append('%d' % p)
        if maxlen and len(r) > maxlen:
            break
    r.reverse()
    return ''.join(r)

def fbase(n, radix=2, maxlen=8):
    r = []
    f = math.modf(n)[0]
    while f:
        f, p = math.modf(f*radix)
        r.append('%.0f' % p)
        if maxlen and len(r) > maxlen:
            break
    return ''.join(r)

def base(n, radix, maxfloat=8):
    if isinstance(n, float):
        return ibase(n, radix)+'.'+fbase(n, radix, maxfloat)
    elif isinstance(n, (str, unicode)):
        n,f = n.split('.')
        n = int(n, radix)
        f = int(f, radix)/float(radix**len(f))
        return n + f
    else:
        return ibase(n, radix)

if __name__=='__main__':
    pi = 3.14
    print 'pi:', pi, 'base 10'

    piBase3 = base(pi, 3)
    print 'pi:', piBase3, 'base 3'

    piFromBase3 = base(piBase3, 3)
    print 'pi:', piFromBase3, 'base 10 from base 3'