for loop

2004-12-12 Thread houbahop
Hello,
I have seen a lot of way to use the for statement, but I still don't know 
how to do:

for i=morethanzero to n
or
for i= 5 to len(var)

of course I kno wthat I can use a while loop to achieve that but if this is 
possible whith a for one, my preference goes to the for.

regards,
Dominique. 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread Diez B. Roggisch
> for i in range(morethanzero, n):
>  ...
> 
>> for i= 5 to len(var)
> 
> for i in range(5, len(var)):
>  ...

Better use xrange - it doesn't create an actual list, but instead an
iterator enumerating the elements. That way more memory and cpu efficient.
-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread Steven Bethard
houbahop wrote:
for i=morethanzero to n
for i in range(morethanzero, n):
...
for i= 5 to len(var)
for i in range(5, len(var)):
...
although range(len(var)) is usually not what you want, because you can 
just do:

for item in itertools.islice(var, 5, None):
...
or if you really do need the index too:
for i, item in itertools.islice(enumerate(var), 5, None):
...
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread loritsch
houbahop wrote:
> Hello,
> I have seen a lot of way to use the for statement, but I still don't
know
> how to do:
>
> for i=morethanzero to n
> or
> for i= 5 to len(var)
>
> of course I kno wthat I can use a while loop to achieve that but if
this is
> possible whith a for one, my preference goes to the for.
>
> regards,
> Dominique.

I think the key point that hasn't been made here is what a for
statement is really doing in python...

>From the online documentation:

"The for statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object"

Neither of the statements:
> for i=morethanzero to n
> for i= 5 to len(var)
create a sequence or iterable object, and that is why they don't work.

That is why previous posts in this thread have suggested using range(),
xrange(), etc.  Because they create a sequence or iterable object.
When first using python, I recall that this distinction was not clear
to me, as I was used  to a more traditional for statement (as in
C/C++):

for ( initialise ; test ; update )

Essentially, python's for statement is more like a foreach statement in
many other languages (Perl, C#, etc).  These statements essentially
reduce the traditional form above to what many consider a more readable
form:

foreach item in collection:

In order to transform the tradition for statement into this more
readable form, each language requires that their collections being
iterated over satisfy a precondition defined by the language (in python
this precondition is that the collection is iterable).

While this restriction may seem a little strange to people who are used
to the more traditional for statement form, the result of this approach
is often a more readable and clear statement.
Regards,

Michael Loritsch

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread Steven Bethard
Diez B. Roggisch wrote:
for i in range(5, len(var)):
...
Better use xrange - it doesn't create an actual list, but instead an
iterator enumerating the elements. That way more memory and cpu efficient.
I could've sworn I read somewhere in the past that xrange was supposed 
to be slower than range in some situation, but at least for some simple 
cases in Python 2.4, it seems to be about as fast or faster:

> python -m timeit "for i in range(100): a = i*2"
1 loops, best of 3: 21.8 usec per loop
> python -m timeit "for i in xrange(100): a = i*2"
1 loops, best of 3: 19.4 usec per loop
> python -m timeit "for i in range(1): a = i*2"
100 loops, best of 3: 2.18 msec per loop
> python -m timeit "for i in xrange(1): a = i*2"
100 loops, best of 3: 2.29 msec per loop
> python -m timeit "for i in range(10): a = i*2"
10 loops, best of 3: 25.5 msec per loop
> python -m timeit "for i in xrange(10): a = i*2"
10 loops, best of 3: 20.7 msec per loop
I hardly ever use (x)range for anything (because you can almost always 
use a for loop to loop over items instead), but I'll file this info away 
mentally for the next time I do.  Thanks!

Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread houbahop
thank you,
Whith python, It seems that all that I have learn in other languages is not 
directly usable :) but looks like python is more efficient.
dominique.

<[EMAIL PROTECTED]> a écrit dans le message de news: 
[EMAIL PROTECTED]
> houbahop wrote:
>> Hello,
>> I have seen a lot of way to use the for statement, but I still don't
> know
>> how to do:
>>
>> for i=morethanzero to n
>> or
>> for i= 5 to len(var)
>>
>> of course I kno wthat I can use a while loop to achieve that but if
> this is
>> possible whith a for one, my preference goes to the for.
>>
>> regards,
>> Dominique.
>
> I think the key point that hasn't been made here is what a for
> statement is really doing in python...
>
>>From the online documentation:
>
> "The for statement is used to iterate over the elements of a sequence
> (such as a string, tuple or list) or other iterable object"
>
> Neither of the statements:
>> for i=morethanzero to n
>> for i= 5 to len(var)
> create a sequence or iterable object, and that is why they don't work.
>
> That is why previous posts in this thread have suggested using range(),
> xrange(), etc.  Because they create a sequence or iterable object.
> When first using python, I recall that this distinction was not clear
> to me, as I was used  to a more traditional for statement (as in
> C/C++):
>
> for ( initialise ; test ; update )
>
> Essentially, python's for statement is more like a foreach statement in
> many other languages (Perl, C#, etc).  These statements essentially
> reduce the traditional form above to what many consider a more readable
> form:
>
> foreach item in collection:
>
> In order to transform the tradition for statement into this more
> readable form, each language requires that their collections being
> iterated over satisfy a precondition defined by the language (in python
> this precondition is that the collection is iterable).
>
> While this restriction may seem a little strange to people who are used
> to the more traditional for statement form, the result of this approach
> is often a more readable and clear statement.
> Regards,
>
> Michael Loritsch
> 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread Diez B. Roggisch
> I hardly ever use (x)range for anything (because you can almost always
> use a for loop to loop over items instead), but I'll file this info away
> mentally for the next time I do.  Thanks!

Thats true for me too - and since enumerate was introduced, the number of
applications of xrange have decreased further.


-- 
Regards,

Diez B. Roggisch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop

2004-12-12 Thread Binu K S
If you are used to the C kind of for loops, avoid mistakes like this one:

>>> for i in range(1,6):
... print i
... i+=2
... 
1
2
3
4
5

Obvious if you know you are iterating over a sequence.
-- 
http://mail.python.org/mailman/listinfo/python-list


Threaded for loop

2007-01-13 Thread John

I want to do something like this:

for i = 1 in range(0,N):
 for j = 1 in range(0,N):
   D[i][j] = calculate(i,j)

I would like to now do this using a fixed number of threads, say 10
threads.
What is the easiest way to do the "parfor" in python?

Thanks in advance for your help,
--j

-- 
http://mail.python.org/mailman/listinfo/python-list


for loop question

2006-07-06 Thread bruce
hi..

basic foor/loop question..

i can do:

 for a in foo
  print a

if i want to do something like
  for a, 2, foo
print foo

where go from 2, to foo..

i can't figure out how to accomplish this... 

can someone point me to how/where this is demonstrated...

found plenty of google for for/loop.. just not this issue..

thanks

-bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


For loop extended syntax

2005-03-20 Thread George Sakkis
I'm sure there must have been a past thread about this topic but I don't know 
how to find it: How
about extending the "for  in" syntax so that X can include default arguments 
? This would be very
useful for list/generator comprehensions, for example being able to write 
something like:

[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]

instead of the less elegant explicit loop version that has to check for the 
length of each sequence.
What do you think ?

George


-- 
http://mail.python.org/mailman/listinfo/python-list


strange for loop construct

2007-01-05 Thread Sardaukary
I was googling for an example of the classic word frequency program in
Python as I'm just learning the language, and wanted to see how other
people implemented it.

I found this blog post
http://digitalhistory.uwo.ca/dhh/index.php/2006/08/20/easy-pieces-in-python-word-frequencies/
(with a much more concise version than I managed) but I can't seem to
find any mention in various Python documentation of the following
construct

wordfreq = [wordlist.count(p) for p in wordlist]

I would expect

for p in wordlist:
wordfreq.append(wordlist.count(p))


I didn't know you could have an expression in the same line.

-- 
http://mail.python.org/mailman/listinfo/python-list


Explanation about for loop

2007-01-11 Thread raghu
can any one help me explaining for loop and its execution and its
syntax with a simple example.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread skip

John> I want to do something like this:

John> for i = 1 in range(0,N):
John>  for j = 1 in range(0,N):
John>D[i][j] = calculate(i,j)

John> I would like to now do this using a fixed number of threads, say
John> 10 threads.  What is the easiest way to do the "parfor" in python?

I'd create a queue containing 10 tokens.  Pull a token off the queue, invoke
the thread with the parameters for its chunk, have it compute its bit, lock
D, update it, unlock it, then return the token to the token queue. Sketching
(and completely untested):

# Calculate one row of D
def calcrow(i, N, token, Tqueue, Dqueue):
d = [0.0] * N
for j in range(N):
d[j] = calculate(i, j)
D = Dqueue.get()
D[i][:] = d
Dqueue.put(D)
Tqueue.put(token)

# This queue limits the number of simultaneous threads
Tqueue = Queue.Queue()
for i in range(10):
Tqueue.put(i)

# This queue guards the shared matrix, D
Dqueue = Queue.Queue()
D = []
for i in range(N):
D.append([0.0] * N)
Dqueue.put(D)

for i in range(N):
token = Tqueue.get()
t = threading.Thread(target=calcrow, args=(i, N, token, Tqueue,
   Dqueue))
t.start()

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread Paul Rubin
"John" <[EMAIL PROTECTED]> writes:
> I want to do something like this:
> 
> for i = 1 in range(0,N):
>  for j = 1 in range(0,N):
>D[i][j] = calculate(i,j)
> 
> I would like to now do this using a fixed number of threads, say 10
> threads. What is the easiest way to do the "parfor" in python?

It won't help in terms of actual parallelism.  Python only lets one
thread run at a time, even on a multi-cpu computer.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread Carl Banks

Dennis Lee Bieber wrote:
> On 13 Jan 2007 12:15:44 -0800, "John" <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
>
> >
> > I want to do something like this:
> >
> > for i = 1 in range(0,N):
> >  for j = 1 in range(0,N):
> >D[i][j] = calculate(i,j)
> >
> > I would like to now do this using a fixed number of threads, say 10
> > threads.
> > What is the easiest way to do the "parfor" in python?
> >
> > Thanks in advance for your help,
> > --j
>
>   Don't know if it's the easiest -- and if "calculate" is a CPU-bound
> number cruncher with no I/O or other OS-blocking calls, it won't be
> faster either as the GIL will only let one run at a time, even on
> multi-core processors.

It could still be helpful if you'd like to get as much done as possible
in as short a time as possible, and you suspect that one or two cases
are likely to hold everything up.


Carl Banks

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread parallelpython
John wrote:
> I want to do something like this:
>
> for i = 1 in range(0,N):
>  for j = 1 in range(0,N):
>D[i][j] = calculate(i,j)
>
> I would like to now do this using a fixed number of threads, say 10
> threads.
> What is the easiest way to do the "parfor" in python?
>
> Thanks in advance for your help,

As it was already mentioned before threads will not help in terms of
parallelism (only one thread will be actually working). If you want to
calculate this in parallel here is an easy solution:

import ppsmp

#start with 10 processes
srv = ppsmp.Server(10)

f = []

for i = 1 in range(0,N):
  for j = 1 in range(0,N):
  #it might be a little bit more complex if 'calculate' depends on
other modules or calls functions
  f.append(srv.submit(calculate, (i,j)))

for i = 1 in range(0,N):
  for j = 1 in range(0,N):
 D[i][j] = f.pop(0)

You can get the latest version of ppsmp module here:
http://www.parallelpython.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread John

Damn! That is bad news. So even if caclulate is independent for (i,j)
and
is computable on separate CPUs (parts of it are CPU bound, parts are IO
bound)
python cant take advantage of this?

Surprised,
--Tom

Paul Rubin wrote:
> "John" <[EMAIL PROTECTED]> writes:
> > I want to do something like this:
> >
> > for i = 1 in range(0,N):
> >  for j = 1 in range(0,N):
> >D[i][j] = calculate(i,j)
> >
> > I would like to now do this using a fixed number of threads, say 10
> > threads. What is the easiest way to do the "parfor" in python?
>
> It won't help in terms of actual parallelism.  Python only lets one
> thread run at a time, even on a multi-cpu computer.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread John

Damn! That is bad news. So even if caclulate is independent for (i,j)
and
is computable on separate CPUs (parts of it are CPU bound, parts are IO
bound)
python cant take advantage of this?

Surprised,
--j

Paul Rubin wrote:
> "John" <[EMAIL PROTECTED]> writes:
> > I want to do something like this:
> >
> > for i = 1 in range(0,N):
> >  for j = 1 in range(0,N):
> >D[i][j] = calculate(i,j)
> >
> > I would like to now do this using a fixed number of threads, say 10
> > threads. What is the easiest way to do the "parfor" in python?
>
> It won't help in terms of actual parallelism.  Python only lets one
> thread run at a time, even on a multi-cpu computer.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-13 Thread John


Thanks. Does it matter if I call shell commands os.system...etc in
calculate?

Thanks,
--j

[EMAIL PROTECTED] wrote:
> John wrote:
> > I want to do something like this:
> >
> > for i = 1 in range(0,N):
> >  for j = 1 in range(0,N):
> >D[i][j] = calculate(i,j)
> >
> > I would like to now do this using a fixed number of threads, say 10
> > threads.
> > What is the easiest way to do the "parfor" in python?
> >
> > Thanks in advance for your help,
>
> As it was already mentioned before threads will not help in terms of
> parallelism (only one thread will be actually working). If you want to
> calculate this in parallel here is an easy solution:
>
> import ppsmp
>
> #start with 10 processes
> srv = ppsmp.Server(10)
>
> f = []
>
> for i = 1 in range(0,N):
>   for j = 1 in range(0,N):
>   #it might be a little bit more complex if 'calculate' depends on
> other modules or calls functions
>   f.append(srv.submit(calculate, (i,j)))
>
> for i = 1 in range(0,N):
>   for j = 1 in range(0,N):
>  D[i][j] = f.pop(0)
>
> You can get the latest version of ppsmp module here:
> http://www.parallelpython.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-14 Thread Paul Rubin
"John" <[EMAIL PROTECTED]> writes:
> Damn! That is bad news. So even if caclulate is independent for
> (i,j) and is computable on separate CPUs (parts of it are CPU bound,
> parts are IO bound) python cant take advantage of this?

Not at the moment, unless you write C extensions that release the
global interpreter lock (GIL).  One of these days.  Meanwhile there
are various extension modules that let you use multiple processes,
look up POSH and Pyro.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-14 Thread parallelpython
John wrote:
> Thanks. Does it matter if I call shell commands os.system...etc in
> calculate?
>
> Thanks,
> --j

The os.system command neglects important changes in the environment
(redirected streams) and would not work with current version of ppsmp.
Although there is a very simple workaround:
print os.popen("yourcommand").read()
instead of os.system("yourcommand")


Here is a complete working example of that code:
http://www.parallelpython.com/component/option,com_smf/Itemid,29/topic,13.0

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-14 Thread skip

John> Damn! That is bad news. So even if caclulate is independent for
John> (i,j) and is computable on separate CPUs (parts of it are CPU
John> bound, parts are IO bound) python cant take advantage of this?

It will help if parts are I/O bound, presuming the threads which block
release the global interpreter lock (GIL).

There is a module in development (processing.py) that provides an API like
the threading module but that uses processes under the covers:

http://mail.python.org/pipermail/python-dev/2006-October/069297.html

You might find that an interesting alternative.

Skip

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-14 Thread sturlamolden

John wrote:
> I want to do something like this:
>
> for i = 1 in range(0,N):
>  for j = 1 in range(0,N):
>D[i][j] = calculate(i,j)
>
> I would like to now do this using a fixed number of threads, say 10
> threads.

Why do you want to run this in 10 threads? Do you have 10 CPUs?

If you are concerned about CPU time, you should not be using threads
(regardless of language) as they are often implemented with the
assumption that they stay idle most of the time (e.g. win32 threads and
pthreads). In addition, CPython has a global interpreter lock (GIL)
that prevents the interpreter from running on several processors in
parallel. It means that python threads are a tool for things like
writing non-blocking i/o and maintaining responsiveness in a GUI'. But
that is what threads are implemented to do anyway, so it doesn't
matter. IronPython and Jython do not have a GIL.

In order to speed up computation you should run multiple processes and
do some sort of IPC. Take a look at MPI (e.g. mpi4py.scipy.org) or
'parallel python'. MPI is the de facto industry standard for dealing
with CPU bound problems on systems with multiple processors, whether
the memory is shared or distributed does not matter. Contrary to common
belief, this approach is more efficient than running multiple threads,
sharing memory and synchronizong with mutexes and event objects - even
if you are using a system unimpeded by a GIL.

The number of parallel tasks should be equal to the number of available
CPU units, not more, as you will get excessive context shifts if the
number of busy threads or processes exceed the number of computational
units. If you only have two logical CPUs (e.g. one dual-core processor)
you should only run two parallel tasks - not ten. If you try to
parallelize using additional tasks (e.g. 8 more), you will just waste
time doing more context shifts, more cache misses, etc. But if you are
a lucky bastard with access to a 10-way server, sure run 10 tasks in
parallel.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded for loop

2007-01-14 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
>
> There is a module in development (processing.py) that provides an API like
> the threading module but that uses processes under the covers:
>
> http://mail.python.org/pipermail/python-dev/2006-October/069297.html
>
> You might find that an interesting alternative.

See the promised parallel processing overview on the python.org Wiki
for a selection of different solutions:

http://wiki.python.org/moin/ParallelProcessing

Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Preston Hagar
On 7/6/06, bruce <[EMAIL PROTECTED]> wrote:
hi..basic foor/loop question..i can do: for a in foo  print aif i want to do something like  for a, 2, fooprint foowhere go from 2, to foo..i can't figure out how to accomplish this...
can someone point me to how/where this is demonstrated...You might want to look here:http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm
I am not exactly sure what you are asking, so perhaps a hopefully related example will help you on your way.Let's say you have a variable foo and want to count from 2 to the value of foo, you could do the following:
foo = 20for i in range(2,foo):  print iThis would print the numbers 2 through 29 out.Hope this helps.Preston
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2006-07-06 Thread Daniel Haus
just do:

for a in range(2, foo+1):
print a

range(a, b) gives [a, a+1, a+2, ..., b-2, b-1]


bruce schrieb:

> hi..
>
> basic foor/loop question..
>
> i can do:
>
>  for a in foo
>   print a
>
> if i want to do something like
>   for a, 2, foo
> print foo
>
> where go from 2, to foo..
>
> i can't figure out how to accomplish this...
>
> can someone point me to how/where this is demonstrated...
>
> found plenty of google for for/loop.. just not this issue..
> 
> thanks
> 
> -bruce

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: for loop question

2006-07-06 Thread bruce
'ppreaciate the answers

duh...

-bruce


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Daniel Haus
Sent: Thursday, July 06, 2006 2:02 PM
To: python-list@python.org
Subject: Re: for loop question


just do:

for a in range(2, foo+1):
print a

range(a, b) gives [a, a+1, a+2, ..., b-2, b-1]


bruce schrieb:

> hi..
>
> basic foor/loop question..
>
> i can do:
>
>  for a in foo
>   print a
>
> if i want to do something like
>   for a, 2, foo
> print foo
>
> where go from 2, to foo..
>
> i can't figure out how to accomplish this...
>
> can someone point me to how/where this is demonstrated...
>
> found plenty of google for for/loop.. just not this issue..
> 
> thanks
> 
> -bruce

-- 
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Grant Edwards
On 2006-07-06, Daniel Haus <[EMAIL PROTECTED]> wrote:

>> i can do:
>>
>>  for a in foo
>>   print a
>>
>> if i want to do something like
>>   for a, 2, foo
>> print foo
>>
>> where go from 2, to foo..

> just do:
>
> for a in range(2, foo+1):
> print a

Except that in the OP's example foo was a sequence, not an
integer.  I think.

-- 
Grant Edwards   grante Yow!  You can't hurt
  at   me!! I have an ASSUMABLE
   visi.comMORTGAGE!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread Daniel Haus
> Except that in the OP's example foo was a sequence, not an
> integer.  I think.

Yes, possibly. But then, what's "from 2 to foo"?

this way it might be

for a in [2] + foo:
print a

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop question

2006-07-06 Thread York
for a in range(2, len(foo)): print a

or maybe you need
for a in range(1, len(foo)): print a
?

York


bruce wrote:
> hi..
> 
> basic foor/loop question..
> 
> i can do:
> 
>  for a in foo
>   print a
> 
> if i want to do something like
>   for a, 2, foo
> print foo
> 
> where go from 2, to foo..
> 
> i can't figure out how to accomplish this... 
> 
> can someone point me to how/where this is demonstrated...
> 
> found plenty of google for for/loop.. just not this issue..
> 
> thanks
> 
> -bruce
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Kay Schluehr
George Sakkis wrote:

> This would be very
> useful for list/generator comprehensions, for example being able to
write something like:
>
> [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>

Looks very appealing, but what to do with

[x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?

Should it raise an exception due to a pattern mismatch?

If not how should matching rules apply here?

[x*y-z for (x=0,y=0,z=0) in (1,2,3), (4,5), (6,7,8)]

If in doubt write a vector class that cares about the correct padding (
or more general and with geometric meaning: select the right hyperplane
) and enable to switch between different paddings. This solution is
both flexible and reusable.

Regards Kay

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Matteo Dell'Amico
George Sakkis wrote:
I'm sure there must have been a past thread about this topic but I don't know 
how to find it: How
about extending the "for  in" syntax so that X can include default arguments 
? This would be very
useful for list/generator comprehensions, for example being able to write 
something like:
[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
instead of the less elegant explicit loop version that has to check for the 
length of each sequence.
What do you think ?
How did you get the data in that format in the first place? It looks a 
bit strange to me. Wouldn't it be easier to fill in default values when 
you gather data as opposed to when you use it?

--
Ciao,
Matteo
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Kay Schluehr" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
>
> > This would be very
> > useful for list/generator comprehensions, for example being able to
> write something like:
> >
> > [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
> >
>
> Looks very appealing, but what to do with
>
> [x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?
>
> Should it raise an exception due to a pattern mismatch?

I didn't have in mind to generalize the syntax even more than the respective 
for function
signatures, therefore this would be syntax error:
SyntaxError: non-keyword arg after keyword arg

> If not how should matching rules apply here?
>
> [x*y-z for (x=0,y=0,z=0) in (1,2,3), (4,5), (6,7,8)]
>
> If in doubt write a vector class that cares about the correct padding (
> or more general and with geometric meaning: select the right hyperplane
> ) and enable to switch between different paddings. This solution is
> both flexible and reusable.
>
> Regards Kay

This was just an example; I think the proposed functionality will be helpful in 
far more cases than
dealing with geometry or vectors, so I would prefer it to be supported by the 
language itself.

Regards,
George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Matteo Dell'Amico" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
> > I'm sure there must have been a past thread about this topic but I don't 
> > know how to find it:
How
> > about extending the "for  in" syntax so that X can include default 
> > arguments ? This would be
very
> > useful for list/generator comprehensions, for example being able to write 
> > something like:
> >
> > [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
> >
> > instead of the less elegant explicit loop version that has to check for the 
> > length of each
sequence.
> > What do you think ?
>
> How did you get the data in that format in the first place? It looks a
> bit strange to me. Wouldn't it be easier to fill in default values when
> you gather data as opposed to when you use it?

Not always. Say for example that you're doing some 2D geometry stuff, and later 
you have to extend
it to 3D. In this case you may have to deal with both 2D and 3D objects, and 
map the former to the
latter when necessary.

George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Heiko Wundram
On Sunday 20 March 2005 20:47, George Sakkis wrote:
> Not always. Say for example that you're doing some 2D geometry stuff, and
> later you have to extend it to 3D. In this case you may have to deal with
> both 2D and 3D objects, and map the former to the latter when necessary.

But this rather sounds like you'd want an adaptor iterator, like the 
following:

>>> class AdaptPossible2D(object):
...   def __init__(self,data):
... self.data = data
...   def __iter__(self):
... for item in self.data:
...   if len(item) == 2:
... yield item+(0,)
...   else:
... yield item
...
>>> for x,y,z in AdaptPossible2D([(1,2),(1,2,3),(3,4)]):
...   print x,y,z
...
1 2 0
1 2 3
3 4 0

Using the above code makes it absolutely clear what you want, and doesn't need 
any new syntax which can be ambiguous like (x=0,y,z=0), etc. The above idiom 
also takes only constant extra space, as it doesn't duplicate the list during 
iteration.

-- 
--- Heiko.


pgpiKidxAK8Og.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Heiko Wundram" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> On Sunday 20 March 2005 20:47, George Sakkis wrote:
> > Not always. Say for example that you're doing some 2D geometry stuff, and
> > later you have to extend it to 3D. In this case you may have to deal with
> > both 2D and 3D objects, and map the former to the latter when necessary.
>
> But this rather sounds like you'd want an adaptor iterator, like the
> following:
>
> >>> class AdaptPossible2D(object):
> ...   def __init__(self,data):
> ... self.data = data
> ...   def __iter__(self):
> ... for item in self.data:
> ...   if len(item) == 2:
> ... yield item+(0,)
> ...   else:
> ... yield item
> ...
> >>> for x,y,z in AdaptPossible2D([(1,2),(1,2,3),(3,4)]):
> ...   print x,y,z
> ...
> 1 2 0
> 1 2 3
> 3 4 0
>
> Using the above code makes it absolutely clear what you want, and doesn't need
> any new syntax which can be ambiguous like (x=0,y,z=0), etc. The above idiom
> also takes only constant extra space, as it doesn't duplicate the list during
> iteration.


Once more, the 2D/3D example was just that, an example; my point was not to 
find a specific solution
to a specific problem. Extending the "for .. in" syntax would be an elegant way 
to express this idea
in a more succint, familiar and generic way than a customized adaptor. As for 
the ambiguity, it is
not more ambiguous than function signatures as long as all keyword arguments go 
after all the
required ones; I'm not suggesting that (x=0,y,z=0) should be valid.

George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Heiko Wundram
Am Sonntag, 20. März 2005 22:22 schrieb George Sakkis:
> Once more, the 2D/3D example was just that, an example; my point was not to
> find a specific solution to a specific problem.

And my point being: it's simple enough to give a general recipe (which my 
example was) without extending Python's syntax, so why extend the syntax and 
not just use a solution derived from that recipe that's working now (and is 
backwards compatible at least to 2.3), and which is also clear in itself?

I'm not saying that your syntax looks "strange" or "bad", but there are means 
to do what you want to do now, without cumbersome syntax or duplicating code, 
and as such I'm -1 on syntactic sugar (TOWTDI and all)...

Don't take this the wrong way, but I think introducing syntax is the wrong 
solution to a non-existant problem with the language.

-- 
--- Heiko.


pgpKzqC7Aa4ue.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: For loop extended syntax

2005-03-20 Thread George Sakkis
"Heiko Wundram" <[EMAIL PROTECTED]> wrote:

> Am Sonntag, 20. März 2005 22:22 schrieb George Sakkis:
> > Once more, the 2D/3D example was just that, an example; my point was not to
> > find a specific solution to a specific problem.
>
> And my point being: it's simple enough to give a general recipe (which my
> example was) without extending Python's syntax, so why extend the syntax and
> not just use a solution derived from that recipe that's working now (and is
> backwards compatible at least to 2.3), and which is also clear in itself?
>
> I'm not saying that your syntax looks "strange" or "bad", but there are means
> to do what you want to do now, without cumbersome syntax or duplicating code,
> and as such I'm -1 on syntactic sugar (TOWTDI and all)...
>
> Don't take this the wrong way, but I think introducing syntax is the wrong
> solution to a non-existant problem with the language.

The way I see it, it's closer to applying existing syntax (from function 
signatures) in a new
context than introducing new syntax, but that's a detail. I guess it's a matter 
of personal
preference to syntactic sugar then. Still, python is rife with syntactic sugar: 
iterators, default
function arguments, *varargs, **kwdargs, [list]/(tuple)/{dict} literals, 
recently @decorators, and
more. If syntactic sugar didn't matter, we would be happy with scheme's syntax.

George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-20 Thread Kay Schluehr
George Sakkis wrote:

> > Looks very appealing, but what to do with
> >
> > [x*y-z for (x=0,y,z) in (1,2,3), (4,5), (6,7,8)] ?
> >
> > Should it raise an exception due to a pattern mismatch?
>
> I didn't have in mind to generalize the syntax even more than the
respective
> for function
> signatures, therefore this would be syntax error:
> SyntaxError: non-keyword arg after keyword arg

O.K. Allthough it has fallen out of Guidos favor one can use a lambda
to obtain the same solution:

[(lambda x,y,z=0:x*y-z)(*vec) for vec in (1,2,3), (4,5), (6,7,8)]

This inspires to examine Your list comprehension not as plain 'syntax
suggar' but in a clear operational perspective. Since (x,y,z=0) is not
a valid Python tuple we have to replace it by

lambda x,y,z=0:(x,y,z)

This acts on the list elements of the comprehension like the proposed
(x,y,z=0) whereas the valid (x,y,z) acts like

lambda x,y,z:(x,y,z)

So we have generalized tuples to lambdas. If we let lambda
x,y,z=0:(x,y,z) iterate over the list elements, why not the generalized

lambda x,y,z=0:(lambda x,a=0:(x,a),y,z) ?

Returning to Your soluion and translating back the lambda:

[x*y-z for ((x,a=0),y,z=0) in (1,2,3), (4,5), (6,7,8)]

should also be possible from an operational perspective.

Regards Kay

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Ron
On Sun, 20 Mar 2005 13:16:37 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:

>I'm sure there must have been a past thread about this topic but I don't know 
>how to find it: How
>about extending the "for  in" syntax so that X can include default 
>arguments ? This would be very
>useful for list/generator comprehensions, for example being able to write 
>something like:
>
>[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>
>instead of the less elegant explicit loop version that has to check for the 
>length of each sequence.
>What do you think ?
>
>George
>

How would this examples work?

for x=5,y,z in (123),(4,5),(6,7,8,9)

Would the x default over ride the first value?
Should, the 4 element in the third tuple be dropped without an error?


A  general reusable function might be something like this:

def formatlistofargs(arglist, nargs=1, defvalue=0):
returnvalues = []
for i in arglist:
ii = list(i)
while len(ii)http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread George Sakkis
"Ron" <[EMAIL PROTECTED]> wrote:

> How would this examples work?
>
> for x=5,y,z in (123),(4,5),(6,7,8,9)
>
> Would the x default over ride the first value?
> Should, the 4 element in the third tuple be dropped without an error?

It has already been clarified twice in the thread that the default values would 
be allowed *only in
the end*, exactly as default function arguments.

> A  general reusable function might be something like this:
>
> def formatlistofargs(arglist, nargs=1, defvalue=0):
> returnvalues = []
> for i in arglist:
> ii = list(i)
> while len(ii) ii.append(defvalue)
> ii=ii[:nargs]
> returnvalues.append(ii)
> return returnvalues
>
> for x,y,z in formatlistofargs(((1,2,3),(3,4),(5,6,7,8)),3):
> print x,y,z

Of course there are ways to have a function fill in the defaults, but 
syntactically I would find
"for (x,y,z=0) in (1,2,3), (4,5), (6,7,8): print x,y,z" more obvious and 
concise.

By the way, I don't think it's a good idea in general to drop the extra values 
implicitly, as you do
in your recipe, for the same reason that calling a function foo(x,y,z) as 
foo(1,2,3,4) is an error.
A generalization of the 'for .. in' syntax that would handle extra arguments 
the same way as
functions would be:

for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
 print x, y, z, rest

I'd love to see this in python one day; it is pretty obvious what it would do 
for anyone familiar
with function argument tuples.

George


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Jeff Shannon
George Sakkis wrote:
A generalization of the 'for .. in' syntax that would handle 
> extra arguments the same way as functions would be:
for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
 print x, y, z, rest
I'd love to see this in python one day; it is pretty obvious what
> it would do for anyone familiar with function argument tuples.
Let's all keep in mind that for...in... is using standard tuple 
unpacking rules (you're getting the next tuple from a list of tuples, 
and then unpacking that tuple), so what is really being proposed are 
extensions to tuple unpacking.  (Making this work in the context of a 
for loop but not work in other tuple-unpacking situations would create 
inconsistency.)

Function arguments are *not* (in general) a case of tuple unpacking, 
on the other hand, so the parallels between function arguments and for 
loop control-variable tuples are not so straightforward as is being 
claimed.

There may be valid arguments in favor of enhancing tuple unpacking in 
this way (indeed, I believe I recall a thread or two on this subject), 
but it's important to consider the general consequences, not just the 
single aspect of for-loop usage.

Jeff Shannon
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Terry Reedy

"George Sakkis" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> A generalization of the 'for .. in' syntax that would handle
> extra arguments the same way as functions would be:
>
> for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
> print x, y, z, rest
>
> I'd love to see this in python one day; it is pretty obvious
> what it would do for anyone familiar with function argument tuples.

Jeff covered the obvious objection that this is a change from assignment 
sematics to function call semantics.  Slightly less obvious is that this 
will slow down everyone's for loops for the benefit of the very few who 
would want to do such a thing.  (Is the above based on a real use case?) 
Python function calls are 'slow' (relative to assignment, certainly) in 
part *because* of the great flexibility in call signatures.

In any case, one can now write (with hardcoded format and types, untested):

def argify(*tups):
  for tup in tups:
ltup = len(tup)
ifltup >= 4: yield tup[0:3] + (tup[3:],)
elif ltup == 3: yield tup + ((),)
elif ltup == 2: yield tup + (0, ())
else:raise TypeError("Tuple %s needs at least 2 items" 
% (tup,)

for x,y,z,rest in argify(): print x,y,x,rest

Terry J. Reedy

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Greg Ewing
Jeff Shannon wrote:
Function arguments are *not* (in general) a case of tuple unpacking, on 
the other hand, so the parallels between function arguments and for loop 
control-variable tuples are not so straightforward as is being claimed.
It seems to me the parallel is close enough that no
confusion would result.
Can you think of any situation in which surprising
behaviour would occur through someone thinking the
parallel was closer than it is?
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Ron
On Mon, 21 Mar 2005 15:56:26 -0500, "George Sakkis"
<[EMAIL PROTECTED]> wrote:


>It has already been clarified twice in the thread that the default values 
>would be allowed *only in
>the end*, exactly as default function arguments.

Was just asking if there should be other special general cases.  What
programmers want usually depend on the problem at hand. imho  :)

>Of course there are ways to have a function fill in the defaults, but 
>syntactically I would find
>"for (x,y,z=0) in (1,2,3), (4,5), (6,7,8): print x,y,z" more obvious and 
>concise.
>
>By the way, I don't think it's a good idea in general to drop the extra values 
>implicitly, as you do
>in your recipe, for the same reason that calling a function foo(x,y,z) as 
>foo(1,2,3,4) is an error.
>A generalization of the 'for .. in' syntax that would handle extra arguments 
>the same way as
>functions would be:
>
>for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
> print x, y, z, rest
>
>I'd love to see this in python one day; it is pretty obvious what it would do 
>for anyone familiar
>with function argument tuples.
>
>George

I would probably do it this way myself:

def padlist(alist,length,pad):
alist[length:]=[pad]*(length-len(alist))
return alist

for xyz in [1,2,3],[3,4],[5,6,7]:
x,y,z = padlist(xyz, 3, 0)
print x,y,z

# or this if it's faster:

for x,y,z in [padlist(xyz,3,0) for xyz in [1,2,3],[3,4],[5,6,7]]:
print x,y,z


Which isn't too different from what you are suggesting.  I think
someone may have already suggested using list comprehensions.

Ron






-- 
http://mail.python.org/mailman/listinfo/python-list


Re: For loop extended syntax

2005-03-21 Thread Kay Schluehr
Terry Reedy wrote:

> Jeff covered the obvious objection that this is a change from
assignment
> sematics to function call semantics.
> Slightly less obvious is that this
> will slow down everyone's for loops for the benefit of the very few
who
> would want to do such a thing.

If the action of (x,y,z=0) on a tuple is regarded as a function call
why not letting resolve it by the compiler in an appropriate manner?
The tuple assignment is just a special case of this and can be resolved
in a different way. There would be no slowdown at all.

Regards Kay

-- 
http://mail.python.org/mailman/listinfo/python-list


Pyrex: step in for loop

2005-05-26 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,

I'm trying to improve speed in a module and substituted the pythonic
'for in range()' for 'for i from min < i < max:'

But, I need to define a step for the i variable.  How can I do it?

for example, how do I iterate through 8 to 14 with step 1?

Luis
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFClkGTHn4UHCY8rB8RAgZXAJ0XPg9IH0OU329FVX3o14QjNFXuXgCgm+UR
O0GpXmDpQr7Y7TgMsmVvZ6s=
=zZnm
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


best solution to for loop

2005-09-21 Thread Mauricio Tellez
Hi, I have several apps which connect to a database,  fetch some
data an put this into a gtk.TreeStore, but if the result set is 1500
row long, the app response slowly, how can optimize this? here is an
example of what I do:

cur.execute("SELECT * FROM clients")data = "">

for row in data:
   treeStore.append(row[0], row[1], row[4], "Ohio", row[5])

I read Guido's  An Optimization Anecdote ( http://www.python.org/doc/essays/list2str.html)
 and perhaps filter() or something like that could help. Any clue?

--
Mauricio Tellez
-- 
http://mail.python.org/mailman/listinfo/python-list

assignment in a for loop

2006-05-16 Thread MackS
Hello everyone

Consider the following

>>> l = [1,2]
>>> for i in l:
... i = i + 1
...
>>> l
[1, 2]

I understand (I think!) that this is due to the fact that in Python
what looks like "assignment" really is binding a name to an object. The
result is that inside the loop I am creating an object with value (i+1)
and then "pointing" the name i at it. Therefore, the object to which i
previously pointed (an element of list l) remains unchanged.

Two brief questions:

1) Is what I wrote above (minimally) correct?

2) Independently of the answer to 1, is there a way for me to assign to
elements of a list inside a loop and without resorting to C-style
ugliness of

for i in range(len(l))
 l[i] = l[i] + 1

?

(Note: not using a list comprehension.)

Thanks in advance

Mack

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-05 Thread Gabriel Genellina

At Friday 5/1/2007 17:39, [EMAIL PROTECTED] wrote:


wordfreq = [wordlist.count(p) for p in wordlist]

I would expect

for p in wordlist:
wordfreq.append(wordlist.count(p))


I didn't know you could have an expression in the same line.


That's known as a "list comprehension" and is roughly equivalent to 
your code. Section 5 of the tutorial covers them. 
http://docs.python.org/tut/node7.html



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: strange for loop construct

2007-01-05 Thread Mark Elston
* Gabriel Genellina wrote (on 1/5/2007 12:49 PM):
> At Friday 5/1/2007 17:39, [EMAIL PROTECTED] wrote:
> 
>> wordfreq = [wordlist.count(p) for p in wordlist]
>>
>> I would expect
>>
>> for p in wordlist:
>> wordfreq.append(wordlist.count(p))
>>
>>
>> I didn't know you could have an expression in the same line.
> 
> That's known as a "list comprehension" and is roughly equivalent to your 
> code. Section 5 of the tutorial covers them. 
> http://docs.python.org/tut/node7.html
> 
> 

If you have a Python installation you should be able to find the
"Whats New" section of the docs.  List comprehensions are described
pretty well in the "What's new in Python 2.0?" section.  This gives
some simple examples as well as the rationale behind them.

Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread Gabriel Genellina
Mark Elston ha escrito:

> If you have a Python installation you should be able to find the
> "Whats New" section of the docs.  List comprehensions are described
> pretty well in the "What's new in Python 2.0?" section.  This gives
> some simple examples as well as the rationale behind them.

Where do you find the "What's new" for previous releases? I have to
read them online.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread skip
Gabriel> Where do you find the "What's new" for previous releases? I
Gabriel> have to read them online.

Google for

what's new site:python.org

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread Gabriel Genellina
On 7 ene, 16:34, [EMAIL PROTECTED] wrote:

> Gabriel> Where do you find the "What's new" for previous releases? I
> Gabriel> have to read them online.
>
> Google for
> > what's new site:python.org

That's what I do. But this post:

> If you have a Python installation you should be able to find the
> "Whats New" section of the docs.  List comprehensions are described
> pretty well in the "What's new in Python 2.0?" section.

suggested that one could find that info inside the Python installation,
and I was asking *where*, because I can't find it, and I suspect it
actually isn't there.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread skip

Gabriel> Where do you find the "What's new" for previous releases? I
Gabriel> have to read them online.
>> 
>> Google for
>> > what's new site:python.org

Sorry, I took "I have to read them online" to mean that you needed to read
them online because (perhaps) you don't have a source distribution on your
computer.  My 2.5 source (Subversion sandbox) has 2.0 through 2.5 What's New
source in Doc/whatsnew.

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread Jorge Godoy
[EMAIL PROTECTED] writes:

> Gabriel> Where do you find the "What's new" for previous releases? I
> Gabriel> have to read them online.
> >> 
> >> Google for
> >> > what's new site:python.org
>
> Sorry, I took "I have to read them online" to mean that you needed to read
> them online because (perhaps) you don't have a source distribution on your
> computer.  My 2.5 source (Subversion sandbox) has 2.0 through 2.5 What's New
> source in Doc/whatsnew.

My SuSE installation has it as /usr/share/doc/packages/python/Misc/NEWS

-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread Dustan

Mark Elston wrote:
> * Gabriel Genellina wrote (on 1/5/2007 12:49 PM):
> > At Friday 5/1/2007 17:39, [EMAIL PROTECTED] wrote:
> >
> >> wordfreq = [wordlist.count(p) for p in wordlist]
> >>
> >> I would expect
> >>
> >> for p in wordlist:
> >> wordfreq.append(wordlist.count(p))
> >>
> >>
> >> I didn't know you could have an expression in the same line.
> >
> > That's known as a "list comprehension" and is roughly equivalent to your
> > code. Section 5 of the tutorial covers them.
> > http://docs.python.org/tut/node7.html
> >
> >
>
> If you have a Python installation you should be able to find the
> "Whats New" section of the docs.  List comprehensions are described
> pretty well in the "What's new in Python 2.0?" section.  This gives
> some simple examples as well as the rationale behind them.

Shouldn't that same page be found on the python website?
http://www.python.org/doc/2.0/
Any clue as to why it isn't?

> Mark

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange for loop construct

2007-01-07 Thread Gabriel Genellina
On 7 ene, 18:52, "Dustan" <[EMAIL PROTECTED]> wrote:

> Shouldn't that same page be found on the python 
> website?http://www.python.org/doc/2.0/
> Any clue as to why it isn't?

For 2.0 it's on
http://www.python.org/download/releases/2.0/new-python.htm
For later ones, it's on
http://www.python.org/download/releases/2.5/NEWS.txt (replacing 2.5 as
desired)
You can use google with site:www.python.org (or the Search box in the
Python web) to locate them.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for loop

2007-01-11 Thread Amit Khemka
On 11 Jan 2007 20:48:19 -0800, raghu <[EMAIL PROTECTED]> wrote:
> can any one help me explaining for loop and its execution and its
> syntax with a simple example.

Well Guido did that:
http://docs.python.org/tut/node6.html#SECTION00620


-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for loop

2007-01-11 Thread Paul McGuire
"raghu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> can any one help me explaining for loop and its execution and its
> syntax with a simple example.
>
Bookmark this page: http://docs.python.org/ref/ref.html
"for loop" reference page: http://docs.python.org/ref/for.html
Bookmark this page: http://docs.python.org/tut/tut.html
"for loop" explanation: 
http://docs.python.org/tut/node6.html#SECTION00620

Please avail yourself of one of the many online or hardcopy Python tutorial 
and reference resources.  If you are asking about for loops, you have a lot 
of basic ground to cover, more than is really suitable for newsgroup 
traffic.  Google for "python tutorial" should give you a good start.

-- Paul



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Explanation about for loop

2007-01-11 Thread Gabriel Genellina

At Friday 12/1/2007 01:48, raghu wrote:


can any one help me explaining for loop and its execution and its
syntax with a simple example.


This section of Dive Into Python explain for loops:
http://diveintopython.org/file_handling/for_loops.html
(And you could read the whole book too)


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pyrex: step in for loop

2005-05-26 Thread Mike Meyer
"Luis P. Mendes" <[EMAIL PROTECTED]> writes:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> Hi,
>
> I'm trying to improve speed in a module and substituted the pythonic
> 'for in range()' for 'for i from min < i < max:'
>
> But, I need to define a step for the i variable.  How can I do it?
>
> for example, how do I iterate through 8 to 14 with step 1?

guru% pydoc range
Help on built-in function range in module __builtin__:

range(...)
range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

so it's

for i in range(8, 14, 1): ...

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pyrex: step in for loop

2005-05-26 Thread Luis P. Mendes
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1


| so it's
|
| for i in range(8, 14, 1): ...
|
| http://enigmail.mozdev.org

iD8DBQFClkmlHn4UHCY8rB8RAlUqAKCxSEkEKVIcoshTwmL7GQNK6d/j0wCgoC67
jOhuXQpnDt23SEAM9huKTQA=
=8XO0
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pyrex: step in for loop

2005-05-26 Thread Mike Meyer
"Luis P. Mendes" <[EMAIL PROTECTED]> writes:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
>
> | so it's
> |
> | for i in range(8, 14, 1): ...
> |
> | 
> For what I've read, for i in range is slower than the other for
> construct used by Pyrex:
>
> for i from iMin <= i < iMax:
>
> My question had to do with this new expression.  How can I introduce a
> step there.

My bad. I missed the "Pyrex" in the subject line.

   Sorry,
 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pyrex: step in for loop

2005-05-26 Thread Greg Ewing
Luis P. Mendes wrote:

> I'm trying to improve speed in a module and substituted the pythonic
> 'for in range()' for 'for i from min < i < max:'
> 
> But, I need to define a step for the i variable.  How can I do it?

If you want maximum clarity, I'd suggest using the for-loop
to iterate over a contiguous range of integers and an expression
that maps the loop variable to whatever you want.

If you want the maximum possible speed, it *may* be faster
to use a while loop instead and do your own index updating.
But profile to make sure.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
-- 
http://mail.python.org/mailman/listinfo/python-list


how to break a for loop?

2006-02-20 Thread Gregory Petrosyan
Hello!
It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
that's why I encountered stupid problem: I need to remove zeros from
the begining of list, but I can't :-(. I use

for i,coef in enumerate(coefs):
if coef == 0:
del coefs[i]
else:
break

but it removes ALL zeros from list. What's up?


P.S. I feel SO stupid asking this quastion... ;-)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best solution to for loop

2005-09-22 Thread Dan
> Hi, I have several apps which connect to a database,  fetch some data
> an put this into a gtk.TreeStore, but if the result set is 1500 row
> long, the app response slowly

The first thing to test is whether it's Python or the database that's
the bottleneck. 1500 rows isn't all that much for a database, but it
might not be trivial either.

Even if the bottleneck is Python, the solution might be to limit the
amount of data that you process. For example, rather than displaying all
1500 records in a tree (nobody wants to scroll through 1500 records
anyway), try grouping them by the first letter of their name. Display a
tree consisting of each letter, then when the user clicks that letter:

  cur.execute("SELECT * FROM clients WHERE name LIKE '" + letter + "%'")

-- 
   I had picked out the theme of the baby's room and done other
   things. I decided to let Jon have this.
   - Jamie Cusack (of the Netherlands), whose husband Jon
 finally talked her into letting him name their son Jon 2.0


-- 
http://mail.python.org/mailman/listinfo/python-list


problem with array and for loop

2006-05-10 Thread Fabian Braennstroem
Hi,

I have a 'simple' problem with a multidimension array in a
for loop. It looks like this:

wert= zeros([127,2])
wert1= zeros(127)
m=1
l=1

for pos in [pos1,pos2,pos3]: 
for i in range(1,125):
wert[l,m]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
#wert1[i]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
m=m+1;
l=l+1;

It works for the 1D 'wert1'. Does anyone have an idea? 


Greetings!
 Fabian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread MackS
Sorry, my previous post probably was not very good at explaining _why_
I want to do this.

Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

 arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
 ...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.

Thanks

Mack

MackS wrote:
> Hello everyone
>
> Consider the following
>
> >>> l = [1,2]
> >>> for i in l:
> ... i = i + 1
> ...
> >>> l
> [1, 2]
>
> I understand (I think!) that this is due to the fact that in Python
> what looks like "assignment" really is binding a name to an object. The
> result is that inside the loop I am creating an object with value (i+1)
> and then "pointing" the name i at it. Therefore, the object to which i
> previously pointed (an element of list l) remains unchanged.
>
> Two brief questions:
>
> 1) Is what I wrote above (minimally) correct?
>
> 2) Independently of the answer to 1, is there a way for me to assign to
> elements of a list inside a loop and without resorting to C-style
> ugliness of
>
> for i in range(len(l))
>  l[i] = l[i] + 1
>
> ?
>
> (Note: not using a list comprehension.)
> 
> Thanks in advance
> 
> Mack

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

> >>> l = [1,2]
> >>> for i in l:
> ... i = i + 1
> ...
> >>> l
> [1, 2]
> 
> I understand (I think!) that this is due to the fact that in Python
> what looks like "assignment" really is binding a name to an
> object. The result is that inside the loop I am creating an object
> with value (i+1) and then "pointing" the name i at it. Therefore,
> the object to which i previously pointed (an element of list l)
> remains unchanged.

That's a fair explanation, yes.

> Two brief questions:
> 
> 1) Is what I wrote above (minimally) correct?

Correct for what? You can tell if it's *syntactically* correct by
simply running it.

As for any other "correct", define that. Does it do what you want it
to do?

> 2) Independently of the answer to 1, is there a way for me to assign
> to elements of a list inside a loop and without resorting to C-style
> ugliness of
> 
> for i in range(len(l))
>  l[i] = l[i] + 1

You can build a new list from your operations on the old one.

new_list = []
for x in old_list:
new_list.append(x+1)

You can also do it more succinctly with a list comprehension
expression.

> (Note: not using a list comprehension.)

What's preventing the use of list comprehensions?

new_list = [x+1 for x in old_list]

-- 
 \  "Smoking cures weight problems. Eventually."  -- Steven Wright |
  `\   |
_o__)  |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

[MackS, please don't top-post.]

> Suppose I want to do modify all arguments which are passed to a
> function. Do I need to use a list comprehension such as
> 
> def f(arg1,arg2,arg3):
> 
>  arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
>  ...
> 
> This would be awful when, eg, one adds an argument to the function
> definition. It would require edition of the code at two different
> locations.

If you anticipate increasing the number of values passed to the
function, and you're doing the same operation on all of them, why not
pass in a list::

>>> def add_one_to_each(nums):
... """ Makes a new list with each value incremented by one. """
...
... incremented_nums = [x+1 for x in nums]
... return incremented_nums
...
>>> foo = [3, 5, 8]
>>> bar = add_one_to_each(foo)
>>> bar
[4, 6, 9]

-- 
 \ "Some mornings, it's just not worth chewing through the leather |
  `\  straps."  -- Emo Philips |
_o__)  |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread MackS
Thank you for your reply.


> > 1) Is what I wrote above (minimally) correct?
>
> Correct for what? You can tell if it's *syntactically* correct by
> simply running it.
>
> As for any other "correct", define that. Does it do what you want it
> to do?

I was referring to my attempted explanation, not the code snippet.

> [...]
>
> What's preventing the use of list comprehensions?
>
> new_list = [x+1 for x in old_list]

Suppose I want to do anything as trivial as modify the values of the
list members _and_ print their new values. List comprehensions must not
contain statements, I think. 


Mack

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-16 Thread Ben Finney
"MackS" <[EMAIL PROTECTED]> writes:

> Thank you for your reply.

A pleasure to help.

> > What's preventing the use of list comprehensions?
> >
> > new_list = [x+1 for x in old_list]
> 
> Suppose I want to do anything as trivial as modify the values of the
> list members _and_ print their new values. List comprehensions must
> not contain statements, I think.

You're correct, but that's because you're creating a new list, not
modifying the existing one. The list comprehension can do anything you
like to generate each element, so long as it's an expression::

>>> foo = [3, 5, 8]
>>> print [x+1 for x in foo]
[4, 6, 9]
>>> print [x**2 for x in foo]
[9, 25, 64]
>>> print [str(x**2) for x in foo]
['9', '25', '64']
>>> print [len(str(x**2)) for x in foo]
[1, 2, 2]

If it's too complex to be readable in a single expression, make it a
function which returns a value, since calling a function is itself an
expression::

>>> def get_result_of_complex_stuff(n):
... quad = n**4
... if len(str(quad)) % 2:
... word = "spam"
... else:
... word = "eggs"
... result = word.strip("s").title()
... return result
...
>>> foo = [3, 5, 8]
>>> print [get_result_of_complex_stuff(x) for x in foo]
['Egg', 'Pam', 'Egg']

Once you have your new list being created by a list comprehension, do
what you like with it. If you want it to be stored, assigned back to
the original name, each value printed, or whatever you like, then do
so::

>>> bar = [get_result_of_complex_stuff(x) for x in foo]
>>> foo = bar
>>> for x in foo:
... print x,
...
Egg Pam Egg

-- 
 \  "One time a cop pulled me over for running a stop sign. He |
  `\said, 'Didn't you see the stop sign?' I said, 'Yeah, but I |
_o__) don't believe everything I read.'"  -- Steven Wright |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: assignment in a for loop

2006-05-17 Thread bruno at modulix
MackS wrote:
(snip)
>>What's preventing the use of list comprehensions?
>>
>>new_list = [x+1 for x in old_list]
>  
> Suppose I want to do anything as trivial as modify the values of the
> list members _and_ print their new values. 

Then it's a sure design smell IMHO. Don't mix presentation with logic.

> List comprehensions must not
> contain statements, I think. 

You're right.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


"For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Hi All,

I apologize if this was brought up before, I couldn't find any "prior
art" :-).
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if :
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if ]
-

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if :
print i*2

Just curious. Thanks!

Sergey.

-- 
http://mail.python.org/mailman/listinfo/python-list


skip item in list "for loop"

2006-04-14 Thread Jacob Rael
I am new to python and I love it. I am hacking a file. I want to not
print a line if it contains the word 'pmos4_highv'. I also don't want
to print the next line. The following code works but it "smells bad"
and just doesn't look right. I was reading about generators. If I was
using one, I could do a .next() after the match and get rid of the
flags. Any suggestions how I can improve this?


inPmos= False

inFile = sys.stdin
fileList = inFile.readlines()

for line in fileList:
line = line.rstrip()
# Remove PMOS definitions - typically two lines. Screwed if only
one and last inst.
if inPmos:
inPmos = False
continue
if 'pmos4_highv' in line:
inPmos = True
continue


jr

-- 
http://mail.python.org/mailman/listinfo/python-list


A little more advanced for loop

2007-02-09 Thread Horta
Hi folks,

  Suppose I have to loop over 3 lists being the same size at the same
time and order. How can I do that without using the range() function
or whatever indexing?

Example using range:

a = ['aaa', '']
b = ['bb', '']
c = ['c', '']

for i in range(len(a)):
# using a[i], b[i], and c[i]

  I'm sure there's a elegant way to do that...

  Thanks in advance.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-20 Thread Schüle Daniel
Gregory Petrosyan wrote:
> Hello!
> It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
> that's why I encountered stupid problem: I need to remove zeros from
> the begining of list, but I can't :-(. I use
> 
> for i,coef in enumerate(coefs):
> if coef == 0:
> del coefs[i]
> else:
> break
> 
> but it removes ALL zeros from list. What's up?

I don't know how enumerate is implemented, but I would
suspect that modifying the list object in the loop
through del is asking for trouble

try
for i,coef in enumerate(coefs[:]):
instead

> P.S. I feel SO stupid asking this quastion... ;-)

uda4i

hth, Daniel

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-20 Thread Petr Jakes
zero_list=[0,0,0,0,0,1,2,3,4]
for x in range(len(zero_list)):
if zero_list[x]!=0: break
nonzero_list=zero_list[x:]
print nonzero_list

but some more "pythonic" solutions will be posted from other users I
guess :)

HTH
Petr Jakes

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-20 Thread Jesus Rivero - (Neurogeek)
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hello Gregory!

I would also use lists to implement this. They are more practical and
you could take advantage of pop() or remove() methods instead of using
the Oh-so-Scary del. You could also use a lambda+map or reduce methods
to remove all zeros or just do something like this:

list_ = [0,0,0,1,0,0,1]
print [ elm for elm in list_ if elm != 0 ]
[1,1]



Regards,

Jesus (Neurogeek)

Gregory Petrosyan wrote:
> Hello!
> It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
> that's why I encountered stupid problem: I need to remove zeros from
> the begining of list, but I can't :-(. I use
> 
> for i,coef in enumerate(coefs):
> if coef == 0:
> del coefs[i]
> else:
> break
> 
> but it removes ALL zeros from list. What's up?
> 
> 
> P.S. I feel SO stupid asking this quastion... ;-)
> 

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org

iD8DBQFD+mVpdIssYB9vBoMRAl4hAJ9RnvgvEo5NsutG9KmD6qOEL7VyFgCfeLit
h7FLsbRvHR1z5DSxSPZHFlY=
=SY2U
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-20 Thread Scott David Daniels
Gregory Petrosyan wrote:
> Hello!
> It's 1:56 o'clock in St.-Petersburg now, and I am still coding... maybe
> that's why I encountered stupid problem: I need to remove zeros from
> the begining of list, but I can't :-(. I use
> 
> for i,coef in enumerate(coefs):
> if coef == 0:
> del coefs[i]
> else:
> break
 for index, coef in enumerate(coefs):
 if coef:
 if index:
 del coefs[: index]
 break

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-20 Thread bonono

Gregory Petrosyan wrote:
>I need to remove zeros from
> the begining of list, but I can't :-(.

I believe the following is almost a direct translation of the above
sentence.

import itertools as it
a=[0,0,0,1,0]
a[:]=it.dropwhile(lambda x: x is 0, a)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread Steven D'Aprano
Petr Jakes wrote:

> zero_list=[0,0,0,0,0,1,2,3,4]
> for x in range(len(zero_list)):
> if zero_list[x]!=0: break
> nonzero_list=zero_list[x:]
> print nonzero_list
> 
> but some more "pythonic" solutions will be posted from other users I
> guess :)


That looks perfectly Pythonic to me.

You know, just because Python has for loops and 
multi-line blocks of code doesn't mean we shouldn't use 
them *wink*


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread Giovanni Bajo
[EMAIL PROTECTED] wrote:

>> I need to remove zeros from
>> the begining of list, but I can't :-(.
>
> I believe the following is almost a direct translation of the above
> sentence.
>
> import itertools as it
> a=[0,0,0,1,0]
> a[:]=it.dropwhile(lambda x: x is 0, a)


Usa lambda x: x==0 or simply lambda x: x

Using 'is' relies on the interpreter reusing existing instances of the
immutable object '0', which is an implementation detail.
-- 
Giovanni Bajo


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread bonono

Giovanni Bajo wrote:
> [EMAIL PROTECTED] wrote:
>
> >> I need to remove zeros from
> >> the begining of list, but I can't :-(.
> >
> > I believe the following is almost a direct translation of the above
> > sentence.
> >
> > import itertools as it
> > a=[0,0,0,1,0]
> > a[:]=it.dropwhile(lambda x: x is 0, a)
>
>
> Usa lambda x: x==0 or simply lambda x: x
>
> Using 'is' relies on the interpreter reusing existing instances of the
> immutable object '0', which is an implementation detail.

stand corrected. But I don't think "lambda x: x" is I want as 0 would
be false which would stop the dropwhile right away.

For this particular case one can even use operator.not_ directly, which
skip the lambda(has some peformance advantage).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread Gregory Petrosyan
Thanks to everybody for help. Python community is very friendly and
helpfull indeed!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread bearophileHUGS
This time it seems that using itertools gives slower results, this is
the test code:

import itertools as it
from operator import __not__

def trim_leading_zeros(seq):
if not seq:
return seq
for pos, el in enumerate(seq):
if el != 0:
break
if seq[pos] == 0:
del seq[:]
return seq
return seq[pos:]

def trim_leading_zeros2(seq):
seq[:] = it.dropwhile(__not__, seq)
return seq

data = ([0,0,0,0,0,1,2,3,4],
[1,2,3,4],
[0,1],
[0,0,0],
[0,0,0,1],
[])

for l in data:
print l, trim_leading_zeros(l), trim_leading_zeros2(l)

from time import clock
n = 3 * 10**5

l = [0] * n + [1] * n
t = clock()
trim_leading_zeros(l)
print round(clock()-t, 2), "s"

l = [0] * n + [1] * n
t = clock()
trim_leading_zeros2(l)
print round(clock()-t, 2), "s"

Gives this output on my PC:

[0, 0, 0, 0, 0, 1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
[0, 1] [1] [1]
[0, 0, 0] [] []
[0, 0, 0, 1] [1] [1]
[] [] []
0.3 s
2.86 s

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to break a for loop?

2006-02-21 Thread bonono

[EMAIL PROTECTED] wrote:
> This time it seems that using itertools gives slower results, this is
> the test code:
Understandable, as dropwhile still needs to go through the whole list
and the difference will be larger when the list get longer. Though I
still prefer that if the list is not horribly long as it is like a
spec. But then, one can always name the fast in place del slice version
like "dropwhileFast".

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with array and for loop

2006-05-10 Thread Robert Kern
Fabian Braennstroem wrote:
> Hi,
> 
> I have a 'simple' problem with a multidimension array in a
> for loop. It looks like this:
> 
> wert= zeros([127,2])
> wert1= zeros(127)
> m=1
> l=1
> 
> for pos in [pos1,pos2,pos3]: 
> for i in range(1,125):
> wert[l,m]= 
> probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
> #wert1[i]= 
> probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
> m=m+1;
> l=l+1;
> 
> It works for the 1D 'wert1'. Does anyone have an idea? 

Oy vey.

So the first time through, you are setting the second column of wert. Then l
(btw, never, ever use lower-case "l" as a single-letter variable name; it looks
like "1") gets incremented to 2, which would try to put data into the third
column of wert. However, wert only has two columns.

Are you aware that numpy array indices start with 0, not 1?

You will probably want to ask numpy questions on the numpy-discussion mailing 
list:

  http://www.scipy.org/Mailing_Lists

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with array and for loop

2006-05-10 Thread Fabian Braennstroem
Hi Robert,

* Robert Kern <[EMAIL PROTECTED]> wrote:
> Fabian Braennstroem wrote:
>> Hi,
>> 
>> I have a 'simple' problem with a multidimension array in a
>> for loop. It looks like this:
>> 
>> wert= zeros([127,2])
>> wert1= zeros(127)
>> m=1
>> l=1
>> 
>> for pos in [pos1,pos2,pos3]: 
>> for i in range(1,125):
>> wert[l,m]= 
>> probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
>> #wert1[i]= 
>> probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i);
>> m=m+1;
>> l=l+1;
>> 
>> It works for the 1D 'wert1'. Does anyone have an idea? 
>
> Oy vey.
>
> So the first time through, you are setting the second column of wert. Then l
> (btw, never, ever use lower-case "l" as a single-letter variable name; it 
> looks
> like "1") gets incremented to 2, which would try to put data into the third
> column of wert. However, wert only has two columns.

Thanks! I misunderstood the declaration of a multid-dim
array; it works now.
>
> Are you aware that numpy array indices start with 0, not 1?
>
> You will probably want to ask numpy questions on the numpy-discussion mailing 
> list:
>
>   http://www.scipy.org/Mailing_Lists

I thought a simple for loop-array-declaration question would
fit in this group ... it actually help for this simple
problem. Thanks!

Greetings!
 Fabian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with array and for loop

2006-05-10 Thread Robert Kern
Fabian Braennstroem wrote:
> Hi Robert,
> 
> * Robert Kern <[EMAIL PROTECTED]> wrote:

>>Are you aware that numpy array indices start with 0, not 1?
>>
>>You will probably want to ask numpy questions on the numpy-discussion mailing 
>>list:
>>
>>  http://www.scipy.org/Mailing_Lists
> 
> I thought a simple for loop-array-declaration question would
> fit in this group ... it actually help for this simple
> problem. Thanks!

When you have an issue with a certain package, and that package has a dedicated
mailing list, you will usually a get a much better response on that list instead
of a general one. While I usually read comp.lang.python every day and try to
answer all numpy and scipy questions that come by, I really prefer to see these
questions on the appropriate lists.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Mitja Trampus
[EMAIL PROTECTED] wrote:

> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
> 
>   for i in c if :
>   print i*2

Maybe there's been a PEP, don't really know...
Currently, the only sensible alternative is what you've written below:

> The available equivalent
> feels a bit awkward:
> 
>   for i in c:
>   if :
>   print i*2


This indeed doesn't look nice, especially if you've got lots of code instead of 
just 
print. An alternative which avoids double indentation is

for i in c:
if not : continue
print i*2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Thank you for replying, Mitja! That *is* a nice alternative.

Do you think it's a good idea to ask on comp.python.devel if they would
be interested in a PEP about this (provided there is none)?

Cheers,
Sergey.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Grant Edwards
On 2006-03-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I apologize if this was brought up before, I couldn't find any "prior
> art" :-).
> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
>
>   for i in c if :
>   print i*2
>
> ...because it's similar to the list comprehension construct:
>
>   [i*2 for i in c if ]
> -
>
> Is this the intended difference in constructs? The available equivalent
> feels a bit awkward:
>
>   for i in c:
>   if :
>   print i*2

   for j in [i*2 for i in c if ]:
  print j

-- 
Grant Edwards   grante Yow!  .. I wonder if I
  at   ought to tell them about my
   visi.comPREVIOUS LIFE as a COMPLETE
   STRANGER?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Ben Finney
[EMAIL PROTECTED] writes:

> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
>
>   for i in c if :
>   print i*2
>
> ...because it's similar to the list comprehension construct:
>
>   [i*2 for i in c if ]

Why not combine the two:

for i in [j for j in c if ]:
print i*2

-- 
 \   "I got food poisoning today. I don't know when I'll use it."  |
  `\  -- Steven Wright |
_o__)  |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
> Why not combine the two:

I guess because (at least in source code) you're doing a loop twice
:-). I don't know what a compiler would do. I think though that the
"for i in c if test:" construct is more readable and maybe can even be
better optimized.
Thanks!

Sergey.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread John Zenger
Rather than a list comprehension, it would be faster and more 
memory-efficient to use a generator comprehension.  Just change the 
square brackets to parentheses:

 for j in (i*2 for i in c if ):
print j


Grant Edwards wrote:
> On 2006-03-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>>Hi All,
>>
>>I apologize if this was brought up before, I couldn't find any "prior
>>art" :-).
>>On more than one occasion, I found myself wanting to use a "conditional
>>loop" like this (with "Invalid syntax" error, of course):
>>
>>  for i in c if :
>>  print i*2
>>
>>...because it's similar to the list comprehension construct:
>>
>>  [i*2 for i in c if ]
>>-
>>
>>Is this the intended difference in constructs? The available equivalent
>>feels a bit awkward:
>>
>>  for i in c:
>>  if :
>>  print i*2
> 
> 
>for j in [i*2 for i in c if ]:
>   print j
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Why not combine the two:
>
> I guess because (at least in source code) you're doing a loop twice
> :-). I don't know what a compiler would do. I think though that the
> "for i in c if test:" construct is more readable and maybe can even be
> better optimized.

 There are also the filter and ifilter functions:

for i in filter(testfunc, c):

tjr



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-27 Thread s . lipnevich
I think I like generator comprehension in this case better than either
list comprehension or a filter because both of the latter create a new
full "result list" before the loop even begins. At least I suppose they
do. Also, I think Mitja's suggestion "if not : continue" and
Terry's filter function are more readable than comprehensions.
It's not a contest though :-), all these variants are great, thank you
all!
Do you think this discussion is a proof that the following principle
got violated, or do you think that "loop with condition" is not such an
atomic thing to be subject to this: "There should be one -- and
preferably only one -- obvious way to do it."
Cheers,

Sergey.

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >