[Tutor] Is there an easily or shorter way?
davea at davea.name
Mon Dec 15 23:59:11 CET 2014
On 12/15/2014 04:25 PM, Ken G. wrote:
> I am sure there is a better way to refine the following lines.
> Letting x equal a number from 1 to 28, go through 28 separate 'if'
> statements to print a resulting value that equaled the value of x.
> For example:
> x = 8
> if x = 1, print 'one'
> if x = 2, print 'two'
> if x = 8, print 'eight'
> if x = 28, print 'twenty eight'
> Would a single line using list or dictionary be shorter?
If this is an assignment, and you quoted it correctly, then you're
required to go through 28 if statements. On the other hand, if that
paragraph is just a description of the way you solved it, then yes, it
can be improved. Just making all but the first if statement an elif
will make it faster, because once it finds a value, it won't continue
checking the remaining ones.
Still faster would be testing first for fourteen, and making a tree out
of the if statements, using > and < comparisons instead of only ==
comparisons. Worst case would be about 5 tests. This would not be more
compact, just quicker to execute.
Faster yet, and somewhat more compact would be to make a tuple or list
of 29 items (0 through 28), and just index into it.
Slower, but more compact, would be to write the kind of library that
Danny pointed you to, or the code that Ken/Bod alluded to.
But the real question is what's your goal. Your original code isn't
legal Python, so you're presumably in a learning mode. If so, you want
to keep it simple, not use 3rd party libraries for something you could
do yourself. And when you're given an assignment, you should do it
exactly the way they want it, and only after that's correct (and
running), do it also in other ways. Those other ways could be to
improve performance, reduce size, make it more readable (or less, to
enter it in obfuscation contests), to make it independent of any loaded
libraries, to look like some sample in another language, ...
My second suggestion, untested:
if x < 14:
if x < 7:
if x < 3:
if x == 1:
elif x < 5:
if x == 3:
More information about the Tutor