首页 > 解决方案 > TypeError in Recursive Function (Decimal to Binary)

问题描述

all, I have this code that, for the life of me, I can't figure out how to solve this TypeError.

def dtobr(n):
    if n == 0:
        return 0
    else:
        return (n % 2) + 10 * dtobr(int(n / 2))

I need it to return as a string (project requirement for class). The math is correct, but when I change the last line to

return str((n % 2) + 10 * dtobr(int(n / 2)))

I get

"TypeError: unsupported operand type(s) for +: 'int' and 'str'".

I have tried setting "return (n % 2) + 10 * dtobr(int(n / 2))" to x, setting y to int(x) and returning y, and I've have no clue (and Google isn't offering any solutions that I can try to apply to my problem) what else I can do. Any ideas would be helpful!!

标签: pythonrecursion

解决方案


在返回上执行str()意味着所有递归调用也将返回 a str,因此您需要将这些返回转换回 a int,例如:

def dtobr(n):
    if n == 0:
        return '0'
    else:
        return str((n % 2) + 10 * int(dtobr(n // 2)))

In []:
dtobr(10)

Out[]:
'1010'

或者只是使用辅助函数进行转换:

def dtobr(n):
    return str(dtobr_(n))

def dtobr_(n):
    if n == 0:
        return 0
    else:
        return (n % 2) + 10 * dtobr_(n // 2)

In []:
dtobr(10)

Out[]:
'1010'

但我不明白为什么只是跟注str(dtobr(10))不会同样好。

注意://是整数除法,所以你不需要int(n/2)n//2会做。


推荐阅读