[Tutor] Squaring every digit in number

Joel Goldstick joel.goldstick at gmail.com
Sat Nov 21 11:38:43 EST 2015


On Sat, Nov 21, 2015 at 10:06 AM, Laura Creighton <lac at openend.se> wrote:

> In a message of Sat, 21 Nov 2015 17:50:49 +0545, Aadesh Shrestha writes:
> >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
>
> Read up on list comprehensions:
> https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
>
> Have fun!
>
> Laura
>

This method converts the number to a string, walks thru the string and
converts to the squares.
>>> num = 123
>>> d_squared = ""
>>> for d in str(num):
...   d_squared += str(int(d)**2)
...
>>> d_squared
'149'
>>> int(d_squared)
>>>
149



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



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays


More information about the Tutor mailing list