I want to make a function that gets the sum of the squares of its each digits. 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. I tested this function and it works great, but I want to use an integer as an input and not a list.
Edit: For example the given is 123. So the function must return 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
CodePudding user response:
You can use an integer as an input and transform it into a list.
arr = [int(x) for x in input("Enter a number: ")]
and then you pass your list into your function.
def squarer(arr): # where arr is a list
# <insert a recursive formula>
# return the sum
CodePudding user response:
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
CodePudding user response:
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.
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.
CodePudding user response:
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))
CodePudding user response:
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)