马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 一个账号 于 2021-1-7 20:03 编辑
这个代码还有很多地方需要完善,欢迎大家一起交流
import math
def atoi(x=0, base=10) -> int:
if base < 2 and base != 0 or base > 36:
raise ValueError("atoi() base must be >= 2 and <= 36, or 0")
if isinstance(x, int):
if base != 10:
raise TypeError("atoi() can't convert non-string with explicit base")
return x
if isinstance(x, float):
if base != 10:
raise TypeError("atoi() can't convert non-string with explicit base")
return math.floor(x)
if isinstance(x, bytes):
if base != 10:
raise TypeError("atoi() can't convert non-string with explicit base")
x = x.decode()
if isinstance(x, str):
num = 0
current_num = 0
if not base:
base = 10
if x:
symbol = -1 if x[0] == "-" else 1
x = x[1:] if x[0] in "+-" else x
bit = pow(base, len(x)-1)
else:
raise ValueError('invalid literal for atoi() with base 10: ""')
for i in x:
if i not in "0123456789ABCDEF":
raise ValueError(f'invalid literal for atoi() with base {base}: "{x}"')
elif i == "0":
pass
elif i == "1":
num += 1 * bit * symbol
current_num = 1
elif i == "2":
num += 2 * bit * symbol
current_num = 2
elif i == "3":
num += 3 * bit * symbol
current_num = 3
elif i == "4":
num += 4 * bit * symbol
current_num = 4
elif i == "5":
num += 5 * bit * symbol
current_num = 5
elif i == "6":
num += 6 * bit * symbol
current_num = 6
elif i == "7":
num += 7 * bit * symbol
current_num = 7
elif i == "8":
num += 8 * bit * symbol
current_num = 8
elif i == "9":
num += 9 * bit * symbol
current_num = 9
elif i == "A":
num += 10 * bit * symbol
current_num = 10
elif i == "B":
num += 11 * bit * symbol
current_num = 11
elif i == "C":
num += 12 * bit * symbol
current_num = 12
elif i == "D":
num += 13 * bit * symbol
current_num = 13
elif i == "E":
num += 14 * bit * symbol
current_num = 14
elif i == "F":
num += 15 * bit * symbol
current_num = 15
if current_num >= base:
raise ValueError(f'invalid literal for atoi() with base {base}: "{x}"')
bit //= base
return num
raise TypeError(f'atoi() argument must be a string, a bytes-like object or a number, not "{type(x).__name__}"')
|