[Tutor] trivial simple program..can it be made more concise?
Steven D'Aprano
steve at pearwood.info
Sat Feb 14 10:07:02 CET 2015
On Sat, Feb 14, 2015 at 03:17:28AM +0000, steve10brink at comcast.net wrote:
> Hi all,
>
> I was playing with Python tonight and created a simple program that
> outputs numbers counting up then counting down all on the same
> terminal line. The code is as follows:
>
> #------------------------------------------------------------
> a = 320000 #number to count up to
>
> for i in range (a):
> print i, '\r',
>
> for i in range ((a-1),0,-1):
> print i, '\r',
>
> #------------------------------------------------------------
>
> It works as desired. However, I was trying to figure out a way to make
> it more concise but cannot see a way since the 'range' parameters must
> be integers (no functions allowed?).
Parameters to range can be anything which evaluates to integers, but
I'm not sure how that will help you. Also, in Python 2 xrange is a
little more efficient than range.
How's this?
a = 320000
counts = (xrange(a), xrange(a-1, 0, -1))
for counter in counts:
for i in counter:
print i, '\r'
BUT I'm not sure why you are worried about making it more concise when
your code doesn't do what you want, as far as I can tell. You want the
counter to be written on the same line, not 640 thousand lines, but when
I try it, I get each number written to a different line.
Try this instead:
import sys
a = 320000
counts = (xrange(a), xrange(a-1, 0, -1))
for counter in counts:
for i in counter:
sys.stdout.write(str(i) + '\r')
sys.stdout.flush()
--
Steve
More information about the Tutor
mailing list