python - 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!!
解决方案
在返回上执行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
会做。
推荐阅读
- python - y-shift 每秒 xtick
- javascript - chart.js:连接两个折线图的问题
- .htaccess - 如何强制将 http 和 www 重定向到 https
- javascript - 带有 CDN 的 Vue - 设置组件样式的最佳方式
- windows - 我们可以在复制过程中打开 Robocopy 日志吗?
- python - Floyd-Warshall 到 Graph networkx
- ios - 如何检查 nil 是否已经强制向下转换的属性
- r - 为什么向量没有用新值更新
- teradata - 自动提交 Teradata SQL 助手
- android - 没有为多个单词设置可点击跨度