464,820 Members | 856 Online
Need help? Post your question and get tips & solutions from a community of 464,820 IT Pros & Developers. It's quick & easy.

# type conversion problem

 P: 50 hi all, I've just started back up with python after a looong break - it's great to be back :D Anyway, I'm going through "how to think like a computer scientist" as a refresher and trying to come up with a function to return the sum of squares for a given number. I decided to write it as a list comprehension: Expand|Select|Wrap|Line Numbers sum(int(i)**2 for i in str(x))   I think I read somewhere that type conversion in python was costly? Is there a better way to do this? Thanks Jul 20 '08 #1
5 Replies

 Expert Mod 2.5K+ P: 2,851 hi all, I've just started back up with python after a looong break - it's great to be back :D Anyway, I'm going through "how to think like a computer scientist" as a refresher and trying to come up with a function to return the sum of squares for a given number. I decided to write it as a list comprehension: Expand|Select|Wrap|Line Numbers sum(int(i)**2 for i in str(x))   I think I read somewhere that type conversion in python was costly? Is there a better way to do this? Thanks I don't understand how you could sum the squares of a number. You can sum the squares of 2 numbers though. Why do you need to convert anything? What is 'x'? Expand|Select|Wrap|Line Numbers >>> def sum_squares(x,y): ...     return sum([num**2 for num in [x,y]]) ...  >>> sum_squares(3,4) 25 Why go to all the trouble of a list comprehension or generator? Expand|Select|Wrap|Line Numbers >>> def sum_squares(x,y): ...     return x**2+y**2 ...  >>> sum_squares(5,6) 61 >>>  Jul 20 '08 #2

 P: 50 thanks for the reply I'm summing the squares of elements in a list Expand|Select|Wrap|Line Numbers x=[1, 2, 3]   # I would expect 14 as a result   cheers Jul 21 '08 #3

 100+ P: 314 Expand|Select|Wrap|Line Numbers >>> x = [1,2,3] >>> sum( [ i**2 for i in x ] ) 14 >>>    Why the type conversion? Jul 21 '08 #4

 P: 50 Expand|Select|Wrap|Line Numbers >>> x = [1,2,3] >>> sum( [ i**2 for i in x ] ) 14 >>>    Why the type conversion? sorry I gave the wrong info x=1234 Jul 21 '08 #5

 Expert Mod 2.5K+ P: 2,851 This is kind of screwy. Here's a couple of ways. One uses no conversion and the other converts once. Expand|Select|Wrap|Line Numbers def sum_squares_int(num):     num_list = []     while num > 0:         num_list.append(num%10)         num /= 10     return sum([i**2 for i in num_list])   def sum_squares_int1(num):     return sum([(num/10**i%10)**2 for i in range(len(str(num)))]) Jul 21 '08 #6