简体   繁体   English

Python中特定方式的数字总和

[英]Sum of Digits in a specific way in Python

I'm looking for a code that runs, ie:我正在寻找运行的代码,即:

    int(input) = 2565

Printed Output should be like:打印输出应该是这样的:

    2 + 5 + 6 + 5  = 18 = 1 + 8 = 9

I wrote the code that gives final answer "9".我编写了给出最终答案“9”的代码。 But I couldn't managed to write it with every digit separated "+" sign.但是我无法用每个数字分隔的“+”号来写它。 Assuming that I need to use while loop but how can I write the code so it will be like the output above?假设我需要使用 while 循环,但我该如何编写代码,使其与上面的输出类似?

You can use something like this:你可以使用这样的东西:

def sum_of_digits(s):
    if s < 10:
        return s
    return sum_of_digits(sum(int(c) for c in str(s)))
    
> sum_of_digits(2565)
9

It recursively checks if the numerical value is less than 10. If it does, it returns this value.它递归地检查数值是否小于 10。如果是,则返回该值。 If not, it adds the digits, then recursively calls itself on the result.如果不是,则添加数字,然后根据结果递归调用自身。

Edit编辑

To print out the steps as it goes along, you could do something like this:要在执行过程中打印出这些步骤,您可以执行以下操作:

def sum_of_digits(s):
    if s < 10:
        print(s)
        return s
    print(' + '.join(c for c in str(s)) + ' = ')
    return sum_of_digits(sum(int(c) for c in str(s)))

First, initiate an empty string output_str .首先,启动一个空字符串output_str
With a while loop which contniues when our integer is > 9:当我们的整数大于 9 时,while 循环会继续:

  1. [s for s in str(x)] would create a list of the digits (as strings) of our integer. [s for s in str(x)]将创建我们整数的数字(作为字符串)的列表。 It's called a list comprehension , is very useful, and my advice is to read a bit about it.它被称为列表理解,非常有用,我的建议是阅读它。
  2. With " + ".join() we create a string with " + " between the digits.使用" + ".join()我们创建一个在数字之间带有 " + " 的字符串。 Add this string at the end of output_str .output_str的末尾添加此字符串。
  3. Add " = " to the end of output_str ." = "添加到output_str
  4. Calculate the sum of the digits (we cannot use sum(lst_of_digits) because it's a list of strings. sum([int(s) for s in lst_of_digits]) converts the string list into an inter list, which can be summed using sum() ).计算数字的总和(我们不能使用sum(lst_of_digits)因为它是一个字符串列表。 sum([int(s) for s in lst_of_digits])将字符串列表转换为一个 inter 列表,可以使用sum() )。 Store the sum into x .将总和存储到x
  5. Add the new x + " = " to output_string .将新的x + " = "output_string

At the end of the string, we have a redundant " = " (because the last (5) was not needed), let's just remove the last 3 chars ( = ) from it.在字符串的末尾,我们有一个多余的“=”(因为不需要最后一个(5)),让我们从中删除最后三个字符( = )。

x = 2565
output_str = ""
while x > 9:
    lst_of_digits = [s for s in str(x)]
    output_str += " + ".join(lst_of_digits)
    output_str += " = "
    x = sum([int(s) for s in lst_of_digits])
    output_str += f"{x} = "
output_str = output_str[:-3]

outputs:输出:
output_str = '2 + 5 + 6 + 5 = 18 = 1 + 8 = 9'

You can play around with the end keyword argument of the print function which is the last character/string that print will put after all of its arguments are, well, printed, by default is "\\n" but it can be change to your desire.您可以使用print函数的end关键字参数,它是 print 在所有参数都打印之后将放置的最后一个字符/字符串,嗯,打印,默认情况下是"\\n"但它可以根据您的需要进行更改.

And the .join method from string which put the given string between the given list/iterable of strings to get the desire result:和字符串中的.join方法将给定的字符串放在给定的字符串列表/可迭代对象之间以获得所需的结果:

>>> " + ".join("123")
'1 + 2 + 3'
>>> 

Mixing it all together:将它们混合在一起:

def sum_digit(n):
    s = sum(map(int,str(n)))
    print(" + ".join(str(n)),"=",s, end="")
    if s<10:
        print()
        return s
    else:
        print(" = ",end="")
        return sum_digit(s)

Here we first get the sum of the digit on s , and print it as desire, with end="" print will not go to the next line which is necessary for the recursive step, then we check if done, and in that case print a new empty line if not we print an additional = to tie it for the next recursive step在这里,我们首先获取s上数字的总和,并将其打印为期望值,使用end=""打印不会转到递归步骤所需的下一行,然后我们检查是否完成,在这种情况下打印一个新的空行,如果不是我们打印一个额外的=以将其绑定到下一个递归步骤

>>> sum_digit(2565)
2 + 5 + 6 + 5 = 18 = 1 + 8 = 9
9
>>> 

This can be easily be modify to just return the accumulated string by adding an extra argument or to be iterative but I leave those as exercise for the reader :)这可以很容易地修改为通过添加额外的参数或迭代来返回累积的字符串,但我将它们作为练习留给读者:)

I am a noob but this should do what you want.我是一个菜鸟,但这应该做你想做的。

Cheers, Guglielmo干杯,古列尔莫

import math
import sys

def sumdigits(number):

    digits = []
    for i in range( int(math.log10(number)) + 1):
      digits.append(int(number%10))
      number = number/10

    digits.reverse()
    string = ''
    thesum = 0
    for i,x in enumerate(digits):
      string += str(x)
      thesum += x
      if i != len(digits)-1: string += ' + '
      else: string += ' = '

    if thesum > 10:
      return string,thesum,int(math.log10(number))+1
    else:
      return string,thesum,0


def main():

    number = float(sys.argv[1])
    finalstring = ''

    string,thesum,order = sumdigits(number)
    finalstring += string
    finalstring += str(thesum)
    
    while order > 0:
      finalstring += ' = '
      string,thesum,order = sumdigits(thesum)

      finalstring += string
      finalstring += str(thesum)


    print 'myinput = ',int(number)
    print 'Output = ',finalstring

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM