[Tutor] Squaring every digit in number

Alan Gauld alan.gauld at btinternet.com
Sat Nov 21 14:30:22 EST 2015


On 21/11/15 12:05, Aadesh Shrestha wrote:

> is there a better solution than this which requires less code?

Yes, several. But less lines of code is not necessarily better.
it might take more memory, or run slower. So better is a relative term 
and you always need to think about what you mean by better.

That having been said...

> def square_digits(num):
>      arr = []
>      list  = []

Never use the name of a built in type as a variable name.
You will lose the ability to access the original type name.

>      while(num !=0):
>          temp = num%10
>          num = num /10

You can use the divmod() function to combine these two lines:

            num,temp = divmod(num,10)


>          arr.insert(0, temp)
>      for i in arr:

Rather than inserting each digit into the array then looping
over the array squaring everything, why not insert the
squared number directly into the array and avoid the
second loop?

>          list.append( i*i)
>      str1 = ''.join(str(e) for e in list)
>      return int(str1)

I assume this does what you want? For example if num is 47
The return value is 1649.

If so you could again save a step by converting the square into a string 
before inserting into the array:

             arr.insert(0, str(temp**2))
       return int(''.join(arr) )

So the final code would be:

def square_digits(num):
     arr = []
     while(num !=0):
         num,temp = divmod(num,10)
         arr.insert(0, str(temp**2))
     return int(''.join(arr))


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list