简体   繁体   English

Python 程序使用递归 function 求数字平方和

[英]Python program to find sum of squares of digits using a recursive function

I want to make a function that gets the sum of the squares of its each digits.我想做一个 function 得到每个数字的平方和。 Although, I have seen some solutions in the internet, the one I have seen is "getting the sum of the squares of its digits" but given a list.虽然,我在互联网上看到了一些解决方案,但我看到的是“得到其数字的平方和”,但给出了一个列表。 For example, instead of starting at the integer 133, they use [1,3,3] as an input.例如,他们不是从 integer 133 开始,而是使用 [1,3,3] 作为输入。 I tested this function and it works great, but I want to use an integer as an input and not a list.我测试了这个 function 并且效果很好,但我想使用 integer 作为输入而不是列表。

Edit: For example the given is 123. So the function must return 14. (1^2 + 2^2 + 3^2)编辑:例如给定的是 123。所以 function 必须返回 14。 (1^2 + 2^2 + 3^2)

My idea is:我的想法是:

    def squarer(x):                           # where x is an integer (not a list)
        # <insert a recursive formula>
        # return the sum

One simple way to make a recursive function is, to always square the first digit and then call the same function with the remaining digits.制作递归 function 的一种简单方法是始终将第一个数字平方,然后用剩余的数字调用相同的 function。

def squarer(x: int) -> int:
    if x < 10:  # trivial case, when x has only one digit
        return x**2
    first_digit = int(str(x)[0])  # extract the first digit
    return first_digit**2 + squarer(int(str(x)[1:]))  # recursive call

Here, I used the functions int() and str() to always access the individual digits and cast the the variable back to an integer.在这里,我使用函数int()str()始终访问单个数字并将变量转换回 integer。

You can use an integer as an input and transform it into a list.您可以使用 integer 作为输入并将其转换为列表。

arr  = [int(x) for x in input("Enter a number: ")]

and then you pass your list into your function.然后你将你的列表传递给你的 function。

def squarer(arr):                           # where arr is a list
        # <insert a recursive formula>
        # return the sum

Try to convert your number to string so you can iterate by each digit.尝试将您的数字转换为字符串,以便您可以按每个数字进行迭代。 And after you can convert string to list or just convert each digit to int before you apply other logic在您可以将字符串转换为list之后,或者在应用其他逻辑之前将每个数字转换为int

If I understood the question correctly, this code should solve your problem如果我正确理解了这个问题,这段代码应该可以解决您的问题

It is not of the highest quality but it works:)它不是最高质量的,但它有效:)

def sq(x):

    sum = 0
    while x > 0:
        y = x/10
        r = y*10
        r = x-r
        r = r*r
        sum = sum+r
        x = y

    return sum


print(sq(12))

Recursive and without any transformations:递归且没有任何转换:

def squarer(n):
    if n <= 0:
        return 0
    rest, first_digit = divmod(n, 10)
    return first_digit**2 + squarer(rest)

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

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