[Tutor] Squaring every digit in number

Peter Otten __peter__ at web.de
Sat Nov 21 15:49:46 EST 2015


Aadesh Shrestha wrote:

> I am currently taking challenges on codewars.
> Problem: Square Every Digit
> 
> is there a better solution than this which requires less code?
> 
> def square_digits(num):
>     arr = []
>     list  = []
>     while(num !=0):
>         temp = num%10
>         num = num /10
>         arr.insert(0, temp)
>     for i in arr:
> 
>         list.append( i*i)
>     str1 = ''.join(str(e) for e in list)
>     return int(str1)

Here's one which moves most of the code out of the function:

# Python 2
TRANS = {ord("0") + digit: unicode(digit*digit) for digit in range(10)}

def square_digits(num):
    return unicode(num).translate(TRANS)

Negative numbers keep their leading "-" sign.
Replace unicode with str for the Python 3 version.




More information about the Tutor mailing list