On 11/21/2015 7:05 AM, 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)



************************
Aadesh Shrestha
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
"Better" is somewhat subjective, but "less code" is not so much so:

def square_digits(num):
    try:
        return int(''.join((str(int(n)**2) for n in str(int(num)))))
    except ValueError:
        return 0

The "str(int(num))" could be shortened to "str(num)", also, but I liked being able to accept any argument that could be converted to an int, and also raising the ValueError before looping .

Have fun at codewars

Nathan Hilterbrand


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to