Python - 使用递归将数字字符串转换为整数?

标签 python recursion

假设我有一个 string = '123',但我想将其转换为 123,而不使用 int() 函数。我将如何使用递归来完成此操作? 到目前为止,我的想法是将字符串放入数组中,例如 ['1','2','3'],然后根据 ASCII 表示进行转换。

for i in string:

myArr.append (ord(i) - ord('0'))

所以现在我有一个看起来像 [1,2,3] 的列表。接下来我应该做什么来递归得到123? 我有一个想法,使用位值并将它们加在一起(即 100 + 20 + 3 = 123),但我不知道该怎么做。任何想法都会有帮助!

最佳答案

我想这是一个学术练习,因为这是一个相当做作的问题。假设 s 表示大于或等于零的整数:

def strToInt(s, acc):
    if not s:
        return acc
    return strToInt(s[1:], 10 * acc + ord(s[0]) - 48)

或者更短:

def strToInt(s, acc):
    return strToInt(s[1:], 10 * acc + ord(s[0]) - 48) if s else acc

诀窍是将转换结果累积在一个额外的参数中,这具有产生尾递归解决方案的良好副作用(这在 Python 中并不重要,但仍然......)。另请注意我们如何使用 ord() 获取代表数字的字符的数值,并通过简单地减去 48 我们得到实际的数字值。测试了一下,效果符合预期:

strToInt('123', 0) # the accumulator always starts in zero
=> 123

关于Python - 使用递归将数字字符串转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734672/

相关文章:

c++ - 为什么我的函数返回正确的值,即使我将 8 作为第一个数字?

python - 使用 np.fromfile 或 open & struct 读取 fortran 二进制文件(流式访问)

python - 创建集群需要 InstanceProfile - 创建 python 函数来安装模块

python - 为什么 Pandas 将日期时间转换为聚合函数中的 float

python - 当你调用 `if key in dict` 时会发生什么

javascript - Node.JS 递归 promise 无法解析

javascript - 使用 ng-include 的 angularjs Treeview 为所有节点的父节点触发 ng-click

caching - 使用 memcacheD 进行缓存的初学者指南

python - 线图中的非重叠误差线

javascript - js Array.prototype.filter.call() - 有人能解释一下这段代码是如何工作的吗?