Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify this python code

Tags:

python

I've written a program to check if my thought about solution on paper is right (and it is).

The task: how many zeros is in the back of multiplication of all numbers from 10 to 200.

It is 48 and it is a simple to calculate manually.

I never write on python seriously and this is what I get:

mul = 1
for i in range(10, 200 + 1):
    mul *= i

string = str(mul)
string = string[::-1]
count = 0;
for c in str(string):
    if c == '0':
        count += 1
    else:
        break

print count
print mul

I bet it is possible to write the same more elegant in such language like a python.

ps: yes, it is a homework, but not mine - i just helped a guy ;-)

like image 912
zerkms Avatar asked Oct 26 '10 23:10

zerkms


3 Answers

A straight-forward implementation that doesn't involve calculating the factorial (so that it works with big numbers, ie 2000000!) (edited):

fives = 0
twos = 0
for i in range(10, 201):
   while i % 5 == 0:
      fives = fives + 1
      i /= 5
   while i % 2 == 0:
      twos = twos + 1
      i /= 2
print(min(fives, twos))
like image 123
irrelephant Avatar answered Nov 07 '22 10:11

irrelephant


import math

answer = str(math.factorial(200) / math.factorial(9))
count = len(answer) - len(answer.rstrip('0'))
  1. Import the math library
  2. Calculate the factorial of 200 and take away the first 9 numbers
  3. Strip away zeros from the right and find out the difference in lengths
like image 6
Brian McKenna Avatar answered Nov 07 '22 10:11

Brian McKenna


print sum(1 + (not i%25) + (not i%125) for i in xrange(10,201,5))
like image 4
Robert William Hanks Avatar answered Nov 07 '22 10:11

Robert William Hanks