【问题标题】:Count the digits in a number计算一个数字中的位数
【发布时间】:2021-12-07 10:58:37
【问题描述】:

我写了一个函数叫count_digit:

# Write a function which takes a number as an input
# It should count the number of digits in the number
# And check if the number is a 1 or 2-digit number then return True 
# Return False for any other case
def count_digit(num):
    if (num/10 == 0):
        return 1
    else:
        return 1 + count_digit(num / 10);


print(count_digit(23))

我得到325 作为输出。为什么会这样,我该如何纠正?

【问题讨论】:

  • 使用 Python 2 或 3?
  • return len(str(num))
  • @LarrytheLlama,OP 可能正在尝试执行递归函数。这很有效
  • 你应该使用整数除法(// 而不是/)或者这里建议的更简单的方法。
  • 数字中的位数究竟是什么意思?

标签: python filter count


【解决方案1】:

将整数转换为字符串,然后对转换后的字符串使用 len() 方法。除非您也考虑将浮点数作为输入,而不是仅使用整数。

【讨论】:

    【解决方案2】:

    这是Python3 行为。 / 返回 float 而不是 integer 除法。

    将您的代码更改为:

    def count_digit(num):
        if (num//10 == 0):
            return 1
        else:
            return 1 + count_digit(num // 10)
    
    print(count_digit(23))
    

    【讨论】:

    • 去掉'else'怎么样,在return之后
    • @datdinhquoc 我认为对于初学者来说,最好在此处明确使用“else”。
    【解决方案3】:

    递归

    def count_digit(n):
        if n == 0:
            return 0
        return count_digit(n // 10) + 1
    

    简单

    def count_digit(n):
        return len(str(abs(n)))
    

    【讨论】:

    • @Timus 完成。已添加abs()
    【解决方案4】:

    假设您总是将整数发送到函数并且您要求数学答案,这可能是您的解决方案:

    import math
    
    
    def count_digits(number):
        return int(math.log10(abs(number))) + 1 if number else 1
    
    
    if __name__ == '__main__':
        print(count_digits(15712))
        # prints: 5
    

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 2011-07-19
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多