【问题标题】:Python recursion (format issue)Python 递归(格式问题)
【发布时间】:2021-03-10 10:53:12
【问题描述】:

编写一个递归函数replace_digit(n, d, r),用r 替换数字n 中每个出现的数字d

replace_digit(31242154125, 1, 0) => 30242054025

我的代码就是这样

def replace_digit(n, d, r):
    y=str(n)
    if len(y)==0:
        return ''
    else:
        if y[0]== str(d):
            return str(r) + replace_digit(str(n)[1:],d,r)
        else:
            return y[0]+ replace_digit(str(n)[1:],d,r)

但是,我得到的答案是字符串格式。知道如何转换为整数格式吗?我已经被困了很长一段时间了:(

【问题讨论】:

  • 返回一个整数(int(string_value)),并将返回值从递归调用再次转换为字符串。
  • 啊,这里有个问题:以0 开头的数字会丢失那个数字。您对处理数字的方向有什么进一步的说明吗?
  • 不是真的,我只需要得到显示的数字,其中'1'变成'0's

标签: python


【解决方案1】:

如果你的递归函数必须返回一个整数,那么返回整数。您始终可以将返回的整数转换回用于递归调用的字符串。

当你在调用之前用完数字时你必须停下来,所以只有在y中有2个或更多字符时才递归。

但是,这种方法存在一个大问题:在转换为 int() 时会丢弃前导零

>>> int('025')
25

你有两个选择:

  • 在转换为字符串时填充数字(使用str.zfill()format(),并使用传递给递归调用的值的长度)。
  • 从头开始递归。这也将允许您不使用字符串

这是一种使用零填充的方法:

def replace_digit(n, d, r):
    nstr = str(n)
    first, rest = nstr[0], nstr[1:]
    if rest:
        rest = str(replace_digit(rest, d, r)).zfill(len(rest))
    if first == str(d):
        first = str(r)
    return int(first + rest)

请注意,您总是希望将第一个字符与尾部分开无论如何,因此我对两者都使用了变量。

这样,当没有剩余数字时,您可以使用if rest:来防止递归,您可以在返回值上调用str()。该函数返回更新后的rest 值(可能替换第一个值)的int() 转换。

演示:

>>> replace_digit(31242154125, 1, 0)
30242054025

相反的一端递归不会有零问题,除了如果输入值以0开头。但是,您可以改为使用 除法和模块操作 直接处理整数值:

  • number % 10 以整数形式为您提供最右边的数字。
  • number // 10 给你剩余的数字,同样是整数。

您可以使用divmod() function 将这两个操作合二为一。就个人而言,我不这样做,因为我认为它不会特别提高可读性,并且using the operators is slightly faster when using CPython

您可以通过再次将返回值乘以 10,将递归调用结果与(可能被替换的)最后一位重新组合:

def replace_digit(n, d, r):
    head, last = n // 10, n % 10
    if head:
        head = replace_digit(head, d, r)
    if last == d:
        last = r
    return (head * 10) + last

这适用于任何自然数,包括 0:

>>> replace_digit(0, 1, 0)
0
>>> replace_digit(0, 0, 1)
1
>>> replace_digit(31242154125, 1, 0)
30242054025
>>> replace_digit(31242154125, 4, 9)
31292159125

【讨论】:

  • 有什么办法可以有类似我的代码吗?我对零填充还是有点陌生​​
  • @WeiHan:那是你自己做的,对不起。我为您提供了有关如何正确解决此问题的所有选项。
猜你喜欢
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2010-12-08
  • 2021-03-17
相关资源
最近更新 更多