【问题标题】:How can I do this effectively? [closed]我怎样才能有效地做到这一点? [关闭]
【发布时间】:2020-08-01 22:06:06
【问题描述】:

这个问题:

输入:123456

结果:

1+2+3+4+5+6 = 21
2+1 = 3

返回:3

这是我的代码:

num = input()
print(sum(list(map(int, list(num)))))

直到1位数我才知道该怎么做。

【问题讨论】:

  • 您尝试完成什么以及从哪里获得2+1?这背后有什么逻辑吗?
  • 在问题中显示您尝试的格式正确的代码。
  • 在你要求别人为你做作业之前,先花点力气。 How to ask
  • 2+1 是最新求和的返回。
  • @March,我已经修改了我的答案,请看一下,现在更具可读性和简洁性。

标签: python python-3.x


【解决方案1】:

使用sum()list comprehensionrecursion 的一种方法,

def simulated_sum(input):
    """This is a recursive function
    to find the simulated sum of an integer"""

    if len(str(input)) == 1:
        return input
    else:
        input_digits = [int(x) for x in str(input)]
        latest_sum = sum(input_digits)
        return simulated_sum(latest_sum)

input = int(input('Enter a number'))    
print(simulated_sum(input))

演示: https://rextester.com/WCBXIL71483

【讨论】:

    【解决方案2】:

    你可以试试这个:

    s = input()
    while(len(s)>1):
        s = str(sum(list(map(int,s))))
    

    【讨论】:

      【解决方案3】:

      一种方式:

      while len(str(ans))>1:
          ans = sum(map(int, str(ans)))
      

      完整代码:

      num = 45637
      ans = num
      
      while len(str(ans))>1:
          ans = sum(map(int, str(ans)))
      
      print(ans)
      

      输入 45637 的输出:

      7
      

      【讨论】:

        【解决方案4】:

        试试这个(IPython 中的示例):

        In [1]: s = '123456'
        Out[1]: '123456'
        
        In [2]: digits = [int(j) for j in s]
        Out[2]: [1, 2, 3, 4, 5, 6]
        
        In [3]: s = str(sum(digits))
        Out[3]: '21'
        

        重复第 2 步和第 3 步,直到 len(s) == 1

        【讨论】:

          【解决方案5】:

          这是你想要的吗? (说明不清楚):

          def myfunction(number):
              total = 0
              answertotal = 0
              for i in str(number):
                  total += int(i)
              for i in str(total):
                  answertotal += int(i)
              return answertotal
          
          myfunction(123456)
          

          这个函数返回 3

          【讨论】:

            猜你喜欢
            • 2022-11-09
            • 2013-03-30
            • 1970-01-01
            • 1970-01-01
            • 2018-10-05
            • 2015-05-01
            • 1970-01-01
            • 2012-08-18
            • 1970-01-01
            相关资源
            最近更新 更多