python取反函数_Python优雅的反函数int(string,base)

我曾经用同样的目标编写了自己的函数,但现在却令人尴尬地复杂化了。

from math import log, ceil, floor

from collections import deque

from itertools import repeat

from string import uppercase, digits

import re

__alphanumerals = (digits + uppercase)

class InvalidBaseError(ValueError): pass

class FloatConvertError(ValueError): pass

class IncorrectBaseError(ValueError): pass

def getbase(number, base=2, frombase = 10):

if not frombase == 10:

number = getvalue(number, frombase)

#getvalue is also a personal function to replicate int(number, base)

if 1 >= base or base >= len(__alphanumerals) or not floor(base) == base:

raise InvalidBaseError("Invalid value: {} entered as base to convert

to. n{}".format(base,

"Assert that the base to convert to is a decimal integer."))

if isinstance(number, str):

try:

number = atof(number)

except ValueError:

#The first check of whether the base is 10 would have already corrected the number

raise IncorrectBaseError("Incorrect base passed as base of number -> number: {} base: {}".format(number, frombase))

#^ v was supporting float numbers incase number was the return of another operation

if number > floor(number):

raise FloatConvertError("The number to be converted must not be a float. {}".format(number))

isNegative = False

if number < 0:

isNegative = True

number = abs(number)

logarithm = log(number, base) if number else 0 #get around number being zero easily

ceiling = int(logarithm) + 1

structure = deque(repeat(0, ceiling), maxlen = ceiling)

while number:

if number >= (base ** int(logarithm)):

acceptable_digit = int(number / (base ** floor(logarithm)))

structure.append(acceptable_digit if acceptable_digit < 10 else __alphanumerals[acceptable_digit])

number -= acceptable_digit * (base ** floor(logarithm))

else:

structure.append(0)

logarithm -= 1

while structure[0] == 0:

#the result needs trailing zeros

structure.rotate(-1)

return ("-" if isNegative and number else "") + reduce(lambda a, b: a + b, map(lambda a: str(a), structure))

我认为函数strbase应该只支持base> = 2和&lt; = 36以防止与python中的其他工具冲突,例如int。

另外,我认为只应该使用一个字母大小写字母,最好是大写,以防止与其他函数如int冲突,因为它会认为“a”和“A”都是10。

from string import uppercase

dig_to_chr = lambda num: str(num) if num < 10 else uppercase[num - 10]

def strbase(number, base):

if not 2 <= base <= 36:

raise ValueError("Base to convert to must be >= 2 and <= 36")

if number < 0:

return "-" + strbase(-number, base)

d, m = divmod(number, base)

if d:

return strbase(d, base) + dig_to_chr(m)

return dig_to_chr(m)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值