3

Can someone explain me why should I first convert a number to string in order to convert it after that to integer. Here is the code for example:

print sum(int(number) for number in str(__import__('math').factorial(520)))
Mazdak
  • 105,000
  • 18
  • 159
  • 188
George G.
  • 155
  • 1
  • 4
  • 13
  • 1
    So do you want to compute `520!` or the sum of the digits in `520!`? – MrHug Dec 15 '15 at 10:27
  • I just want to know the reason i have to convert number such as (520) and each of containing it numbers to string in order to convert them back to int right after. – George G. Dec 15 '15 at 10:34
  • Well my point is that if you want to calculate `520!` then this is not the way to go. If you want to calculate the sum of the digits, then this is ;) Take for instance `6!`. Do you want the algorithm to output `720` or `7+2+0 = 9`? – MrHug Dec 15 '15 at 10:41
  • I have separate script for calculating the cumulative sum of all digits. I just pick this script because it illustrate my str() question, which you cleared for me, thank you! – George G. Dec 15 '15 at 10:46

2 Answers2

3

Because the code sums the digits of factorial result. In order to access each digit it converted the number to string and looped over the digit characters and then converted them to int.

>>> __import__('math').factorial(10)
3628800
>>> sum(int(number) for number in str(__import__('math').factorial(10)))
27 # == 3 + 6 + 2 + 8 + 8

There is another way to access digits of a number and that is dividing by 10 and saving the remainder. In that case you don't have to convert the number to string and then string digits to int.

def sum_digits(number):
    reminder = 0
    while number:
        reminder += number%10
        number = number/10
    return reminder

num = __import__('math').factorial(10)
print(sum_digits(num))
27
Omid
  • 2,617
  • 4
  • 28
  • 43
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • so every time when i need to access each item to be summed or for something else, it needs to become str first? P.S. I can't accept the answer in first 4 min. so I will accept it after few min, thank you – George G. Dec 15 '15 at 10:30
  • @GeorgeG. Actually you are converting the number to string. Compare with another way. – Mazdak Dec 15 '15 at 10:34
  • yes, I am first converting a number to string, and after that i am converting a string to an int, which is the part that confuse me – George G. Dec 15 '15 at 10:35
  • @GeorgeG.: you are converting the number to a string, iterating over all the digits of the string, and then converting each digit to an int. – Andrea Corbellini Dec 15 '15 at 10:38
2

Because you're iterating over each character in the string. If you unroll it from the generator comp it's easy to tell

sum_ = 0
for number in str(math.factorial(520)):
    sum_ += int(number)
Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
Adam Smith
  • 52,157
  • 12
  • 73
  • 112