George G.
George G.

Reputation: 155

usage of str() to convert number in int() in Python

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)))

Upvotes: 3

Views: 160

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

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

Upvotes: 3

Adam Smith
Adam Smith

Reputation: 54163

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)

Upvotes: 2

Related Questions