![]() |
Arithmetic By Percentage
Let's say i want to perform a subtraction on a variable (say, Energy) by 5%, the shortest way i can think of is:
:
Tolerance = 0.05 * Energy:
Energy = Energy - 0.05*(Energy) |
I think the shortest you could get would be:
:
energy -= 0.05 * energy:
energy *= 0.95 |
I was hoping there's something like:
Gone = energy * 50% |
If I'm understanding you right .....
:
gone = energy*percentage; |
Quote:
:
def pc(x): return x / 100.0:
pc = 0.01 |
A Percent class for doing percentage arithmetic
Python's ability to emulate numeric types makes it easy to "extend" Python with some interesting behavior. Here's a Percent class that allows you to write code like: saleprice = origprice - discount, where origprice is a number, and discount is a class instance that computes the actual discount based on the value of origprice.
You could do the same thing with a variable called markup as in markup=Percent(10) and then compute retailprice = wholesaleprice + markup. -- Paul :
class Percent(object)::
20% |
Very short.
|
Well, once you get the class junk out of the way, I'd say this is pretty short/elegant, certainly more along the lines of what the OP was looking for.
:
discount = Percent(20)Percent is more than just a fancy wrapper around "divide by 100". Note that discount can be subtracted from any number of other values, and it will calculate the respective percentage before returning the value. Are you the curmudgeon-in-residence on these forums? :) -- Paul |
If it makes me a curmudgeon to point out when you're being silly, yes, indeed. The OP distinctly asked for a short way. Merely hiding things so that they aren't visible at the point of invocation doesn't qualify as either short or elegant.
|
Isn't the point of invocation what matters? Or at least what matters in this case.
|
| All times are GMT -5. The time now is 1:57 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC