def str2int(s):
result = 0
if s[0] == '-':
sign = -1
i = 1
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
result = sign * result
return result
else:
i = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return result
def int2str(i):
strng = ""
if i > 0:
while i != 0:
num = i % 10
strng += chr(48+num)
i = i / 10
return strng[::-1]
else:
while i != 0:
num = abs(i) % 10
strng += chr(48+num)
i = abs(i) / 10
return '-' + strng[::-1]
我是新手,我必须根据基本编写代码。我自己写这些功能,但这些看起来很奇怪。你能帮我改进代码吗?谢谢
答案 0 :(得分:0)
https://codereview.stackexchange.com/这可能是一个更好的问题
不管没有错误检查,一个明显的评论是你有可以考虑的常用代码。仅在if
,else
中捕获唯一的内容,而不是重复while
循环:
def str2int(s):
if s[0] == '-':
sign = -1
i = 1
else:
sign = 1
i = 0
result = 0
while i < len(s):
num = ord(s[i]) - ord('0')
result = result * 10 + num
i += 1
return sign * result
在python中通常认为迭代列表而不是索引是更好的形式:
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
result = 0
for c in s:
num = ord(c) - ord('0')
result = result * 10 + num
return sign * result
这些最后一行等同于标准map
和reduce
(reduce
在functools
中对于py3)。虽然有些人会反对它:
from functools import reduce # Py3
def str2int(s):
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
return sign * reduce(lambda x,y: x*10+y, map(lambda c: ord(c) - ord('0'), s))
对int2str()
也有类似的机会。