10進数をN進数に基数変換する

30分プログラム、その631。http://gauc.no-ip.org/awk-users-jp/blis.cgi/DoukakuAWK_055にインスパイアされました。
上記のサイトと同様に、第1引数に整数、第2引数に変換したい基数を受け取って、文字列化した整数を返すようになっています。

使い方

# 8進数
print Str(42,8)

# 10進数
print Str(42,10)

# 16進数
print Str(42,16)

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# base_conv.py -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/08/01 22:09:56
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def cseq(a,b):
    for c in xrange(ord(a),ord(b)+1):
        yield chr(c)

def unreduce(f,x):
    y = f(x)
    while y != None:
        yield y[0]
        y = f(y[1])

DIGITS = list(cseq('0','9')) + list(cseq('A','Z'))

def Str(n,base):
    xs = list(unreduce(lambda m: None if m <= 0 else (m % base, m / base ) ,n))
    xs.reverse()
    return ''.join(map(lambda x: DIGITS[x] ,xs))

print Str(42,8)
print Str(42,10)
print Str(42,16)
print Str(42,42)