Search code examples
pythonpercentagefractionsfactors

Python Percentage-complete calculator


EDITZ: I've figured it out. :) All I had to do was add a .0 to the end of the 100 (and add an int() statement as well). :P Yay for float/decimals!

I'm making a factor calculator. It works perfectly. Here's a sample output of the code:

Get factors of {10}

[1, 2, 5, 10]

Get factors of {120}

[1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120]

and so on (you input the text within the curly braces ( { } )). It's made in Python 2.7. In order to make it 110% perfect (better than before :P), I want it to display the amount that's been calculated.. while my computer is really quick and can calculate the factors of 120 near instantaneously, if I input a big number like 5000 it takes about 30 seconds to calculate. A little long (This is because it's calculating 25 million equations). It'd be nice if it displayed a percentage finished right at the bottom of the screen so that you would know about how long is left.

So my code (which I'll show you shortly) will output this when you input 5 as the number.

Get factors of 5 Calculation completed: 20% Calculation completed: 40% Calculation completed: 60% Calculation completed: 80% [1, 5]

(I dunno why it doesn't show 100%, I can easily add that in though so don't worry.) Okay, so it's working well. Great! Now I get this one problem..

Get factors of 101

Calculation completed: 0%

Calculation completed: 0%

Calculation completed: 0%

Calculation completed: 0%

Calculation completed: 0%

Calculation completed: 0%


Calculation completed: 0%

Calculation completed: 0%

Calculation completed: 0%

[1, 101]

That is quite obviously a problem. It only works if you input a number equal to or less than 100, and sense 100 calculates near-instantly, that's kinda pointless. :P

At this point it's probably a good time to show my code:

def getFactors(n):
    out = [1]
    for i in range(1, n):
        for j in range(1, n):
            if (i * j == n):
                out.append(i)
        print "Calculation completed: " + str(100 / n * i ) + "%"
    out.append(n)
    return out

while(0 < 1):
    number = int(raw_input("Get factors of "))
    print getFactors(number)
    print ""

Main part to focus on: the first print function. :P

Any clues why it doesn't work? Thanks a lot if you can help. :)


Solution

  • By default Python 2 performs calculation on integer arithmetics if all operands are integers.

            print "Calculation completed: " + str(100. / n * i ) + "%"
            #                                        ^
            #                      the "dot" here force calculation
            #                      using floating point values
    

    An alternative, as suggested by Padraic Cunningham is to add this import to your source file:

    from __future__ import division
    

    It makes division in Python 2 behaves like in Python 3 (see PEP-238 for details)