python - 位数递减的最小数
问题描述
我发现了一个实现函数的问题,该函数将正整数 n 作为输入并返回大于 n 且位数在减少的最小正整数,类似地对于返回大于 n 且位数在增加的最小正整数的函数。我认为递增函数工作正常。但是函数减少的错误是什么?对于输入 reduction(100),它返回 11 而不是 110。
# the next integer whose digits are increasing.
def increasing(n):
asastring = str(n)
length = len(asastring)
if asastring == "9"*length:
return "1"*(length+1)
if length == 1:
return int(n)+1
if length >= 2:
firstcharacter = asastring[0]
secondcharacter = asastring[1]
if int(firstcharacter) > int(secondcharacter):
return int(str(firstcharacter)*length)
if firstcharacter == secondcharacter:
return firstcharacter+str(increasing(int(asastring[1:])))
if int(firstcharacter) < int(secondcharacter):
if secondcharacter == "9":
return str(int(firstcharacter)+1) * len(str(n))
return firstcharacter+str(increasing(int(asastring[1:])))
# the next integer whose digits are decreasing.
def decreasing(n):
asastring = str(n)
length = len(asastring)
# First the case where we need to add a digit.
if asastring == "9"*length:
return "1"+"0"*length
# Now we know that the next integer has the same number of digits as the original number.
if length == 1:
return int(n)+1
if length >= 2:
firstcharacter = asastring[0]
secondcharacter = asastring[1]
if int(firstcharacter) > int(secondcharacter):
endpart = str(((asastring[1:3])))
value = firstcharacter + str(decreasing(int(asastring[1:])))
return str(firstcharacter) + str(decreasing(int(asastring[1:])))
if int(firstcharacter) == int(secondcharacter):
return decreasing(firstcharacter+str(decreasing(int(asastring[1:]))))
if int(firstcharacter) < int(secondcharacter):
return str(int(firstcharacter)+1)+'0'*(length-1)
i=100
print(increasing(i))
print(decreasing(i))
解决方案
您需要删除递归调用中完成的 int 类型转换,因为 int('00') 正在将您的数字转换为零(基本上删除所有起始零)并缩短字符串的长度。只需删除该铸造..其余代码工作正常:
def decreasing(n):
asastring = str(n)
length = len(asastring)
# First the case where we need to add a digit.
if asastring == "9"*length:
return "1"+"0"*length
# Now we know that the next integer has the same number of digits as the original number.
if length == 1:
return int(n)+1
if length >= 2:
firstcharacter = asastring[0]
secondcharacter = asastring[1]
if int(firstcharacter) > int(secondcharacter):
return str(firstcharacter) + str(decreasing(asastring[1:]))
if int(firstcharacter) == int(secondcharacter):
return decreasing(firstcharacter+str(decreasing(asastring[1:])))
if int(firstcharacter) < int(secondcharacter):
return str(int(firstcharacter)+1)+'0'*(length-1)
推荐阅读
- python - Python & Pandas:构造 lambda 参数
- firebase - 带有 nginx 代理服务器的 Firebase 自定义域“需要设置”
- flutter - 如何在颤动中获取列表的值表单字段?我需要颤振表单字段的帮助
- powerbi - DAX过滤器功能不过滤
- reactjs - 反应:成功认证后重定向到 PrivateRoute 不起作用
- python - Heroku 网络中的 H14
- facebook - 是否可以在 facebook 墙上删除后调用 webhook?
- r - 使用坐标数据创建一个线对象
- json - 对象内部的 API 值在 Postman 和应用程序之间返回不同
- javascript - 如何检查特定对象键是否作为另一个对象键的值存在?