Newbie help looping/reducing code
Cameron Laird
claird at lairds.us
Mon Feb 19 20:37:40 EST 2007
In article <7x1wkl8xb7.fsf at ruckus.brouhaha.com>,
Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>Lance Hoffmeyer <lance at augustmail.com> writes:
>> def even_odd_round(num):
>> if(round(num,2) + .5 == int(round(num,2)) + 1):
>> if num > .5:
>> if(int(num) % 2):
>> num = round(num,2) + .1 #an odd number
>> else:
>> num = round(num,2) - .1 #an even number
>> else:
>> num = 1
>> rounded_num = int(round(num,0))
>> return rounded_num
>
>I would also rewrite this function. It's quite hard to figure out
>what it's intended to do. At minimum it should be carefully
.
.
.
>def even_odd_round(num):
> assert num >= 0
>
> # separate the number's integer and fractional parts
> intpart, fracpart = int(num), num % 1.0
>
> # decide what to do based on the fractional part
> if fracpart < 0.495:
> return intpart # round downward
> elif fracpart > 0.505 or intpart==0:
> return intpart+1 # round upward
> else:
> return intpart + intpart % 2 # round to even
I have even less idea than Paul what the true intent of even_odd_round()
is. I offer, though, the general observation that it's VERY often possible
to do what people want in this sort of regard with a simple use of
formatting--something like
"%.3f" % num
If one comes from C or Java, it can be hard to appreciate immediately how
useful this is. It's also likely to be more robust than anything naively
written "by hand".
More information about the Python-list
mailing list