【问题标题】:recursive sum of all the digits in a number数字中所有数字的递归和
【发布时间】:2020-07-28 16:39:51
【问题描述】:

我被困在这个练习中。

任务:

数字根是数字中所有数字的递归和。给定n,取n的位数之和。如果该值超过一位,则继续以这种方式减少,直到产生一位数。这仅适用于自然数。

它是这样工作的:

digital_root(16)
1 + 6 = 7

digital_root(942)
9 + 4 + 2 = 15 ... 1 + 5 =6

我的方法就在这里。关于如何正确返回正确值的任何提示?我将不胜感激。

def digital_root(n):
    answ = 0
    s = 0
    x = str(n)

    for i in range(0, len(x)):
        s = s + int(x[i])
    if len(str(s)) > 1:
        digital_root(s)
    elif len(str(s)) == 1:
        answ = s # here is an answer
        return answ # answer is 2 but this one is not returning 2, why?

    return answ # here it returns answ=0, I want to return 2...

print(digital_root(493193))

【问题讨论】:

    标签: python python-3.x recursion return


    【解决方案1】:

    对于递归函数,最好从最基本的情况开始,然后逐步增加复杂性。

    另外,一个有用的技巧是使用字符串的list() 将字符串切割成字符,因此list("abc") 返回["a", "b", "c"]

    使用这个,我们得到:

    def digital_root(n):
        # basic scenario: n is 1 digit, ergo <10. 
        if n < 10:
             return n
    
        # alternative case: more than 1 digit
        # cut n into digits with a list comprehension
        # str(714) => "714", list(str(714)) => "['7', '1', '4']
        digits = [int(c) for c in list(str(n))]
    
        # take the digital root of the sum
        return digital_root(sum(digits))
    

    【讨论】:

      【解决方案2】:

      你对递归调用的结果什么都不做——这就是你的代码出错的原因。

      通过索引迭代大多不好 - 更好地直接迭代字符串。


      这是使用一些built in python 函数进行递归的一种更简洁的方法:

      def rec_sum(n):
          sn = str(n)
          # base case - return the number
          if len(sn)==1:
              return n
      
          # not the base case,return whatever the recursive output returns
          return rec_sum(sum(map(int,sn)))
      
      
      for n in range(1,71):
          print(f"{n:3}=>{rec_sum(n):3}", end = "|")
          if n%7 == 0:
              print()
      

      输出:

        1=>  1|  2=>  2|  3=>  3|  4=>  4|  5=>  5|  6=>  6|  7=>  7|
        8=>  8|  9=>  9| 10=>  1| 11=>  2| 12=>  3| 13=>  4| 14=>  5|
       15=>  6| 16=>  7| 17=>  8| 18=>  9| 19=>  1| 20=>  2| 21=>  3|
       22=>  4| 23=>  5| 24=>  6| 25=>  7| 26=>  8| 27=>  9| 28=>  1|
       29=>  2| 30=>  3| 31=>  4| 32=>  5| 33=>  6| 34=>  7| 35=>  8|
       36=>  9| 37=>  1| 38=>  2| 39=>  3| 40=>  4| 41=>  5| 42=>  6|
       43=>  7| 44=>  8| 45=>  9| 46=>  1| 47=>  2| 48=>  3| 49=>  4|
       50=>  5| 51=>  6| 52=>  7| 53=>  8| 54=>  9| 55=>  1| 56=>  2|
       57=>  3| 58=>  4| 59=>  5| 60=>  6| 61=>  7| 62=>  8| 63=>  9|
       64=>  1| 65=>  2| 66=>  3| 67=>  4| 68=>  5| 69=>  6| 70=>  7|
      

      sum(map(int,sn)) 部分的意思是:map(function,iterable)int() 函数应用于sn 中的所有字符(字符串是可迭代的),这是您的号码的字符串。然后它sum()s 它并用那个总和调用它自己。

      【讨论】:

        【解决方案3】:

        主要问题是,在进行递归调用时,您没有将返回值分配给任何东西,因此对于需要多次传递的任何值,您总是会得到 0。

        另外,在递归调用之后,长度应该是 1,所以下面的 elif 是不必要的,并且会导致错误的返回值,因为它不会将 s 分配给 answ

        固定版本:

        def digital_root(n):
            answ = 0
            s = 0
            x = str(n)
            for i in range(0, len(x)):
                s = s + int(x[i])
            if len(str(s)) > 1:
               s = digital_root(s)
            answ = s # You could even return s directly
            return answ
        
        print(digital_root(493193))
        

        【讨论】:

          【解决方案4】:

          这是我的看法。我有使用sum 的冲动,但这几乎感觉像是在作弊,因为您可以使用sum([int(i) for i in str(n)])

          def digital_root(n):
              # convert to a string
              as_str = str(n)
          
              # get the value of the current first digit
              value = int(as_str[0])
          
              if len(as_str) > 1:
                  # add the recursive return plus the value
                  # for anything other than our base case.
                  # pass the rest of the digits into our recursive call
                  return digital_root(int(as_str[1:])) + value
          
              # our base case
              return value
          
          print(digital_root(493193))
          

          【讨论】:

            【解决方案5】:

            您对此有何看法:

            def digital_root(n):
                if n<10 :
                     return n
                return digital_root( n%10 + digital_root( n//10 ) )
            

            【讨论】:

            • 简洁而且有点开箱即用 - 你能解释一下为什么这和原来的算法是一样的吗?
            猜你喜欢
            • 2022-01-02
            • 2022-01-14
            • 2021-07-27
            • 2015-12-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多