Maybe a stupid idea

Michael Geary Mike at DeleteThis.Geary.com
Wed Dec 31 14:16:46 EST 2003


Hi Sebb,

Your idea is not stupid at all, and your English is very good. :-)

I don't know how much luck you would have getting this built into the core
language, but fortunately you don't really need to. It is very easy to add
it yourself. Here are a couple of ways you could do it.

The easiest would be something like this, a function that returns a list
containing your cycle of values. Note that "first" is the first and last
value in the list, and "limit" is one more than the largest value in the
list. I did it this way to be consistent with Python's range function.

def cycle( first, limit ):
    "Return list of values from first up to limit-1 and down to first."
    return range( first, limit ) + range( limit - 2, first - 1, -1 )

print cycle( 1, 5 )  # print the list itself

for b in cycle( 1, 5 ):
    print "*" * b

Another approach would use a generator (a function that returns a series of
values by using a yield statement):

def cycle( first, limit ):
    "Return series of values from first up to limit-1 and down to first."
    for value in xrange( first, limit ):
        yield value
    for value in xrange( limit - 2, first - 1, -1 ):
        yield value

for b in cycle( 1, 5 ):
    print "*" * b

This approach doesn't construct and return the actual list of values as the
first one does (that's why I didn't put the "print cycle( 1, 5 )" statement
in this test). It calculates and returns the values on the fly. This would
use less memory for a very long cycle, but it's not quite as simple as the
first approach. Both techniques are useful to know about.

Hope that helps!

-Mike

sebb wrote:
> I'm kind of newbie to programming, but I thought of
> something and I want some opinions on that.
>
> It's about a new instruction block to do some cycles.
>
> I thought about that because it's not very easy to
> program a cycle. Here is a simple example :
>
> b=0
>
> while b < 50:
>     b+=1
>     print "*" * b
>
> while b > 0:
>     b-= 1
>     print "*" * b
>
> It takes two while blocks to do a cycle.
>
> I know that cycles is not a structure of any programming
> language, but I want some opinions the know if my idea
> is stupid or not.
>
> If the idea is not so stupid, python may be the first language
> to have a completely new structure block :-)
>
> Note : English is not my mother tongue so the message can
> have mistakes.






More information about the Python-list mailing list