Newbie - 1st Program

Alex Martelli aleax at aleax.it
Mon Nov 10 05:20:46 EST 2003


Mark Smith wrote:
   ...
> It seems to work - great - but how would you make this more 'elegant' -
> I'm sure it's horrible to an experienced hacker...

Not half bad, actually!  I would suggest one improvement: avoid floating
point when you don't need it.  In this case:

> totalPorts = float(inputPorts) + float(outputPorts)
   ...
> crossConnects = (totalPorts / 2) * (totalPorts - 1)

you probably inserted the float() calls when you found out that the
crossConnects computation got truncated when totalPorts was an odd
integer.  But that's just because you're specifying the computations
in the wrong order there.  Try, instead:

totalPorts = inputPorts + outputPorts

crossConnects = (totalPorts * (totalPorts - 1)) / 2

The product "totalPorts * (totalPorts - 1)" is guaranteed to be even
for any integer totalPorts, therefore you don't need to worry about
truncation when you divide it by two.


Incidentally, I'm not sure about your "connection routes" count --
it seems to include the possibility of connecting two output ports
to each other, etc.  I guess that may or may not make sense,
electrically and logically, depending on your setup.  When a valid
"connect" is just between one output port and one input port, of
course, the number of possible connects is inputPorts*outputPorts.

But this isn't really about Python programming (or any other kind
of programming), of course -- except in that it reminds us that no
matter how well we code, first and foremost we must ensure we're
computing what we really WANT to compute -- and that comments exist
to reassure readers and maintainers of the code that we have taken
this into account (e.g., some note in the leading comment about the
possibility of connecting two "egress ports" directly to each
other would have reassured me, as a reader of the code, that the
computation being performed is indeed correct).


Alex





More information about the Python-list mailing list