How can I work with base numbers 5 in Python?

Possible duplicate:
convert integer to string in given number base in python

I want to work with base numbers 5 or any other non-standard base.

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

Should I write my own number class to accomplish this?

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

+3
source share
2 answers
def to_base_5(n):
    s = ""
    while n:
        s = str(n % 5) + s
        n /= 5
    return s
+3
source

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'
+2

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


All Articles