Abhinav Pipil
Abhinav Pipil

Reputation: 25

I want to find the sum of squares of digits in a number, my code work fine for positive numbers but doesn't seem to work with negative numbers

N=int(input('enter a number'))
sum=0
for digit in str(N):
            sum=sum+(int(digit))**2
print(sum) 

This code works totally fine with positive numbers but How do I make it work for negative numbers too?

Upvotes: 2

Views: 1494

Answers (3)

Timur Shtatland
Timur Shtatland

Reputation: 12425

Use re.findall to find digits:

import re
num = int(input('Enter a number: '))
sum = 0
for digit in re.findall(r'\d', str(num)):
    sum = sum + (int(digit))**2
print(sum)

You can also use a more compact and more Pythonic list comprehension:

sum_sq = sum([int(i)**2 for i in re.findall(r'\d', str(num))])

Finally, the initial conversion of the input to int and subsequent casting of it back to str is not needed. Putting it all together:

import re
num = input('Enter a number: ')
sum_sq = sum([int(i)**2 for i in re.findall(r'\d', num)])
print(sum_sq)

Upvotes: 1

Barmar
Barmar

Reputation: 782166

Convert the input to positive with abs().

N=abs(int(input('enter a number')))
total=0
for digit in str(N):
    total=total+(int(digit))**2
print(total) 

Upvotes: 1

Pac0
Pac0

Reputation: 23174

You could skip characters that are not digits.

N = input('enter a number')
total = 0
for digit in [int(d) for d in N if d.isdigit()]:
    total = total + digit**2
print(total) 

(note: I also removed the unnecessary conversion of the input at the beginning, but maybe you want an error to be raised if it is not a whole number. In this case, just put it back and replace N in the list comprehension by str(N))

Upvotes: 0

Related Questions