Re: Map vs. List Comprehensions (was lint warnings)

2011-02-16 Thread Steven D'Aprano
On Tue, 15 Feb 2011 18:55:50 -0500, Gerald Britton wrote:

 So, what's the feeling out there?  Go with map and the operators or
 stick with the list comps?

Stick to whatever feels and reads better at the time.

Unless you have profiled your code, and determined that the map or list 
comp was the bottleneck, who cares if you save half a nanosecond per 
iteration?

map clearly loses badly in the old-time idiom:

map(lambda x: x+1, seq)

or similar. That's the only time I'd just flat out say, avoid map in 
favour of a list comprehension. Otherwise, the performance difference is 
likely to be trivial, as is the difference in length of code. Use 
whichever you like.

I personally appreciate the ability to treat map as a primitive (map 
this function over this data) rather than caring about the mechanics of 
iteration (iterate over data, applying this function to each element in 
turn), so I often use map. But I use list comps even more often.



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


Re: Map Linux locale codes to Windows locale codes?

2010-12-14 Thread Flávio Lisbôa
You could look into the windows registry, the key
HKLM\SYSTEM\CurrentControlSet\Control\Nls has all the supported LCID's
listed. If not, you could simply get the codepage provided by
locale.setlocale(), e.g.:

import locale
print(locale.setlocale(locale.LC_ALL, ))

prints Portuguese_Brazil.1252 for me. That codepage part is actually a
LCID, that you can then cross-reference with any LCID list on the net. I
guess there may be a way to look that up entirely from the registry,
including getting a short reference or ANSI codepage from the LCID, but i
doubt it'd be portable at all.

Maybe what you should do is to make up a dict with known LCID's and their
corresponding language codes. I don't know of any way to do this
automatically in python...

Take a look at http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

2010/12/14 pyt...@bdurham.com

 Is there a way to map Linux locale codes to Windows locale codes?

 Windows has locale codes like 'Spanish_Mexico'. We would like to use the
 more ISO compliant 'es_MX' locale format under Windows.

 Is there a resource or API that might help us with this mapping?

 Babel is not an option for us since we're using Python 2.7.

 Thank you,
 Malcolm

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


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


Re: map is useless!

2010-06-07 Thread James Mills
On Mon, Jun 7, 2010 at 9:20 AM, Steven D'Aprano
st...@remove-this-cybersource.com.au wrote:
 Ruby has a very nice map

 I'm thrilled for them. Personally I think the syntax is horrible.

I concur!

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


Re: map is useless!

2010-06-06 Thread James Mills
On Mon, Jun 7, 2010 at 1:16 AM, rantingrick rantingr...@gmail.com wrote:
 So can anyone explain this poor excuse for a map function? Maybe GVR
 should have taken it out in 3.0?  *scratches head*

Let me get this straight... You're complaining about some trivial
code you've written and a 0.002 or less execution time ?

I must be missing something!

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


Re: map is useless!

2010-06-06 Thread Roald de Vries

On Jun 6, 2010, at 5:16 PM, rantingrick wrote:

Everyone knows i'm a Python fanboy so nobody can call me a troll for
this...

Python map is just completely useless. For one it so damn slow why
even bother putting it in the language? And secondly, the total girl-
man weakness of lambda renders it completely mute!

Ruby has a very nice map


[1,2,3].map{|x| x.to_s}


Have not done any benchmarking but far more useful from the
programmers POV. And that really stinks because map is such a useful
tool it's a shame to waste it. Here are some test to back up the rant.



import time
def test1():

l = range(1)
t1 = time.time()
map(lambda x:x+1, l)
t2= time.time()
print t2-t1



def test2():

l = range(1)
t1 = time.time()
for x in l:
x + 1
t2 = time.time()
print t2-t1



test1()

0.0029346008

test2()

0.00027520752

def test3():

l = range(1)
t1 = time.time()
map(str, l)
t2= time.time()
print t2-t1



def test4():

l = range(1)
t1 = time.time()
for x in l:
str(x)
t2= time.time()
print t2-t1



test3()

0.0032098083

test4()

0.0034850159




So can anyone explain this poor excuse for a map function? Maybe GVR
should have taken it out in 3.0?  *scratches head*


Use list comprehension. It's nicer than Ruby's map:

[x.to_s for x in 1, 2, 3]

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


Re: map is useless!

2010-06-06 Thread Duncan Booth
rantingrick rantingr...@gmail.com wrote:

 Python map is just completely useless. For one it so damn slow why
 even bother putting it in the language? And secondly, the total girl-
 man weakness of lambda renders it completely mute!

Do you realise that you don't have to use lambda? If you need more than a 
single expression just create a named function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Alain Ketterlin
rantingrick rantingr...@gmail.com writes:

 Python map is just completely useless. [...]

 import time
 def test1():
   l = range(1)
   t1 = time.time()
   map(lambda x:x+1, l)
   t2= time.time()
   print t2-t1
 def test2():
   l = range(1)
   t1 = time.time()
   for x in l:
   x + 1
   t2 = time.time()
   print t2-t1

 test1()
 0.0029346008
 test2()
 0.00027520752
 def test3():

Well, not building the resulting list saves some time. But even if you
do r.append(x+1) map appears to be slower...

Try this:

def test3():
l = range(1)
t1 = time.time()
[ x+1 for x in l]
t2 = time.time()
print t2-t1

I've not used map since I learned about list comprehensions.

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


Re: map is useless!

2010-06-06 Thread Shashwat Anand
map is not needed. LC is great :D

On Sun, Jun 6, 2010 at 10:32 PM, Alain Ketterlin 
al...@dpt-info.u-strasbg.fr wrote:

 rantingrick rantingr...@gmail.com writes:

  Python map is just completely useless. [...]

  import time
  def test1():
l = range(1)
t1 = time.time()
map(lambda x:x+1, l)
t2= time.time()
print t2-t1
  def test2():
l = range(1)
t1 = time.time()
for x in l:
x + 1
t2 = time.time()
print t2-t1
 
  test1()
  0.0029346008
  test2()
  0.00027520752
  def test3():

 Well, not building the resulting list saves some time. But even if you
 do r.append(x+1) map appears to be slower...

 Try this:

 def test3():
l = range(1)
t1 = time.time()
 [ x+1 for x in l]
 t2 = time.time()
print t2-t1

 I've not used map since I learned about list comprehensions.

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

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


Re: map is useless!

2010-06-06 Thread rantingrick
On Jun 6, 12:02 pm, Alain Ketterlin al...@dpt-info.u-strasbg.fr
wrote:
 rantingrick rantingr...@gmail.com writes:
 I've not used map since I learned about list comprehensions.

Thats has been my experienced also. Actually i've been at Python for
O... about 2 years now and i don't think i've ever used map in a
script even one time until a month or so ago. After a few unit tests
it seems i was right all along. But the funny thing is in other
languages i use map all the time. It's just too awkward in Python and
i wish it were not so... Oh well?

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


Re: map is useless!

2010-06-06 Thread Lie Ryan
On 06/07/10 03:22, rantingrick wrote:
 On Jun 6, 12:02 pm, Alain Ketterlin al...@dpt-info.u-strasbg.fr
 wrote:
 rantingrick rantingr...@gmail.com writes:
 I've not used map since I learned about list comprehensions.
 
 Thats has been my experienced also. Actually i've been at Python for
 O... about 2 years now and i don't think i've ever used map in a
 script even one time until a month or so ago. After a few unit tests
 it seems i was right all along. But the funny thing is in other
 languages i use map all the time. It's just too awkward in Python and
 i wish it were not so... Oh well?

In the most naive uses, map appears to have no advantage over list
comprehension; but one thing that map can do that list comprehension
still can't do without a walk around the park:

def foo(func, args):
g = lambda x: x+1
return [func(g, x) for x in args]

foo(map, [[4, 6, 3], [6, 3, 2], [1, 3, 5]])

I'm not going to argue how often that would be useful though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Thomas Jollans
On 06/06/2010 05:16 PM, rantingrick wrote:
 So can anyone explain this poor excuse for a map function? Maybe GVR
 should have taken it out in 3.0?  *scratches head*

   
Speaking of Py3k: map no longer builds lists. What once was map is no
more, what once was itertools.imap is now map.

Sometimes Py2.x map is useful, sometimes list comprehension is nicer.
Sometimes Py3.x map / Py2.x itertools.imap is useful, sometimes
generator expressions are more elegant.



Same goes for filter, by the way.

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


Re: map is useless!

2010-06-06 Thread Richard Thomas
Python's map has the useful feature that nobody is in any doubt about
what it does. I don't know much about Ruby I have to say but looking
at that piece of syntax you gave I had no idea how to interpret it.
Anyway, I looked it up.

Calling an method on each of a collection of objects is best
accomplished without map. It is semantically different to mapping a
function over a set.

As far as speed goes, Python has an overhead for making a function
call which means that its often faster to use a for loop. It seems
like a rather small difference in speed though and if what you want to
do is semantically a map you should write it is a map thereby making
your code read like what it does. If it later turns out to slow down
your program too much optimise it then.

In your second pair of tests the map is faster because str is a
builtin and doesn't have that overhead. Additionally the name 'str' is
only looked up once rather than 1 times. :-)

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


Re: map is useless!

2010-06-06 Thread D'Arcy J.M. Cain
On Mon, 07 Jun 2010 05:27:43 +1000
Lie Ryan lie.1...@gmail.com wrote:
 In the most naive uses, map appears to have no advantage over list
 comprehension; but one thing that map can do that list comprehension
 still can't do without a walk around the park:
 
 def foo(func, args):
 g = lambda x: x+1
 return [func(g, x) for x in args]
 
 foo(map, [[4, 6, 3], [6, 3, 2], [1, 3, 5]])

foo = lambda x: [y + 1 for y in x]
[foo(x) for x in [[4, 6, 3], [6, 3, 2], [1, 3, 5]]]

Didn't seem like such a long walk.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Lie Ryan
On 06/07/10 05:54, D'Arcy J.M. Cain wrote:
 On Mon, 07 Jun 2010 05:27:43 +1000
 Lie Ryan lie.1...@gmail.com wrote:
 In the most naive uses, map appears to have no advantage over list
 comprehension; but one thing that map can do that list comprehension
 still can't do without a walk around the park:

 def foo(func, args):
 g = lambda x: x+1
 return [func(g, x) for x in args]

 foo(map, [[4, 6, 3], [6, 3, 2], [1, 3, 5]])
 
 foo = lambda x: [y + 1 for y in x]
 [foo(x) for x in [[4, 6, 3], [6, 3, 2], [1, 3, 5]]]
 
 Didn't seem like such a long walk.
 

that's because you're simplifying the problem, the correct walk is:

def foo(func, args):
g = lambda x: x+1
return [func(g, x) for x in args]

foo((lambda g, a: [g(x) for x in a]), [[4, 6, 3], [6, 3, 2], [1, 3, 5]])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread rantingrick
On Jun 6, 2:48 pm, Richard Thomas chards...@gmail.com wrote:
 Python's map has the useful feature that nobody is in any doubt about
 what it does. I don't know much about Ruby I have to say but looking
 at that piece of syntax you gave I had no idea how to interpret it.
 Anyway, I looked it up.

Well Ruby likes to pass block in the form { ...expression... }. I
don't really care for the braces but the map is more natural in Ruby

 array = [1,2,3].map{|x| x.to_s}
 array
['1', '2', '3']
 array.length
3
 'abc'.map{|x| x.upcase}.join
'ABC'

#-- as in python you do the nested thing --#

 lst = map(str, [1,2,3])
 lst
['1', '2', '3']
 len(lst)
3
 ''.join(map(string.upper, 'abc'))
'ABC'

Thats the only thing that bother me about Python. But in Ruby the
sky's the limit since you pass a block. And no need for that clunky
lambda.

I think Guido and Matz need to set down for a cup of joe fire up their
interpretors and exchange thoughts about language design. Some awesome
synergy could come of it and maybe even create the next best
language.

Guido can teach Matz about the importance of forced indention over
braces, docstrings, command line help, explicitly calling functions/
method, perfect keyword naming, __specialmethodnames__, the Python
Zen! And Matz can show Guido how to build a better lambda and map
functions and more syntactically correct OOP style.

Just ideas folks ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Terry Reedy

On 6/6/2010 11:16 AM, rantingrick wrote:

Everyone knows i'm a Python fanboy so nobody can call me a troll for
this...


Non sequitor. It depends on your intention in posting this...


Python map is just completely useless. For one it so damn slow


Posting invalid speed comparisons stacked against the feature you are 
dissing is either trollish or lame.


 why even bother putting it in the language?

Map was put into the language about a decade before comprehensions and, 
I believe, zip. It encapsulates a basic functional programming idiom.


Consider the following snippet: (in 2.x, delete 'list(' and ...')'):

from operator import add
l1 = range(10)
l2 = range(15,30)
print(list(map(add, l1, l2)))
# [15, 17, 19, 21, 23, 25, 27, 29, 31, 33]

Now replace map with a for loop, no zip or listcomp or genexp allowed.
Time how long it takes. Do you get it right the first time, as I did 
with the above?. Your replacememt may or may not *run* faster, but even 
if so, it will hardly be enough to make much different in most uses.



Maybe GVR should have taken it out in 3.0?


That may have been considered, but map is shorter than the alternative, 
some prefer it stylistically, it can be passed as a function argument 
(including to functool.partial), and its removal would have broken code 
without much gain. It is also handy for explaing generator expressions 
and comprehensions.


Terry Jan Reedy




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


Re: map is useless!

2010-06-06 Thread Steven D'Aprano
On Sun, 06 Jun 2010 08:16:02 -0700, rantingrick wrote:

 Everyone knows i'm a Python fanboy so nobody can call me a troll for
 this...

The first rule of trolling is, always deny being a troll, no matter how 
obvious the trolling. But on the chance I'm wrong, and for the benefit of 
others, your tests don't measure what you think they are measuring and 
consequently your results are invalid. Read on.


 Python map is just completely useless. For one it so damn slow why even
 bother putting it in the language? And secondly, the total girl- man
 weakness of lambda renders it completely mute!

Four trolls in three sentences. Way to go fanboy.

(1) Completely useless? It can't do *anything*?

(2) Slow compared to what?

(3) Are you implying that map relies on lambda?

(4) What's wrong with lambda anyway?

By the way, nice sexist description there. Girl-man weakness indeed. 
Does your mum know that you are so contemptuous about females?



 Ruby has a very nice map

I'm thrilled for them. Personally I think the syntax is horrible.

 
 [1,2,3].map{|x| x.to_s}
 
 Have not done any benchmarking 

... but by counting under my breath while the code runs, I'm POSITIVE 
Ruby is much faster that Python!

By complaining about Python being too slow while admitting that you 
haven't actually tested the speed of your preferred alternative, you have 
*negative* credibility.


 but far more useful from the programmers
 POV. And that really stinks because map is such a useful tool it's a
 shame to waste it. Here are some test to back up the rant.
 
 
 import time
 def test1():
   l = range(1)
   t1 = time.time()
   map(lambda x:x+1, l)
   t2= time.time()
   print t2-t1

That's a crappy test.

(1) You include the cost of building a new function each time.

(2) You make no attempt to protect against the inevitable variation in 
speed caused by external processes running on a modern multi-process 
operating system.

(3) You are reinventing the wheel (badly) instead of using the timeit 
module.


 def test2():
   l = range(1)
   t1 = time.time()
   for x in l:
   x + 1
   t2 = time.time()
   print t2-t1

The most obvious difference is that in test1, you build a 10,000 item 
list, while in test2, you don't. And sure enough, not building a list is 
faster than building a list:

 test1()
 0.0029346008
 test2()
 0.00027520752



 def test3():
   l = range(1)
   t1 = time.time()
   map(str, l)
   t2= time.time()
   print t2-t1
 
 
 def test4():
   l = range(1)
   t1 = time.time()
   for x in l:
   str(x)
   t2= time.time()
   print t2-t1
 
 
 test3()
 0.0032098083
 test4()
 0.0034850159


Look ma, not building a list is still faster than building a list!


 So can anyone explain this poor excuse for a map function? Maybe GVR
 should have taken it out in 3.0?  *scratches head*


So, let's do some proper tests. Using Python 2.6 on a fairly low-end 
desktop, and making sure all the alternatives do the same thing:

 from timeit import Timer
 t1 = Timer('map(f, L)', 'f = lambda x: x+1; L = range(1)')
 t2 = Timer('''accum = []
... for item in L:
... accum.append(f(item))
...
... ''', 'f = lambda x: x+1; L = range(1)')

 min(t1.repeat(number=1000))
3.5182700157165527
 min(t2.repeat(number=1000))
6.702117919921875

For the benefit of those who aren't used to timeit, the timings at the 
end are the best-of-three of repeating the test code 1000 times. The time 
per call to map is 3.5 milliseconds compared to 6.7 ms for unrolling it 
into a loop and building the list by hand. map is *much* faster.

How does it compare to a list comprehension? The list comp can avoid a 
function call and do the addition inline, so it will probably be 
significantly faster:

 t3 = Timer('[x+1 for x in  L]', L = range(1))
 min(t3.repeat(number=1000))
2.0786428451538086

And sure enough it is. But when you can't avoid the function call, the 
advantage shifts back to map:

 t4 = Timer('map(str, L)', L = range(1))
 t5 = Timer('[str(x) for x in  L]', L = range(1))
 min(t4.repeat(number=1000))
3.8360331058502197
 min(t5.repeat(number=1000))
6.6693520545959473



Lessons are:

(1) If you're going to deny being a troll, avoid making inflammatory 
statements unless you can back them up.

(2) Understand what you are timing, and don't compare apples to snooker 
balls just because they're both red.

(3) Timing tests are hard to get right. Use timeit.

(4) map is plenty fast.


Have a nice day.


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


Re: map is useless!

2010-06-06 Thread D'Arcy J.M. Cain
On Mon, 07 Jun 2010 05:59:02 +1000
Lie Ryan lie.1...@gmail.com wrote:
  foo = lambda x: [y + 1 for y in x]
  [foo(x) for x in [[4, 6, 3], [6, 3, 2], [1, 3, 5]]]
  
  Didn't seem like such a long walk.
  
 
 that's because you're simplifying the problem, the correct walk is:

Well, since it gives the same answer and you didn't actually state the
problem I'm not sure how you can make that statement.

Show me the unit test that defines the problem.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Lie Ryan
On 06/07/10 09:56, D'Arcy J.M. Cain wrote:
 On Mon, 07 Jun 2010 05:59:02 +1000
 Lie Ryan lie.1...@gmail.com wrote:
 foo = lambda x: [y + 1 for y in x]
 [foo(x) for x in [[4, 6, 3], [6, 3, 2], [1, 3, 5]]]

 Didn't seem like such a long walk.


 that's because you're simplifying the problem, the correct walk is:
 
 Well, since it gives the same answer and you didn't actually state the
 problem I'm not sure how you can make that statement.
 
 Show me the unit test that defines the problem.

that you must use foo() and you can't change foo() (since foo is very
complex), and you give the same result as the original solution.


def solution(lst):
# make changes here only
return foo(map, lst)

def foo(func, args):
g = lambda x: x+1
return [func(g, x) for x in args]

import unittest
@unittest.FunctionTestCase
def test():
lst = [[4, 6, 3], [6, 3, 2], [1, 3, 5]]
ans = [[5, 7, 4], [7, 4, 3], [2, 4, 6]]
test.assertEqual(solution(lst), ans)

test.runTest()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread D'Arcy J.M. Cain
On Mon, 07 Jun 2010 10:16:19 +1000
Lie Ryan lie.1...@gmail.com wrote:
 On 06/07/10 09:56, D'Arcy J.M. Cain wrote:
  Show me the unit test that defines the problem.
 
 that you must use foo() and you can't change foo() (since foo is very
 complex), and you give the same result as the original solution.

I reject the artificial restriction.  If foo has a proper unit test I
can refactor it any time I want.  If it doesn't then step one is to add
the missing unit tests.

In any case, the problem should be stated in terms of input and
output.  That's the client requrements.  Enforcing the solution is a
homework assignment, not a real requirements specification.

 def solution(lst):
 # make changes here only
 return foo(map, lst)

OK, so I can make changes here.  My change would not use foo.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map is useless!

2010-06-06 Thread Carl Banks
On Jun 6, 8:16 am, rantingrick rantingr...@gmail.com wrote:
 Everyone knows i'm a Python fanboy so nobody can call me a troll for
 this...

1. I don't remember you so I don't know if you're a Python fanboy or
not
2. If you act like a troll I'll call you one even if you are Python
fanboy

Actually, your post only came off as slightly trollish, so you have
that.


 Python map is just completely useless. For one it so damn slow why
 even bother putting it in the language? And secondly, the total girl-
 man weakness of lambda renders it completely mute!

 Ruby has a very nice map

  [1,2,3].map{|x| x.to_s}

 Have not done any benchmarking but far more useful from the
 programmers POV. And that really stinks because map is such a useful
 tool it's a shame to waste it. Here are some test to back up the rant.

  import time
  def test1():

         l = range(1)
         t1 = time.time()
         map(lambda x:x+1, l)
         t2= time.time()
         print t2-t1

  def test2():

         l = range(1)
         t1 = time.time()
         for x in l:
                 x + 1
         t2 = time.time()
         print t2-t1

  test1()
 0.0029346008
  test2()
 0.00027520752
  def test3():

         l = range(1)
         t1 = time.time()
         map(str, l)
         t2= time.time()
         print t2-t1

  def test4():

         l = range(1)
         t1 = time.time()
         for x in l:
                 str(x)
         t2= time.time()
         print t2-t1



  test3()
 0.0032098083
  test4()
 0.0034850159

 So can anyone explain this poor excuse for a map function? Maybe GVR
 should have taken it out in 3.0?  *scratches head*

Since you claim to be a Python Fanboy, you probably know that you can
type import this at a Python prompt, and it brings up a list of
principles that guide the design of the language.

Tell me, do you see Fast is better than slow in that list?  No?
Well that's your answer.

(The technical answer is that map isn't slow, function call overhead
is.)


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


Re: map is useless!

2010-06-06 Thread Terry Reedy

On 6/6/2010 7:20 PM, Steven D'Aprano wrote:

On Sun, 06 Jun 2010 08:16:02 -0700, rantingrick wrote:


Everyone knows i'm a Python fanboy so nobody can call me a troll for
this...


The first rule of trolling is, always deny being a troll, no matter how
obvious the trolling.


Such as the exagerated-claim subject that ends with an exclamation!


But on the chance I'm wrong, and for the benefit of
others, your tests don't measure what you think they are measuring and
consequently your results are invalid. Read on.


+1 on the rest. Thanks for posting it. I have nothing more to add.

Terry Jan Reedy



Python map is just completely useless. For one it so damn slow why even
bother putting it in the language? And secondly, the total girl- man
weakness of lambda renders it completely mute!


Four trolls in three sentences. Way to go fanboy.

(1) Completely useless? It can't do *anything*?

(2) Slow compared to what?

(3) Are you implying that map relies on lambda?

(4) What's wrong with lambda anyway?

By the way, nice sexist description there. Girl-man weakness indeed.
Does your mum know that you are so contemptuous about females?




Ruby has a very nice map


I'm thrilled for them. Personally I think the syntax is horrible.



[1,2,3].map{|x| x.to_s}


Have not done any benchmarking


... but by counting under my breath while the code runs, I'm POSITIVE
Ruby is much faster that Python!

By complaining about Python being too slow while admitting that you
haven't actually tested the speed of your preferred alternative, you have
*negative* credibility.



but far more useful from the programmers
POV. And that really stinks because map is such a useful tool it's a
shame to waste it. Here are some test to back up the rant.



import time
def test1():

l = range(1)
t1 = time.time()
map(lambda x:x+1, l)
t2= time.time()
print t2-t1


That's a crappy test.

(1) You include the cost of building a new function each time.

(2) You make no attempt to protect against the inevitable variation in
speed caused by external processes running on a modern multi-process
operating system.

(3) You are reinventing the wheel (badly) instead of using the timeit
module.



def test2():

l = range(1)
t1 = time.time()
for x in l:
x + 1
t2 = time.time()
print t2-t1


The most obvious difference is that in test1, you build a 10,000 item
list, while in test2, you don't. And sure enough, not building a list is
faster than building a list:


test1()

0.0029346008

test2()

0.00027520752





def test3():

l = range(1)
t1 = time.time()
map(str, l)
t2= time.time()
print t2-t1



def test4():

l = range(1)
t1 = time.time()
for x in l:
str(x)
t2= time.time()
print t2-t1



test3()

0.0032098083

test4()

0.0034850159



Look ma, not building a list is still faster than building a list!



So can anyone explain this poor excuse for a map function? Maybe GVR
should have taken it out in 3.0?  *scratches head*



So, let's do some proper tests. Using Python 2.6 on a fairly low-end
desktop, and making sure all the alternatives do the same thing:


from timeit import Timer
t1 = Timer('map(f, L)', 'f = lambda x: x+1; L = range(1)')
t2 = Timer('''accum = []

... for item in L:
... accum.append(f(item))
...
... ''', 'f = lambda x: x+1; L = range(1)')


min(t1.repeat(number=1000))

3.5182700157165527

min(t2.repeat(number=1000))

6.702117919921875

For the benefit of those who aren't used to timeit, the timings at the
end are the best-of-three of repeating the test code 1000 times. The time
per call to map is 3.5 milliseconds compared to 6.7 ms for unrolling it
into a loop and building the list by hand. map is *much* faster.

How does it compare to a list comprehension? The list comp can avoid a
function call and do the addition inline, so it will probably be
significantly faster:


t3 = Timer('[x+1 for x in  L]', L = range(1))
min(t3.repeat(number=1000))

2.0786428451538086

And sure enough it is. But when you can't avoid the function call, the
advantage shifts back to map:


t4 = Timer('map(str, L)', L = range(1))
t5 = Timer('[str(x) for x in  L]', L = range(1))
min(t4.repeat(number=1000))

3.8360331058502197

min(t5.repeat(number=1000))

6.6693520545959473



Lessons are:

(1) If you're going to deny being a troll, avoid making inflammatory
statements unless you can back them up.

(2) Understand what you are timing, and don't compare apples to snooker
balls just because they're both red.

(3) Timing tests are hard to get right. Use timeit.

(4) map is plenty fast.


Have a nice day.





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


Re: map, index

2010-03-28 Thread Duncan Booth
Luis Quesada l.ques...@4c.ucc.ie wrote:

 Is there a way 
 of writing the following without using zip:
  map(lambda (id,v):id*v,zip(range(len(L)),L))

[ id*v for id,v in enumerate(L) ]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map, index

2010-03-28 Thread Luis Quesada

Duncan Booth wrote:

Luis Quesada l.ques...@4c.ucc.ie wrote:

Is there a way 
of writing the following without using zip:

 map(lambda (id,v):id*v,zip(range(len(L)),L))


[ id*v for id,v in enumerate(L) ]

Cool! Thanks!
Cheers,
Luis
--
http://mail.python.org/mailman/listinfo/python-list


Re: map, index

2010-03-28 Thread Paul Rubin
Luis Quesada l.ques...@4c.ucc.ie writes:
 [ id*v for id,v in enumerate(L) ]
 Cool! Thanks!

If you really want to write that in pointfree style (untested):

   import itertools, operator
   ...
   itertools.starmap(operator.mul, enumerate(L))

For your other question, you could probably do something ugly
with ifilter, but it's not worth it.  

For the style of programming you're interested in, you should read the
docs for the itertools module.  Python culture in general tends to
not be that fond of heavy use of HOF's, since it's very easy to make
mistakes with its iterator protocol and with its dynamic type system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map, index

2010-03-28 Thread Luis Quesada

Paul Rubin wrote:

Luis Quesada l.ques...@4c.ucc.ie writes:

[ id*v for id,v in enumerate(L) ]

Cool! Thanks!


If you really want to write that in pointfree style (untested):

   import itertools, operator
   ...
   itertools.starmap(operator.mul, enumerate(L))

For your other question, you could probably do something ugly
with ifilter, but it's not worth it.  


For the style of programming you're interested in, you should read the
docs for the itertools module.  Python culture in general tends to
not be that fond of heavy use of HOF's, since it's very easy to make
mistakes with its iterator protocol and with its dynamic type system.

Thanks a lot for the pointer.
Python is rather cool indeed.
Cheers,
Luis
--
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-09-02 Thread elsa
On Aug 31, 11:44 pm, Hendrik van Rooyen hend...@microcorp.co.za
wrote:
 On Monday 31 August 2009 11:31:34 Piet van Oostrum wrote:

  But ultimately it is also very much a matter of taste, preference and
  habit.

 This is true, but there is another reason that I posted - I have noticed that
 there seems to be a tendency amongst newcomers to the group to go to great
 lengths to find something that will do exactly what they want, irrespective
 of the inherent complexity or lack thereof of that which they are trying to
 do.

 Now I cannot understand why this is - one could say that it is caused by an
 eagerness to understand all the corners of the tool that is python, but
 somehow it does not feel like that to me - I see it almost as a crisis of
 confidence - as if the newbie lacks the self confidence to believe that he or
 she is capable of doing anything independently.  

 So whenever I can, I try to encourage people to just do it their way, and to
 see what happens, and to hack using the interactive interpreter, to build
 confidence by experimenting and making mistakes, and realizing that when you
 have made a mistake, it is not the end of the world,  - you can fix it and
 move on.

 Don't know if this rant makes any sense...

 - Hendrik

in my own defense - firstly, I was able to implement what I wanted to
do with loops, and I used this to solve the problem I needed to.

However, by asking *why* map didn't work, I now understand how map
works, what contexts it may indeed be useful for, and what the
alternatives are. To boot, you have all given me about 10 different
ways of solving the problem, some of which use prettier (and probably
faster) code than the loops I wrote...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-09-02 Thread Hendrik van Rooyen
On Wednesday 02 September 2009 09:38:20 elsa wrote:


 in my own defense - firstly, I was able to implement what I wanted to
 do with loops, and I used this to solve the problem I needed to.

My rant was not intended as a personal attack - far from it - if all the 
people on this list were to post such clear questions as you did, it would be 
an even greater pleasure to participate in than it is.


 However, by asking *why* map didn't work, I now understand how map
 works, what contexts it may indeed be useful for, and what the
 alternatives are. To boot, you have all given me about 10 different
 ways of solving the problem, some of which use prettier (and probably
 faster) code than the loops I wrote...

Good. So you will soon be here answering questions too.  When you do that, you 
really learn, as long as you do not feel slighted when people point out 
better (or merely different) solutions than yours.  We all help each other 
here, and sometimes we even crack obscure (and not so obscure) jokes.

- Hendrik

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


Re: map

2009-09-01 Thread alex23
Piet van Oostrum p...@cs.uu.nl wrote:
 [myFunc(elt, 'booHoo') for elt in myList] is also a good candidate and
 in this case I think it is preferable to both the loop and the map with
 a partial or lambda in terms of clarity.

From memory, a listcomp with a non-builtin function is also faster
than map with the same.

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


Re: map

2009-09-01 Thread Jan Kaliszewski

Another possibilities, if you really *desire* to use map()
and not list-comprehension (I'd prefer the latter), are:

# Python 2.x:
map(func, mylist, itertools.repeat('booHoo', len(mylist)))

# Python 3.x, where map() works like Py2.x's itertools.imap():
list(map(func, mylist, itertools.repeat('booHoo')))

Cheers,
*j

--
Jan Kaliszewski (zuo) z...@chopin.edu.pl
--
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-08-31 Thread Hendrik van Rooyen
On Monday 31 August 2009 06:55:52 elsa wrote:

8 - map question 


 (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList
 [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want
 to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc
 (myList[2], 'woo') some other time).

Here is some heretical advice:

Do not use stuff like map and reduce unless they fit what you want to do 
perfectly, and JustWorks the first time.

You have a very clear idea of what you want to do, so why do you not just 
simply write something to do it?

something like this (untested):

def woofer(thefunc,thelist,thething):
theanswers = []
for x in thelist:
theanswers.append(thefunc(x,thething))
return theanswers

And the advantage is that you do not have to remember what map does...

*ducks away from the inevitable flames*

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


Re: map

2009-08-31 Thread Gabriel Genellina
En Mon, 31 Aug 2009 05:43:07 -0300, Hendrik van Rooyen  
hend...@microcorp.co.za escribió:

On Monday 31 August 2009 06:55:52 elsa wrote:


(Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList
[1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want
to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc
(myList[2], 'woo') some other time).


Here is some heretical advice:

Do not use stuff like map and reduce unless they fit what you want to do
perfectly, and JustWorks the first time.


I think of that advice as orthodox, not heretical! (functional guys  
are minority here...)



You have a very clear idea of what you want to do, so why do you not just
simply write something to do it?

something like this (untested):

def woofer(thefunc,thelist,thething):
theanswers = []
for x in thelist:
theanswers.append(thefunc(x,thething))
return theanswers

And the advantage is that you do not have to remember what map does...


This block:

theanswers = []
for x in thelist:
theanswers.append(thefunc(x,thething))

is formally the same as this one:

theanswers = [thefunc(x,thething) for x in thelist]

but the list comprehension is faster. So the function becomes:

def woofer(thefunc,thelist,thething):
return [thefunc(x,thething) for x in thelist]

and may be inlined (it's usually easier to read).


*ducks away from the inevitable flames*


*fights back to back with you against heretics*

--
Gabriel Genellina

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


Re: map

2009-08-31 Thread Piet van Oostrum
 Hendrik van Rooyen hend...@microcorp.co.za (HvR) wrote:

HvR On Monday 31 August 2009 06:55:52 elsa wrote:
HvR 8 - map question 

 
 (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList
 [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want
 to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc
 (myList[2], 'woo') some other time).

HvR Here is some heretical advice:

HvR Do not use stuff like map and reduce unless they fit what you want to do 
HvR perfectly, and JustWorks the first time.

HvR You have a very clear idea of what you want to do, so why do you not just 
HvR simply write something to do it?

HvR something like this (untested):

HvR def woofer(thefunc,thelist,thething):
HvR   theanswers = []
HvR   for x in thelist:
HvR   theanswers.append(thefunc(x,thething))
HvR   return theanswers

HvR And the advantage is that you do not have to remember what map does...

Map should be in every good programmer's toolbox. So (s)he presumably
knows already what map does. In order to follow your advise (s)he must
first forget what map does :=)

Agreed on the part that map shouldn't be used indiscriminately. Neither
should loops. Your woofer is much harder to follow than map, I think.

[myFunc(elt, 'booHoo') for elt in myList] is also a good candidate and
in this case I think it is preferable to both the loop and the map with
a partial or lambda in terms of clarity.

On the other hand when you just want to call a function on each element
of a list and you don't need to collect the result a simple loop is
often preferable.

But ultimately it is also very much a matter of taste, preference and habit.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-08-31 Thread Steven D'Aprano
On Mon, 31 Aug 2009 10:43:07 +0200, Hendrik van Rooyen wrote:

 Here is some heretical advice:
 
 Do not use stuff like map and reduce unless they fit what you want to do
 perfectly, and JustWorks the first time.
 
 You have a very clear idea of what you want to do, so why do you not
 just simply write something to do it?

That's not heretical advice -- that's pretty standard, vanilla, boring 
advice. It's probably good advice, if you care more about Getting the Job 
Done than about learning the language.


 And the advantage is that you do not have to remember what map does...

map() is probably the simplest, most straightforward of the functional 
tools in Python. It's harder for me to remember it's name than to 
remember what it does: it applies a function to each element of a list, 
instead of two the entire list as a single argument. Easy-peasy.

 *ducks away from the inevitable flames*

You'll have to try harder than that to get flamed :)



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


Re: map

2009-08-31 Thread Hendrik van Rooyen
On Monday 31 August 2009 11:31:34 Piet van Oostrum wrote:

 But ultimately it is also very much a matter of taste, preference and
 habit.

This is true, but there is another reason that I posted - I have noticed that 
there seems to be a tendency amongst newcomers to the group to go to great 
lengths to find something that will do exactly what they want, irrespective 
of the inherent complexity or lack thereof of that which they are trying to 
do.

Now I cannot understand why this is - one could say that it is caused by an 
eagerness to understand all the corners of the tool that is python, but 
somehow it does not feel like that to me - I see it almost as a crisis of 
confidence - as if the newbie lacks the self confidence to believe that he or 
she is capable of doing anything independently.  

So whenever I can, I try to encourage people to just do it their way, and to 
see what happens, and to hack using the interactive interpreter, to build 
confidence by experimenting and making mistakes, and realizing that when you 
have made a mistake, it is not the end of the world,  - you can fix it and 
move on.

Don't know if this rant makes any sense...

- Hendrik

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


Re: map

2009-08-31 Thread Paul Rubin
elsa kerensael...@hotmail.com writes:
 map(myFunc(b='booHoo'), myList)
 
 Why doesn't this work? is there a way to make it work?

You can use functools.partial but a listcomp might be simpler:

   list(myfunc(a, b='booHoo') for a in myList)

There is another listcomp syntax with square brackets, but I try to
avoid it because it has broken behavior (leaks the index variable) in
Python 2.x.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-08-31 Thread Nobody
On Sun, 30 Aug 2009 21:55:52 -0700, elsa wrote:

 say I have a list, myList. Now say I have a function with more than
 one argument:
 
 myFunc(a, b='None')
 
 now, say I want to map myFunc onto myList, with always the same
 argument for b, but iterating over a:
 
 map(myFunc(b='booHoo'), myList)
 
 Why doesn't this work?

You're passing the result of (incorrectly) calling myFunc to map(), but
you need to pass a function.

 is there a way to make it work?

If you need to construct a simple function on-the-fly, you can use a
lambda form:

map(lambda x: myFunc(x, b='booHoo'), myList)

Or you could use a list comprehension:

[myFunc(x, b='booHoo') for x in myList]

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


Re: map

2009-08-30 Thread Chris Rebert
On Sun, Aug 30, 2009 at 9:55 PM, elsakerensael...@hotmail.com wrote:
 Hi,

 i have a question about the built in map function. Here 'tis:

 say I have a list, myList. Now say I have a function with more than
 one argument:

 myFunc(a, b='None')

 now, say I want to map myFunc onto myList, with always the same
 argument for b, but iterating over a:

 map(myFunc(b='booHoo'), myList)

 Why doesn't this work?

Because myFunc is executed before map() is ever called, and you didn't
specify a value for the `a` parameter, hence you get an error about
not giving a value for `a`.
Another way of saying this: Python uses eager evaluation
(http://en.wikipedia.org/wiki/Eager_evaluation) most of the time.

 is there a way to make it work?

Use functools.partial to fill in the `b` parameter:
http://docs.python.org/library/functools.html#functools.partial

#untested example:
from functools import partial
f = partial(myFunc, b='booHoo')
map(f, myList)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map

2009-08-30 Thread rurpy
On 08/30/2009 10:55 PM, elsa wrote:
 i have a question about the built in map function. Here 'tis:

 say I have a list, myList. Now say I have a function with more than
 one argument:

 myFunc(a, b='None')

 now, say I want to map myFunc onto myList, with always the same
 argument for b, but iterating over a:

 map(myFunc(b='booHoo'), myList)

 Why doesn't this work? is there a way to make it work?

When you write map(myFunc(b='booHoo'), myList), you are telling
Python to call myFunc before the map function is called, because
an argument list, (b='booHoo'), follows myFunc.  You want
to pass map a function object, not the results of calling a
function object.

A couple ways to do what you want:

  map(lambda a: myFunc(a, b='booHoo'), myList)

The lamba expression creates a new function of one argument
(which is needed by map) that, when executed, will call myFunc
with the two arguments it needs.

You can also just define an ordinary function that does
the same thing as the lambda above:

  def tmpFunc (a)
myFunc (a, b='booHoo')
  ...
  map (tmpFunc, myList)

In the functools module there is a function called partial
that does something similar to the lambda above.  I'll leave
it to you you look it up if interested.

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


Re: map

2009-08-30 Thread Wolfgang Strobl
elsa kerensael...@hotmail.com:

now, say I want to map myFunc onto myList, with always the same
argument for b, but iterating over a:

 from functools import partial
 def g(x,y=1): return x+y
...
 map(partial(g,y=2),[1,2])
[3, 4]
 map(partial(g,y=42),[1,2])
[43, 44]


-- 
Wir danken für die Beachtung aller Sicherheitsbestimmungen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map with an extra parameter

2006-09-09 Thread Simon Forman
ml1n wrote:
 [EMAIL PROTECTED] wrote:
  This may be what you need:
 
  class foo:
def __init__(self, a, b):
   self.a = a
   self.b = b
 
  vars = [1,2,3,4,5,6]
  objects = [foo(a, 1) for a in vars]
 
 
  Note that in Python the new is expressed wit the () at the end:
 
 f = new foo()
 
  Bye,
  bearophile

 (Not sure if this group likes top or bottom posts, sorry)
 Thanks for the reply,
 In the interests of speed my thinking was that using map would move the
 loop out of Python and into C, is that the case when using list
 comprehension?  I'd always thought it was just syntatic short hand for
 a Python loop.

 M.

Your thinking is correct. :-)   Check out
http://groups.google.ca/group/comp.lang.python/msg/7a56cf1a052b9c5d
wherein Fredrik Lundh shows the difference by bytecode disassembly.

Peace,
~Simon

P.S. Bottom posts.

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


Re: Map with an extra parameter

2006-09-09 Thread Peter Otten
ml1n wrote:

 I'm not really sure how to explain this so maybe some example code is
 best.  This code makes a list of objects by taking a list of ints and
 combining them with a constant:
 
 class foo:
   def __init__(self):
  self.a = 0
  self.b = 0
 
 def func(a,b):
   f = new foo()
   f.a = a
   f.b = b
   return f
 
 constants = [1]*6
 vars = [1,2,3,4,5,6]
 objects = map(func,vars,constants)
 
 In the real world I need to do this as quick as possible (without
 resorting to c) and there are several constants. (The constant is only
 constant to each list so I can't make it a default argument to func.)
 My question is, can anyone think of a way to do this efficiently
 without having to use the `dummy` list of constants and would it be
 quicker?

Here are two more ways to achieve what you want, but you have to time them
youself.

 from itertools import starmap, izip, repeat
 class Foo:
... def __init__(self, a, b):
... self.a = a
... self.b = b
... def __repr__(self):
... return Foo(a=%r, b=%r) % (self.a, self.b)
...
 constants = repeat(1)
 vars = [1, 2, 3]
 list(starmap(Foo, izip(vars, constants)))
[Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)]

This requires Python 2.5:

 from functools import partial
 map(partial(Foo, b=1), vars)
[Foo(a=1, b=1), Foo(a=2, b=1), Foo(a=3, b=1)]


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


Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
This may be what you need:

class foo:
  def __init__(self, a, b):
 self.a = a
 self.b = b

vars = [1,2,3,4,5,6]
objects = [foo(a, 1) for a in vars]


Note that in Python the new is expressed wit the () at the end:

   f = new foo()

Bye,
bearophile

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


Re: Map with an extra parameter

2006-09-08 Thread ml1n
[EMAIL PROTECTED] wrote:
 This may be what you need:

 class foo:
   def __init__(self, a, b):
  self.a = a
  self.b = b

 vars = [1,2,3,4,5,6]
 objects = [foo(a, 1) for a in vars]


 Note that in Python the new is expressed wit the () at the end:

f = new foo()

 Bye,
 bearophile

(Not sure if this group likes top or bottom posts, sorry)
Thanks for the reply,
In the interests of speed my thinking was that using map would move the
loop out of Python and into C, is that the case when using list
comprehension?  I'd always thought it was just syntatic short hand for
a Python loop.

M.

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


Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
ml1n wrote:
 In the interests of speed my thinking was that using map would move the
 loop out of Python and into C, is that the case when using list
 comprehension?  I'd always thought it was just syntatic short hand for
 a Python loop.

In Python the faster things are often the most simple.
You can time your code to see what's faster.
And even better you may try the simpler solution, and if the program
results too much slow with a profiling you can find the spots needing
improvements.

Bye,
bearophile

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


Re: Map with an extra parameter

2006-09-08 Thread Paul Rubin
ml1n [EMAIL PROTECTED] writes:
 In the interests of speed my thinking was that using map would move the
 loop out of Python and into C, is that the case when using list
 comprehension?  I'd always thought it was just syntatic short hand for
 a Python loop.

Best to run benchmarks, but I don't expect a huge difference between
any of them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map with an extra parameter

2006-09-08 Thread ml1n
[EMAIL PROTECTED] wrote:
 ml1n wrote:
  In the interests of speed my thinking was that using map would move the
  loop out of Python and into C, is that the case when using list
  comprehension?  I'd always thought it was just syntatic short hand for
  a Python loop.

 In Python the faster things are often the most simple.
 You can time your code to see what's faster.
 And even better you may try the simpler solution, and if the program
 results too much slow with a profiling you can find the spots needing
 improvements.

 Bye,
 bearophile

Looks like someone already did:
http://mail.python.org/pipermail/python-list/2005-January/259870.html

Thanks for the shove in the right direction.

M.

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


Re: Map with an extra parameter

2006-09-08 Thread bearophileHUGS
ml1n:
 Looks like someone already did:
 http://mail.python.org/pipermail/python-list/2005-January/259870.html

Don't belive too much in such general timings. Time your specific code
when you think you need a true answer. Timing Python code is very easy
and fast, and sometimes results are surprising.

Bye,
bearophile

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


Re: map() return of flat tuple list

2006-06-23 Thread Mirco Wahab
Thus spoke [EMAIL PROTECTED] (on 2006-06-23 00:57):

 Maybe you want something like this (but this doesn't use map):
 [(r,c) for r, row in enumerate(m) for c in xrange(len(row))]

Ahh, its a 'list comprehension', nice.  Now,
lets see how the decorate/undecorate sort
turns out to look in Python:

arr = [
   [3,3,3,3],
   [3,3,3,1],
   [3,3,3,3] ]


print \
   sorted(
  [ (j,i) for j, row in enumerate(arr) for i in xrange(len(row)) ],
  lambda a,b: (arr[a[0]][a[1]] - arr[b[0]][b[1]])
   )[ 0 ]


== prints indices: (1,3)

He, this looks more like Haskell than like
Python (for me, it looks awful ;-)

I'll try to come up with at least one
map inside the comprehension, if that
works - just to avoid the dual for ;-)

Reagrds and thanks

Mirco

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


Re: map() return of flat tuple list

2006-06-23 Thread bearophileHUGS
Mirco:
He, this looks more like Haskell than like Python (for me, it looks awful ;-)

Maybe this is more readable:

ar = [[3,3,3,3],
  [3,3,3,1],
  [3,3,4,3]]

print sorted( [(r,c) for r,row in enumerate(ar) for c in
xrange(len(row))],
  key=lambda (r,c): ar[r][c]
)[0]

I don't know if operator.itemgetter can be used here, I think it's too
much complex.

With python 2.5 you can probably simplify it a little (and speed it up)
with something like:

print min( [ (r,c) for r,row in enumerate(ar) for c in xrange(len(row))
],
   key=lambda (r,c): arr[r][c]
 )

Bye,
bearophile

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


Re: map() return of flat tuple list

2006-06-22 Thread bearophileHUGS
Maybe you want something like this (but this doesn't use map):

def indexes(m):
return [(r,c) for r, row in enumerate(m) for c in xrange(len(row))]

m1 = [[2,2,5],
  [2,2],
  [2,2,2,2]]

m2 = [[],
  [2],
  [1,2,3,4]]

print indexes(m1)
print indexes(m2)

Output:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (2,
3)]
[(1, 0), (2, 0), (2, 1), (2, 2), (2, 3)]

Bye,
bearophile

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


Re: Map port to process

2006-01-05 Thread Diez B. Roggisch
py wrote:

 Is there a way in python to figure out which process is running on
 which port?  I know in Windows XP you can run netstat -o and see the
 process ID for each open portbut I am looking for something not
 tied to windows particularly, hopefully something in python.
 
 if not, any known way, such as netstat shown above, for other versions
 of windows (such as 98, 2000) and even linux?

Linux also knows netstat.

And at least with on-board mechanisms (meaning the standard lib), I fear you
can only try and use netstat as subprocess.

I'm not aware of an extension module that does what you want, but I didn't
google for it.

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


Re: Map port to process

2006-01-05 Thread Mike Meyer
py [EMAIL PROTECTED] writes:
 Is there a way in python to figure out which process is running on
 which port?  I know in Windows XP you can run netstat -o and see the
 process ID for each open portbut I am looking for something not
 tied to windows particularly, hopefully something in python.

Well, once you get to no tied to an OS, you're out of luck. You can
run network stacks on systems that don't have processes, so there's no
general mechanism for getting process information from a
socket. Restricting things to posixish systems doesn't seem to help
much, as there doesn't seem to be a posix interface to get it either.

 if not, any known way, such as netstat shown above, for other versions
 of windows (such as 98, 2000) and even linux?

Many windows networking tools started life as Unix networking
tools. Netstat is one of them. The -o flag may be a Windows addition,
though. FreeBSD (for instance) doesn't have it, but provides the
sockstat command to get pid/process name/etc. info on
sockets. Sockstat uses sysctls to pull specific kernel structures,
which means it's OS-specific. Python doesn't seem to have a way to do
sysctl calls, either.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: Map of email origins to Python list

2005-11-08 Thread Alan Kennedy
[Claire McLister]
 I've made the script available on our downloads page at:
 
  http://www.zeesource.net/downloads/e2i

[Alan Kennedy]
 I look forward to the map with updated precision :-)

[Claire McLister]
 Me too. Please let me know how we should modify the script.

Having examined your script, I'm not entirely sure what your input 
source is, so I'm assuming it's an mbox file of the archives from 
python-list, e.g. as appears on this page

http://mail.python.org/pipermail/python-list/

or at this URL

http://mail.python.org/pipermail/python-list/2005-November.txt

Those messages are the email versions, so all of the NNTP headers, e.g. 
NNTP-Posting-Host, will have been dropped. You will need these in order 
to get the geographic location of posts that have been made through NNTP.

In order to be able to get those headers, you need somehow to get the 
NNTP originals of messages that originated on UseNet. You can see an 
example of the format, i.e. your message to which I am replying, at this URL

http://groups.google.com/group/comp.lang.python/msg/56e3baabcd4498f2?dmode=source

The NNTP-Posting-Host for that message is '194.109.207.14', which 
reverses to 'bag.python.org', which is presumably the machine that 
gatewayed the message from python-list onto comp.lang.python.

So there are a couple of different approaches

1. Get an archive of the UseNet postings to comp.lang.python (anybody 
know where?)
  A: messages sent through email will have the NNTP-Posting-Host as
a machine at python.org, so fall back to your original algorithm for
those messages
  B: messages sent through UseNet, or a web gateway to same, will have an
NNTP-Posting-Host elsewhere than python.org, so do your geo-lookup
on that IP address.

2. Get the python-list archive
  A: Figure out which messages came through the python.org NNTP gateway
(not sure offhand if this is possible). Automate a query to Google
groups to find the NNTP-Posting-Host (using a URL like the one
above). Requires being able to map the python-list message-id to the
google groups message-id. Do your geo-lookup on that
NNTP-Posting-Host value
  B: Use your original algorithm for messages sent through email.

2A message-id lookup should be achievable through the advanced google 
groups search, at this URL

http://groups.google.com/advanced_search?q=;

See the Lookup the message with message ID at the bottom.

Sorry I don't have time to supply code for any of this. Perhaps some one 
can add more details, or better still some code?

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map of email origins to Python list

2005-11-07 Thread [EMAIL PROTECTED]

Rocco Moretti wrote:
 Paul McGuire wrote:
  Claire McLister [EMAIL PROTECTED] wrote in message
  news:[EMAIL PROTECTED]
We've been working with Google Maps, and have created a web service to
  map origins of emails to a group. As a trial, we've developed a map of
  emails to this group at:
 
http://www.zeesource.net/maps/map.do?group=668
 
This represents emails sent to the group since October 27.
 
Would like to hear what you think of it.
  --
 
  sigh
  Another sleepless camera pointed at the fishbowl that is my online life.
 

 It's also a testament to the limited value of physically locating people
 by internet addresses - If you zoom in on the San Fransico bay area, and
 click on the southern most bubble (south of San Jose), you'll see the
 entry for the Mountain View postal code (94043) - a massive list which
 contains mostly gmail.com accounts, but also contains accounts with .de
 .ca .uk .pl .it .tw and .za domains. I doubt all of the people in that
 list live in sunny California, let alone in Mountain View proper.

North of that bubble is a second massive list also labeled Mountain
View
94043. I found my name on that list and I live in the Chicago area.
Moutain View is, perhaps, where aol.com is located? These bubbles are
showing the location of the server that's registered under the domain
name?

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


Re: Map of email origins to Python list

2005-11-07 Thread Rocco Moretti
[EMAIL PROTECTED] wrote:
 Rocco Moretti wrote:

It's also a testament to the limited value of physically locating people
by internet addresses - If you zoom in on the San Fransico bay area, and
click on the southern most bubble (south of San Jose), you'll see the
entry for the Mountain View postal code (94043) - a massive list which
contains mostly gmail.com accounts, but also contains accounts with .de
.ca .uk .pl .it .tw and .za domains. I doubt all of the people in that
list live in sunny California, let alone in Mountain View proper.
 
 
 North of that bubble is a second massive list also labeled Mountain
 View
 94043. I found my name on that list and I live in the Chicago area.
 Moutain View is, perhaps, where aol.com is located? These bubbles are
 showing the location of the server that's registered under the domain
 name?

Actually, it looks like they are the *same* list. I haven't gone through 
all of the names, but I spot checked a few, and it looks like yours, 
among others, are listed in both spots. (The southern one looks like it 
is a mislocated duplicate, as it is nowhere close to Mountain View, and 
is stuck in the middle of a golf course.)

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


Re: Map of email origins to Python list

2005-11-07 Thread Robert Kern
[EMAIL PROTECTED] wrote:

 North of that bubble is a second massive list also labeled Mountain
 View
 94043. I found my name on that list and I live in the Chicago area.
 Moutain View is, perhaps, where aol.com is located? These bubbles are
 showing the location of the server that's registered under the domain
 name?

Most of AOL's offices are in Dulles, VA. Google's headquarters are in
Mountain View, CA.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter

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


Re: Map of email origins to Python list

2005-11-07 Thread [EMAIL PROTECTED]

Robert Kern wrote:
 [EMAIL PROTECTED] wrote:

  North of that bubble is a second massive list also labeled Mountain
  View
  94043. I found my name on that list and I live in the Chicago area.
  Moutain View is, perhaps, where aol.com is located? These bubbles are
  showing the location of the server that's registered under the domain
  name?

 Most of AOL's offices are in Dulles, VA. Google's headquarters are in
 Mountain View, CA.

Aha, I post to the usenet through Google. Makes the map application
all the more stupid, doesn't it?


 --
 Robert Kern
 [EMAIL PROTECTED]

 In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Map of email origins to Python list

2005-11-07 Thread Alan Kennedy
[Robert Kern]
Most of AOL's offices are in Dulles, VA. Google's headquarters are in
Mountain View, CA.

[EMAIL PROTECTED]
 Aha, I post to the usenet through Google. Makes the map application
 all the more stupid, doesn't it?

Actually, no, because Google Groups sets the NNTP-Posting-Host header to 
the IP address from which the user connected to Google. So your post to 
which I'm replying came from IP address 68.73.244.37, which reverses 
to adsl-68-73-244-37.dsl.chcgil.ameritech.net.

http://groups.google.com/group/comp.lang.python/msg/ca06957210fe12ae?dmode=source

So presumably chcgil indicates you're in Chicago, Illinois?

Although I do have to point out that the map makes it appear as if I've 
been busy posting from all over Dublin's Southside, which, as anyone who 
has seen The Commitments can attest, is a deep insult a born-and-bred 
Northsider such as myself ;-)

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map of email origins to Python list

2005-11-07 Thread [EMAIL PROTECTED]

Alan Kennedy wrote:
 [Robert Kern]
 Most of AOL's offices are in Dulles, VA. Google's headquarters are in
 Mountain View, CA.

 [EMAIL PROTECTED]
  Aha, I post to the usenet through Google. Makes the map application
  all the more stupid, doesn't it?

 Actually, no, because Google Groups sets the NNTP-Posting-Host header to
 the IP address from which the user connected to Google. So your post to
 which I'm replying came from IP address 68.73.244.37, which reverses
 to adsl-68-73-244-37.dsl.chcgil.ameritech.net.

 http://groups.google.com/group/comp.lang.python/msg/ca06957210fe12ae?dmode=source

 So presumably chcgil indicates you're in Chicago, Illinois?

Yes, but why, then, is my name logged into Mountain View, CA?

That justifies my claim of all the more stupid, doesn't it?


 Although I do have to point out that the map makes it appear as if I've
 been busy posting from all over Dublin's Southside, which, as anyone who
 has seen The Commitments can attest, is a deep insult a born-and-bred
 Northsider such as myself ;-)

 --
 alan kennedy
 --
 email alan:  http://xhaus.com/contact/alan

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


Re: Map of email origins to Python list

2005-11-07 Thread George Sakkis
Jorge Godoy [EMAIL PROTECTED]:

 H...  I don't see mine listed there: I'm in South America, Brasil.  More
 specifically in Curitiba, Paraná, Brasil. :-)

That's funny; I was looking for mine and I stumbled across yours at
Piscataway, NJ, US. :-)

George

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


Re: Map of email origins to Python list

2005-11-07 Thread Alan Kennedy
[Alan Kennedy]
So presumably chcgil indicates you're in Chicago, Illinois?

[EMAIL PROTECTED]
 Yes, but why, then, is my name logged into Mountain View, CA?

Presumably the creators of the map have chosen to use a mechanism other 
than NNTP-Posting-Host IP address to geolocate posters.

Claire, what mechanism did you use?

 That justifies my claim of all the more stupid, doesn't it?

Well, to me it just says that the map creation software has some bugs 
that need fixing.

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map of email origins to Python list

2005-11-07 Thread Jorge Godoy
George Sakkis [EMAIL PROTECTED] writes:

 Jorge Godoy [EMAIL PROTECTED]:
 
  H...  I don't see mine listed there: I'm in South America, Brasil.  More
  specifically in Curitiba, Paraná, Brasil. :-)
 
 That's funny; I was looking for mine and I stumbled across yours at
 Piscataway, NJ, US. :-)

Phew!  Thanks for finding me.  I was feeling a bit lost... :-)


Be seeing you,
-- 
Jorge Godoy  [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Map of email origins to Python list

2005-11-07 Thread Claire McLister
Thanks, Alan. You are absolutely right, we are not using the 
NNTP-Posting-Host header for obtaining the IP address.

The Python list is unique among the lists that we have handled so far, 
in that it has a cross-posting mechanism with a net news. Hence, it 
seems we are getting many more wrong locations here than any other 
email list maps we've done so far. We've done them for Linux kernel, 
postresql, apache, tomcat, etc. You can find them by searching their 
names in the 'find' box. Not many people reported wrong locations on 
those maps.

So, we'll have to go back and fix the script that is extracting the IP 
address (which is written in Python, btw). Let me know if someone is 
interested in taking a look at it and I can post it somewhere.

On Nov 7, 2005, at 2:32 PM, Alan Kennedy wrote:

 [Alan Kennedy]
 So presumably chcgil indicates you're in Chicago, Illinois?

 [EMAIL PROTECTED]
 Yes, but why, then, is my name logged into Mountain View, CA?

 Presumably the creators of the map have chosen to use a mechanism other
 than NNTP-Posting-Host IP address to geolocate posters.

 Claire, what mechanism did you use?

 That justifies my claim of all the more stupid, doesn't it?

 Well, to me it just says that the map creation software has some bugs
 that need fixing.

 -- 
 alan kennedy
 --
 email alan:  http://xhaus.com/contact/alan
 -- 
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Map of email origins to Python list

2005-11-07 Thread Alan Kennedy
[Claire McLister]
 Thanks, Alan. You are absolutely right, we are not using the 
 NNTP-Posting-Host header for obtaining the IP address.

Aha, that would explain the lack of precision in many cases. A lot of 
posters in this list/group go through NNTP (either with an NNTP client 
or through NNTP-aware services like Google Groups) which should give 
very good results, when available.

 So, we'll have to go back and fix the script that is extracting the IP 
 address (which is written in Python, btw). 

What better language to write in :-)

 Let me know if someone is 
 interested in taking a look at it and I can post it somewhere.

Sure, please do make it available, or at least the geolocation component 
anyway. I'm sure you'll get lots of useful comments from the many clever 
and experienced folk who frequent this group.

Don't be aggrieved at the negative comment you've received: I think what 
you're doing is fascinating.

But don't forget that a lot of people are not aware that this kind of 
geolocation can be done, along with the many other inferences that can 
be drawn from message and browser headers. So don't be surprised if some 
of them try to shoot the messenger.

I look forward to the map with updated precision :-)

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Map of email origins to Python list

2005-11-07 Thread Mike Meyer
Claire McLister [EMAIL PROTECTED] writes:
 Thanks, Alan. You are absolutely right, we are not using the
 NNTP-Posting-Host header for obtaining the IP address.

Yes, but what are you using?

 The Python list is unique among the lists that we have handled so far,
 in that it has a cross-posting mechanism with a net news. Hence, it
 seems we are getting many more wrong locations here than any other
 email list maps we've done so far. We've done them for Linux kernel,
 postresql, apache, tomcat, etc. You can find them by searching their
 names in the 'find' box. Not many people reported wrong locations on
 those maps.

Hmm. Are you using a different method than you used for the mail
lists? Because my mail and news follows the same path, using the same
host name. The only difference is that my ISP uses supernews.com news
servers, so my postings appear to go direct from my domain to
supernews - but the only place this shows up is in the Path: header.

For the record - I (and my servers) are in Virginia, the domain name I
use is registered to an address in Oklahoma, and everything is relayed
through my ISP in Berkeley. Your map has me in San Francisco. Ok, you
nearly got my ISPs hardware.

 So, we'll have to go back and fix the script that is extracting the IP
 address (which is written in Python, btw). Let me know if someone is
 interested in taking a look at it and I can post it somewhere.

What IP address it is extracting? Well, if you post it, I'll look at
it and figure it out from that.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  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: Map of email origins to Python list

2005-11-07 Thread Claire McLister
On Nov 7, 2005, at 3:26 PM, Alan Kennedy wrote:

 Sure, please do make it available, or at least the geolocation 
 component
 anyway. I'm sure you'll get lots of useful comments from the many 
 clever
 and experienced folk who frequent this group.


I've made the script available on our downloads page at:

  http://www.zeesource.net/downloads/e2i

  Let me know if you have any trouble accessing it. Sorry to disappoint, 
but we actually use a commercial service to convert from IP to 
location. There are several of them available on the net, and we picked 
this one after some testing. I think it has some location problems 
(like putting Mountain View south of San Jose in California), but 
otherwise seemed to be one of the better ones available.

 Don't be aggrieved at the negative comment you've received: I think 
 what
 you're doing is fascinating.

Thanks.

 I look forward to the map with updated precision :-)

Me too. Please let me know how we should modify the script.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-08 Thread Christopher Subich
Ron Adam wrote:
 Christopher Subich wrote:
 
 As others have mentioned, this looks too much like a list 
 comprehension to be elegant, which also rules out () and {}... but I 
 really do like the infix syntax.
 
 
 Why would it rule out ()?

Generator expressions.  Mind you, Py3k might want to unify generators 
and lists in some way anyway, freeing up (). :)

 
 You need to put a lambda express in ()'s anyways if you want to use it 
 right away.
 
  print (lambda x,y:x+y)(1,2)

Although print x+y with (x,y)(1,2) has natural grouping: the lambda 
itself is effectively a single token.  I also like the infix style 
reminiscent of Python's existing comprehensions.

Hell, call it a 'function comprehension' or 'expression comprehension,' 
and we can pretend we invented the damn thing.

 My choice:
 
 name = (let x,y return x+y)   # easy for beginners to understand
 value = name(a,b)
 
 value = (let x,y return x+y)(a,b)

And a zero-argument lambda is (aside from really arcane)?
(let return 2)?

 I think the association of (lambda) to [list_comp] is a nice 
 distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)

Yeah, dictionary comprehensions would be an interesting feature. :) 
Syntax might be a bit unwieldy, though, and I doubt they'd be used often 
enough to be worth implementing, but still neat.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-08 Thread Steven Bethard
Christopher Subich wrote:
 Ron Adam wrote:
 I think the association of (lambda) to [list_comp] is a nice 
 distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)
 
 Yeah, dictionary comprehensions would be an interesting feature. :) 
 Syntax might be a bit unwieldy, though, and I doubt they'd be used often 
 enough to be worth implementing, but still neat.

Dict comprehensions were recently rejected:
 http://www.python.org/peps/pep-0274.html
The reason, of course, is that dict comprehensions don't gain you much 
at all over the dict() constructor plus a generator expression, e.g.:
 dict((i, chr(65+i)) for i in range(4))

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-08 Thread George Sakkis
Steven Bethard [EMAIL PROTECTED] wrote:

 Christopher Subich wrote:
  Ron Adam wrote:
  I think the association of (lambda) to [list_comp] is a nice
  distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)
 
  Yeah, dictionary comprehensions would be an interesting feature. :)
  Syntax might be a bit unwieldy, though, and I doubt they'd be used often
  enough to be worth implementing, but still neat.

 Dict comprehensions were recently rejected:
  http://www.python.org/peps/pep-0274.html
 The reason, of course, is that dict comprehensions don't gain you much
 at all over the dict() constructor plus a generator expression, e.g.:
  dict((i, chr(65+i)) for i in range(4))

Sure, but the same holds for list comprehensions: list(i*i for i in
xrange(10)). The difference is historic I guess; list comprehensions
preceded generator expressions and so they cannot be removed, at least
not before 3.0. I wonder if they will/should be in the language when
the constraint of backwards compatibility is lifted. IMO they should
not (TIOOWTDI, uniformity among builtin data structures, not
overwhelmingly more useful than set or dict comprehensions), but
there's a long way till that day.

George

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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-08 Thread Terry Reedy

George Sakkis [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Steven Bethard [EMAIL PROTECTED] wrote:
 Dict comprehensions were recently rejected:
  http://www.python.org/peps/pep-0274.html
 The reason, of course, is that dict comprehensions don't gain you much
 at all over the dict() constructor plus a generator expression, e.g.:
  dict((i, chr(65+i)) for i in range(4))

 Sure, but the same holds for list comprehensions: list(i*i for i in
 xrange(10)). The difference is historic I guess; list comprehensions
 preceded generator expressions and so they cannot be removed, at least
 not before 3.0. I wonder if they will/should be in the language when
 the constraint of backwards compatibility is lifted.

Guido has asked himself the same question.  Some developers who love l.c.s 
are sure they will stay.  I am not.  I think it might depend on whether 
they have any real advantages in the context of the 3.0 engine and design, 
which don't exist yet.

 IMO they should
 not (TIOOWTDI, uniformity among builtin data structures, not
 overwhelmingly more useful than set or dict comprehensions), but
 there's a long way till that day.

Yes.

Terry J. Reedy



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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Reinhold Birkenfeld
Ron Adam wrote:

 Given the statement:
 
 a = None
 
 And the following are all true:
 
   a == None

Okay.

 (a) == (None)

Okay.

 (a) == ()

Whoops! a (which is None) is equal to the empty tuple (which is not None)?

 (None) == ()

 Then this conceptual comparison should also be true:
 
 if (None):  ==  if ():
 if (): == if:

I can't really see any coherent concept here.

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


Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Steven D'Aprano
Steven Bethard wrote:

 If you're really afraid of two lines, write it as:
 
 def r(): randint(1, 100)
 
 This is definitely a bad case for an anonymous function because it's not 
 anonymous!  You give it a name, r.

This is something I've never understood. Why is it bad 
form to assign an anonymous function (an object) to a 
name?

It isn't just that lambda _can_ create functions that 
aren't bound to any name. That I get. But why is it 
suppose to be wrong to bind such a function to a name?

Sure, if the lambda is so complicated that it becomes 
unreadable, the usage case is wrong and a def should be 
used instead. But I see nothing wrong with doing this:

func = lambda x: x**3 - 3*x**2

Why is it considered abuse of lambda to assign the 
functions to a name? Is it an abuse of lambda to do this?

D = {one: lambda noun: noun,
 two: lambda noun: noun + 's',
 many: lambda noun: 'lots of ' + noun + 's' }

assert D[two](python) == pythons


-- 
Steven.

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Duncan Booth
Steven D'Aprano wrote:
 This is something I've never understood. Why is it bad 
 form to assign an anonymous function (an object) to a 
 name?

Because it obfuscates your code for no benefit. You should avoid making it 
hard for others to read your code (and 'others' includes yourself in the 
future).

Also, it obfuscates tracebacks: all lambda expressions will identify in 
tracebacks as lambda, but if you define a function you can give it a 
meaningful name.

 
 Why is it considered abuse of lambda to assign the 
 functions to a name? Is it an abuse of lambda to do this?
 
 D = {one: lambda noun: noun,
  two: lambda noun: noun + 's',
  many: lambda noun: 'lots of ' + noun + 's' }
 
 assert D[two](python) == pythons
 
 
No, that is approaching a reasonable use of lambda, however I would still 
be inclined to write it with functions. e.g.

   def one(noun):
   return noun

   def two(noun):
   return noun+'s'

   def many(noun):
   return 'lots of %ss' % (noun,)

   D = dict(one=one, two=two, many=many)

although in this particular case I would probably just put format strings 
in the dictionary:

  def D(style, noun):
 formats = dict(one=%s, two=%ss, many=lots of %ss)
 return formats.get(style, an indeterminate number of %ss) % (noun,)

  assert D(two,python) == pythons
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Chris Rebert (cybercobra)
Agreed, I dislike map and its ilk as well.
However, they are handy in some cases. I particularly like the way Ruby
deals with this problem. Instead of all these functions, internal
iterators and true anonymous blocks are used.
Case in point:

def gt_than_5(obj):
return obj  5
results = filter(gt_than_5, seq)

becomes

results = seq.find_all do |item|
  item  5
end

This has the advantage of writing less code for the common cases by
having them builtin to the class. Instead of everyone needlessly
recoding these over and over again, they're implemented in one place.
This could be done by defining an abstract class that enumerable
objects inherit from. It's not practical, but I can dream, can't I? ;-)
Also, you don't have to define a separate testing function. Granted, in
this case, the test func is trivial, but when it's non-trivial, you
really notice the advantages.

Ivan Van Laningham wrote:
 Hi All--

 Tom Anderson wrote:
 
  Comrades,
 
  I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme
  folks. :-)
 
  I disagree strongly with Guido's proposals, and i am not an ex-Lisp,
  -Scheme or -any-other-functional-language programmer; my only other real
  language is Java. I wonder if i'm an outlier.
 
  So, if you're a pythonista who loves map and lambda, and disagrees with
  Guido, what's your background? Functional or not?
 

 I'm a pythonista who doesn't love them.  In fact, even though I've done
 more than my fair share of lambda Tkinter programming using lambdas,
 I've never been happy with lambda.  And I've spent months inside of
 Lisp/Emacs Lisp/Scheme, too (I have the world's second largest .emacs
 file [my friend Andy Glew has the largest], even though I can't use it
 on Windows;-).  I find list comprehensions easier to understand than
 map, and small named functions or, better yet, class methods, *tons*
 easier to read/understand than lambda--there are too many restrictions
 you have to remember.

 Personally, I find that Lisp  its derivatives put your head in a very
 weird place.  Even weirder than PostScript/Forth/RPN, when you come
 right down to it.

 I won't miss them, but since I don't use them now, that doesn't mean a
 whole lot.

 Metta,
 Ivan
 --
 Ivan Van Laningham
 God N Locomotive Works
 http://www.andi-holmes.com/
 http://www.foretec.com/python/workshops/1998-11/proceedings.html
 Army Signal Corps:  Cu Chi, Class of '70
 Author:  Teach Yourself Python in 24 Hours

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Paweł Sakowski
Tom Anderson wrote:
 def flatten(ll):
  return reduce(lambda a, l: a.extend(l), ll, [])
 
 How would one do that as a list comp, by the way? I'm really not very good
 with them yet.

Not really a list-comprehension based solution, but I think what you want is

 ll=[[1,2],[3,4,5],[6]]
 sum(ll,[])
[1, 2, 3, 4, 5, 6]

-- 
 Paweł Sakowski [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Steven D'Aprano
On Thu, 07 Jul 2005 09:36:24 +, Duncan Booth wrote:

 Steven D'Aprano wrote:
 This is something I've never understood. Why is it bad 
 form to assign an anonymous function (an object) to a 
 name?
 
 Because it obfuscates your code for no benefit. You should avoid making it 
 hard for others to read your code (and 'others' includes yourself in the 
 future).

I don't particularly think I'm that much smarter than the average
programmer. In fact I *know* that I'm not that much smarter. So why do I
see nothing obfuscated or obscure or difficult to understand in func =
lambda x: x**3 - 5*x when apparently most of the Python community find it
too complicated?

Whichever is more readable in the absolute sense, the abused lambda
expression above is within a gnat's whisker of the def equivalent,

def func(x):
return x**3 - 5*x

I honestly don't understand why it is supposed to be so hard to follow.

I can think of many function which should not be written with lambda, just
as some things shouldn't be written as list comps. But within the limits
of how much complexity you can reasonably include in a single expression,
I don't see why lambda puts people off.

I make it, eight mental tokens (not necessarily the same as Python tokens)
for the lambda versus nine for the def. A trivial difference. In my mind,
the tokens are:

func, =, lambda, x, :, x**3, -, 5*x

compared to:

def, func, (), x, :, return, x**3, -, 5*x

(Your mental parser may differ.)


 Also, it obfuscates tracebacks: all lambda expressions will identify in 
 tracebacks as lambda, but if you define a function you can give it a 
 meaningful name.

Well there is that. If you have lots of lambdas assigned to names, I guess
debugging could be more difficult:

py f = lambda x: 1.0/x
py f(0)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 1, in lambda
ZeroDivisionError: float division


py def f(x):
... return 1.0/x
...
 f(0)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 2, in f
ZeroDivisionError: float division

So far so good. But then:

py g = f
py del f
py g(0)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 2, in f
ZeroDivisionError: float division

(but we actually got the error by calling g, not f, and in fact f no
longer exists at the point we called g)


 Why is it considered abuse of lambda to assign the 
 functions to a name? Is it an abuse of lambda to do this?
 
 D = {one: lambda noun: noun,
  two: lambda noun: noun + 's',
  many: lambda noun: 'lots of ' + noun + 's' }
 
 assert D[two](python) == pythons
 
 
 No, that is approaching a reasonable use of lambda, however I would still 
 be inclined to write it with functions. e.g.
 
def one(noun):
return noun
 
def two(noun):
return noun+'s'
 
def many(noun):
return 'lots of %ss' % (noun,)
 
D = dict(one=one, two=two, many=many)

I find your version far more difficult to follow than mine.

Psychologically, I find that defs seem to carry significant mental weight
in a way that lambdas don't. Even though the lambda forms are
equivalent to the def forms, I find that the defs are more heavy-weight in
my conceptual map of the program than a lambda would be.

Put it this way: whenever I see a two-line def as above, I can't help
feeling that it is a waste of a def. (Somebody went to all the trouble
to define a function for *that*?) Yet I would never think the same about
a lambda -- lambdas just feel like they should be light-weight. 

Am I just weird?



-- 
Steven.


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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Sion Arrowsmith
=?ISO-8859-2?Q?Pawe=B3?= Sakowski  [EMAIL PROTECTED] wrote:
 ll=[[1,2],[3,4,5],[6]]
 sum(ll,[])
[1, 2, 3, 4, 5, 6]

That's a great argument for list.__add__ having the semantics of
extend rather than append 8-)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  Frankly I have no feelings towards penguins one way or the other
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Reinhold Birkenfeld wrote:
 Ron Adam wrote:
 
 
Given the statement:

a = None

And the following are all true:

  a == None
 
 
 Okay.
 
 
(a) == (None)
 
 
 Okay.
 
 
(a) == ()
 
 
 Whoops! a (which is None) is equal to the empty tuple (which is not None)?

It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
would be.

(a,) == (,)

which would be the same as:

(,) == (,)

(None) == ()

Then this conceptual comparison should also be true:

if (None):  ==  if ():
if (): == if:
 
 
 I can't really see any coherent concept here.
 
 Reinhold

It would work out that.

if: == if:

Does that help?

Cheers,
Ron



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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Bengt Richter
On 7 Jul 2005 15:46:23 GMT, Duncan Booth [EMAIL PROTECTED] wrote:

Steven D'Aprano wrote:

 Put it this way: whenever I see a two-line def as above, I can't help
 feeling that it is a waste of a def. (Somebody went to all the trouble
 to define a function for *that*?) Yet I would never think the same about
 a lambda -- lambdas just feel like they should be light-weight. 

Obviously we think differently there. I don't see why lambdas are any 
different than single expression functions. I certainly don't think of them 
as lighter weight; they take just as long to call; and they involve just as 
much stack setup/tear down. On the other hand I don't consider functions as 
heavyweight, I'm happy to define short helper functions anywhere I think it 
makes the code more expressive.

 Am I just weird?

No, just different[*]. There's nothing wrong with different.

[*] conclusion based entirely on your postings here. I have no evidence 
beyond that.

I think def is a form of assignment, with the target binding name
specified inside the expression syntax instead of to the left of an '=' as 
usual. I.e.,

def f(args): suite

is like

f = def(args): suite

except that I can't use an arbitrary left-hand side in the assignment, such as

MyClass.method = def(self, args): suite
or
   somedict['foo'] = def(self, args): suite

Personally, I think def(args): suite ought to be allowed as an expression that 
you could
put in parentheses like any other expression if you need/want to write it with 
multiple lines.
Obviously this could both replace and expand the functionality of lambda ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]

2005-07-07 Thread Tom Anderson

On Thu, 7 Jul 2005, Ron Adam wrote:


Stian Søiland wrote:

 Or what about a recursive generator?


That's the sort of thing i like to see!

Ok, lets see...  I found a few problems with the testing (and corrected 
it) so the scores have changed.  My sort in place routines were cheating 
because the lists weren't reset between runs so it had the advantage 
after the first time though of sorting already sorted list.


Aaagh, of course!

And Tom's recursive no copy had a bug which kept a reference to one of 
it's arguments so it's output was doubling the list.


Oops. I really should have written tests as well as benchmarks.

And the hasattr function was slowing everyone down, so I inlined it for 
everyone who used it. Using a 1000 item list and starting with a flat 
list and increasing the depth (unflatten) to shallow, medium, and deep. 
(but not so deep to cause recursion errors.)


I wrote a new and improved test harness myself, but left my laptop at 
work, and haven't been in today due to the bombs :(. I ran tests out to 
100 000 elements, and your implementation was still faster, although not 
by a lot - but then i hadn't found the bugs you had, so it's all moot.



And the winners are...

Stians flatten generator is nearly tied with Tom's recursive zerocopy. 
My nonrecursive inplace is faster for very shallow lists, but Tom's 
quickly over takes it.  I was able to improve my nonrecursive copy 
flatten a bit, but not enough to matter.


I also came up with an improvement to my version that should cut down on 
recursive calls - a sort of recursion unrolling. I doubt it wouldd make 
much difference, though.


So Tom's recursive zerocopy is the overall winner with Stian's flatten 
generator close behind and just barely winning out in the very deep 
catagory.


\o/


But they're all respectable times so everyone wins. ;-)


Everyone shall have medals!

tom

--
They travel the world in their ice cream van ...-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

 On Thu, 07 Jul 2005 09:36:24 +, Duncan Booth wrote:
 
 
Steven D'Aprano wrote:

This is something I've never understood. Why is it bad 
form to assign an anonymous function (an object) to a 
name?

Because it obfuscates your code for no benefit. You should avoid making it 
hard for others to read your code (and 'others' includes yourself in the 
future).

Use a descriptive name like this?

def get_the_cube_of_x_and_then_subtract_five_multiplied_by_x(x):
  x**3 - 5*x

I think I like the lambda version here.  ;-)

It would probably have a name which refers to the context in which it's 
used, but sometimes the math expression it self is also the most readable.



 Put it this way: whenever I see a two-line def as above, I can't help
 feeling that it is a waste of a def. (Somebody went to all the trouble
 to define a function for *that*?) Yet I would never think the same about
 a lambda -- lambdas just feel like they should be light-weight. 

In the case of an interface module you might have a lot of two like 
def's that simply change the name and argument format so several modules 
can use it and have a standard consistent or simplified interface.

The lambda may be perfectly fine for that.  But why not use def?

func_x = lambda x: (someother_func_x(x,'value'))

def func_x(x): return someother_func_x(x,'value')

There's both nearly identical, but the def is understandable to 
beginners and advanced python programs.


Cheers,
Ron


 Am I just weird?

Aren't we all?   ;-)

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


Re: Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Tom Anderson
On Thu, 7 Jul 2005, Steven D'Aprano wrote:

 On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote:

 del - delete

 How about just getting rid of del? Removal from collections could be done
 with a method call,

 Which would be called object.del() I presume.

That would be fine.

 And that opens a big can of worms.

 Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do?

Delete the item at index 1, just as del L[1] would.

 It looks like it should result in L becoming [4, 3, 2, 0].

Why? I guess if you hadn't read the documentation and were just calling 
methods at random, you might, but i can't think of any other case.

 An easy mistake to make, if you forget that the argument is (presumably) 
 an index.

Not the kind of thing people tend to forget! There is the problem that 
people might get del and remove mixed up; i didn't actually realise there 
was a remove method on lists until i looked just now.

 You could make it clear by insisting on L.del[1] but that requires a big 
 change in Python's syntax.

It would, so i wouldn't dream of insisting on it.

 What should L.del() do, with no arguments? Raise an error?

Er, exactly the same as calling any other method with a wrong-length 
argument list - a TypeError, i should think.

 Now, you have something like this:

 class thing:
pass
 obj = thing()
 obj.alpha = [4, 3, 2, 1, 0]
 obj.beta = 5

 Python's object model suggests that obj.alpha.del() should call alpha's 
 del method, in the same way that obj.alpha.append() would call alpha's 
 append method.

Exactly so.

 So how do you delete obj.alpha? obj.del(alpha) might work. But what if 
 obj itself is a mapping, with a key alpha as well as an attribute 
 alpha. Which one should obj.del(alpha) delete?

I don't think objects should have a del method by default. I'd suggest a 
delattr or removeattr builtin, working along the lines of getattr and 
setattr, for this task.

 Now, if you said that L.del() should raise an exception earlier, what 
 about obj.beta.del()?

Unless int has a del method, that would be an exception - an 
AttributeError, to be precise.

 Presumably every object automatically has a del method,

I'd say no, but for the sake of argument, let's say it does.

 so you don't have to program a del method yourself. obj.del is a method 
 object. So it has a del method. (Yes, sometimes you want to delete 
 methods. Functions are first class objects in Python.) Which has a del 
 method. Which has a del method.

Right.

 What should obj.del.del.del.del.del.del.del.del.del() do?

Raise a TypeError, since you haven't passed any parameters.

As for obj.del.del.del.del.del.del.del.del.del(del), that's an 
interesting one - it comes down to the question of whether those del 
methods are the same object or not. I'd say not: for two objects a and b 
of the same class, a.foo and b.foo are considered different objects in 
python, and that applies here.

 and i'm not convinced that deleting variables is something we really 
 need to be able to do (most other languages manage without it).

 Most other languages don't have namespaces that can get polluted, or
 on-the-fly creation of variables. Most other languages don't consider
 variables to be simply attributes of a module object.

How much is that really used? And how many of those cases wouldn't be 
covered by a delattr builtin?

 And most other languages don't allow you to run interactive sessions 
 where it is easy to mistakenly make variables you don't want.

 py x = 1
 py u = x+2  # oops, typo, meant y not u
 py del u  # prevent confusion in the programmer's mind

 It is also useful sometimes to delete a module object from the top level 
 namespace before re-importing it, rather than merely reloading it. That 
 requires being able to delete a variable.

That's a very strong use case. However, it would be straightforward to 
make variable deletion an interpreter thing rather than a language thing.

 In summary: del being a keyword works. del() being an object method is 
 unclear, confusing and complicated.

Only if you give it the bizarre semantics you use above!

I think having del as a keyword is actually unhelpful, since it's 
overloaded to do two quite different things - remove items from lists and 
dicts, and expunge attributes from namespaces. Far better to do let lists 
and dicts expose methods to let themselves be manipulated, and to play 
with attributes through a uniform troika of {get, set, del}attr builtins.

tom

-- 
They travel the world in their ice cream van ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Daniel Schüle
 Am I just weird?

I feel the same way about where to use lambda's and where *not*
I come from C and C++ background and defining a function at the top 
level (no nested functions) would always require good reasons

function name has to be remembered, to put it in other words it has to 
be added in a mental list of available function
and writing a 2 liner function would only cause call overhead
(if not inlined) this may be the reason why def feels to me to have 
more weight as lambda
usually you define lambda and forget it, no wasted time to find proper 
name, which may also pollute the namespace
I find it more clear solution, it's concise

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions andbackground unscientific mini-survey]

2005-07-07 Thread Terry Reedy
The difference in readability between

func = lambda x: x**3 - 5*x

def func(x):
return x**3 - 5*x

def func(x): return x**3 - 5*x

is obviously a matter of personal vision.

The fuctional difference (and, I believe, the only difference) is that the 
def form attaches the specific name 'func' to the function object as its 
func_name attribute while the lambda form attaches the generic 'name' 
'lambda'.   This makes tracebacks, for instance, less informative.

The reason some think the name=lambda form an abuse is that it is a second 
way to do almost the same thing (with the functional difference being a 
negative) while ignoring the intended purpose of lambda's presence in the 
language.  (But I will not argue this either way.)

Terry J. Reedy





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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Terry Reedy

Pawe³ Sakowski [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
Tom Anderson wrote:
 def flatten(ll):
  return reduce(lambda a, l: a.extend(l), ll, [])

 How would one do that as a list comp, by the way? I'm really not very 
 good
 with them yet.

Not really a list-comprehension based solution, but I think what you want 
is

 ll=[[1,2],[3,4,5],[6]]
 sum(ll,[])
[1, 2, 3, 4, 5, 6]

Unless sum knows to typecheck input items and special-case lists and use 
list.extend rather than list+list, this turns an O(n) operation into an 
O(n**2) operation.  Sum is meant for numbers.

Terry J. Reedy



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

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Terry Hancock
On Wednesday 06 July 2005 09:41 am, Steven Bethard wrote:
 Terry Hancock wrote:
  And a syntax just occured to me -- what about this:
  [expression for argument list]
 
 If you haven't already, see:
 http://wiki.python.org/moin/AlternateLambdaSyntax
 for other similar proposals.

Yeah, it's basically Robert Brewer: for (no-parens) syntax 
[3] isn't it (except that his eliminates the [], which is 
probably saner).

But hey, it's surely a good thing (in the sense of being 
more obvious) that it occured to me independently, 
right? ;-)

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Terry Reedy

Stian Søiland [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
On 2005-07-06 02:46:27, George Sakkis wrote:

 So, who would object the full-word versions for python 3K ?
 def - define
 del - delete
 exec - execute
 elif - else if

Objections for the else if might be that it sounds like you can
replace else if with else x=94 if you want. Thumbs up for else if
because it explains what it is much better than elif.  elseif ?

Today, on pydev list, in thread Chaining try statements: eltry?,
Guido said 'and in fact I sometimes think it was
a mistake to introduce elif just to save typing else if.'

So maybe this will be reconsidered for 3.0

Terry J. Reedy





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

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Terry Hancock
On Wednesday 06 July 2005 08:38 am, Tom Anderson wrote:
 On Wed, 6 Jul 2005, Terry Hancock wrote:
  With list comprehensions and generators becoming so integral, I'm
  not sure about unpythonic.
 
 I'm going to resist the temptation to argue that list comps are themselves 
 unpythonic :).

Ah, but GvR likes them, so that pretty much makes them pythonic
by definition, doesn't it?  ;-)

 Hang on, where's the punctuation in either of those? They *are* done with 
 keywords! 

Yeah, that's true, and it could be true here too, if you throw away the
[].  I see that's one of the proposed alternatives.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Ron Adam wrote:

 Reinhold Birkenfeld wrote:
 Ron Adam wrote:
(a) == ()
 
 
 Whoops! a (which is None) is equal to the empty tuple (which is not None)?
 
 It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
 would be.

But empty parenthesis are parsed as empty tuple::

  In [8]: type( () )
  Out[8]: type 'tuple'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Christopher Subich
Terry Hancock wrote:
 With list comprehensions and generators becoming so integral, I'm
 not sure about unpythonic.  And a syntax just occured to me --
 what about this:
 
 [y*x for x,y]
 
 ?
 
 (that is:
 
 [expression for argument list]
 
 It's just like the beginning of a list comprehension or generator, but
 without the iterator.  That implies that one must be given, and
 the result is therefore a callable object.

As others have mentioned, this looks too much like a list comprehension 
to be elegant, which also rules out () and {}... but I really do like 
the infix syntax.

Perhaps using angle-brackets would be useful? These have no 
grouping-meaning in Python that I'm aware of.  Example,

y*x for x,y

I'd also prefer using 'with' rather than 'for' as the keyword -- 'with' 
doesn't suggest iteration.  I also suggest parenthization of the 
argument list, since that makes a zero-argument lambda not look weird.

To replicate the examples from 
http://wiki.python.org/moin/AlternateLambdaSyntax

1 lambda a, b, c:f(a) + o(b) - o(c)
   f(a) + o(b) - o(c) with (a, b, c)
2 lambda x: x * x
   x * x with (x)
3 lambda : x
   x with ()
4 lambda *a, **k: x.bar(*a, **k)
   x.bar(*a, **k) with (*a, **k)
5 ((lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list)
   (x(*a,**k) with (x=x, a=a, k=k) for x, a, k in funcs_and_args_list)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Erik Max Francis
Ron Adam wrote:

 It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
 would be.
 
 (a,) == (,)
 
 which would be the same as:
 
 (,) == (,)

  ()
()
  a = ()
  type(a)
type 'tuple'
  (,)
   File stdin, line 1
 (,)
  ^
SyntaxError: invalid syntax

You've wandered way off into the woods now.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   But since when can wounded eyes see / If we weren't who we were
   -- Joi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Christopher Subich wrote:

 As others have mentioned, this looks too much like a list comprehension 
 to be elegant, which also rules out () and {}... but I really do like 
 the infix syntax.

Why would it rule out ()?

You need to put a lambda express in ()'s anyways if you want to use it 
right away.

  print (lambda x,y:x+y)(1,2)

If you don't use the ()'s it reads the y(1,2) as part of the lambda 
expression, might as well require the ()'s to start with rather than 
leave it open for a possible error.


You could even say () is to function as [] is to list.

a function :  name(args)  -  returns a value

a list :  name[index] -  returns a value



My choice:

 name = (let x,y return x+y)   # easy for beginners to understand
 value = name(a,b)

 value = (let x,y return x+y)(a,b)



I think the association of (lambda) to [list_comp] is a nice 
distinction.  Maybe a {dictionary_comp} would make it a complete set. ;-)

Cheers,
Ron













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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Erik Max Francis wrote:

 Ron Adam wrote:
 
 It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
 would be.

 (a,) == (,)

 which would be the same as:

 (,) == (,)
 
 
   ()
 ()
   a = ()
   type(a)
 type 'tuple'
   (,)
   File stdin, line 1
 (,)
  ^
 SyntaxError: invalid syntax
 
 You've wandered way off into the woods now.

Yes,  ummm seems soo...  err.

This is one of those Python isn't quite consistent for practical reasons 
area.  I don't create empty tuples that way very often, but [] is to () 
is to {} is pretty obvious so I don't really have a good excuse.

  (1)
1
  ()
()

  (1)
1
  ((()))
()

Well in my previous explanation I *mean* it to be empty parenthesis.

Does that help?

Cheers,
Ron


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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Erik Max Francis
Ron Adam wrote:

 Well in my previous explanation I *mean* it to be empty parenthesis.
 
 Does that help?

Maybe it might be beneficial to learn a little more of the language 
before proposing such wide-reaching (and un-Pythonic) reforms?

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   But since when can wounded eyes see / If we weren't who we were
   -- Joi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Erik Max Francis wrote:
 Ron Adam wrote:
 
 Well in my previous explanation I *mean* it to be empty parenthesis.

 Does that help?
 
 
 Maybe it might be beneficial to learn a little more of the language 
 before proposing such wide-reaching (and un-Pythonic) reforms?

Hi Erik,

Getting more sleep is the answer to not making those kinds of oversights 
in this case.

It's really was not a (my) proposal, but a suggestion someone else made. 
  It seemed like an interesting idea and I wanted to see what kind of 
problems and benefits it would have.  Discussing an idea with other 
before it's fully thought out is a good way to explore its possibilities 
even though it may mean appearing silly at times, which I don't mind. :)

In the previous posts I was attempting to show a possible pattern or 
logic which doesn't currently correspond to the languages syntax using 
parenthesis.

  (None)
 

That's as close to an empty parenthesis as Python gets.  I was really 
trying to explain an underlying concept, not show actual python code.

And the conclusion (opinion) I've come to, is such a change might be 
made to work, but it would be very confusing to most people who have 
gotten use to the current None usage.  And difficult to emplement in a 
way that's consistant overall.

An alternative is to use a different word such as 'undefined'.  Then 
None can be used as it is currently, and undefined, can be used to test 
for in a comparison for undefined names.  Assigning a name to undefined 
could be used as an alternative to delete a name but so far I don't see 
an advantage to doing that way over using del.



if name is undefined: do something.

Instead of:

try:
   name
except:
   do something


And maybe:

 name = undefined

can be used in expressions where del name can't?

But so far this doesn't seem useful enough to propose and it would 
probably cause more problems (or confusion) than it solves.

Cheers,
Ron
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Terry Hancock
On Tuesday 05 July 2005 06:57 pm, Steven D'Aprano wrote:
 On Tue, 05 Jul 2005 12:11:47 -0700, mcherm wrote:
 
  And besides, def isn't a magic word... it's an abreviation for
  define... 
 
 Really? I thought it was an abbreviation for definition. As in,
 definition of MyFunc is...

Does it matter?  But no, define is correct, because the def
keyword is active. It is *not* a declaration of a function but
a command to define one then and there.

  I hope that any student who didn't understand a word as
  common as define wouldn't have graduated from our school.
 
 How about tuple? 

It's a generalization rather than a specialization:

double (or couple)
triple
quadruple
quintuple
sextuple
septuple
octuple
nontuple
...

Maybe a wee bit less obvious, but still understandable.

Besides, the existence of another poor choice of words wouldn't
make the first one any better, would it?

If you are arguing that lambda is the right and proper
word for this operator that Python should use,  I still will
have to disagree.

OTOH, if you just want the functionality of lambda to remain,
I must say I agree.  It's a useful construct.

But it *is* poorly named. It really stands out as the least
intuitive keyword in the language, IMHO.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Terry Hancock
On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote:
 I understand that the backslash is popular in some ivory-tower functional 
 languages. Currently, a backslash can be used for explicit line joining, 
 and is illegal elsewhere on a line outside a string literal, so i think 
 it's available for this. It would be utterly unpythonic to use puntuation 
 instead of a keyword, and it would make no sense to novices, but it would 
 scare the crap out of C programmers, which has to be worth something.

With list comprehensions and generators becoming so integral, I'm
not sure about unpythonic.  And a syntax just occured to me --
what about this:

[y*x for x,y]

?

(that is:

[expression for argument list]

It's just like the beginning of a list comprehension or generator, but
without the iterator.  That implies that one must be given, and
the result is therefore a callable object.

Wouldn't do anything more or less than present day lambda, but
gets rid of the weird keyword, and integrates nicely with list comps
and generators.  It's currently a syntax error, and it requires no 
special delimiter -- it's really just an extension of list comp syntax.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Steven D'Aprano
I said I'd drop the discussion about lambda, but this 
isn't really the same discussion even if it is part of 
the same thread. That's my excuse, and I'm sticking to it.

Terry Hancock wrote:
 On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote:
 
I understand that the backslash is popular in some ivory-tower functional 
languages. Currently, a backslash can be used for explicit line joining, 
and is illegal elsewhere on a line outside a string literal, so i think 
it's available for this. It would be utterly unpythonic to use puntuation 
instead of a keyword, and it would make no sense to novices, but it would 
scare the crap out of C programmers, which has to be worth something.
 
 
 With list comprehensions and generators becoming so integral, I'm
 not sure about unpythonic.  And a syntax just occured to me --
 what about this:
 
 [y*x for x,y]
 
 ?
 
 (that is:
 
 [expression for argument list]
 
 It's just like the beginning of a list comprehension or generator, but
 without the iterator.  That implies that one must be given, and
 the result is therefore a callable object.

That is a very long chain of implication:

It looks like a list comprehension... but there is no 
iterator... so we have to supply an iterator... so it 
takes an argument... so it is a callable object... oh 
and by the way, it can take any arguments, not just 
iterators.

It is also far too easy to make a mistake, eg to write 
something like newlist = [y*x for x,y] when you 
actually wanted the list comp [y*x for x,y in L].

This would create an anonymous function where you 
expected to create a list. It is hard to think of a 
usage case where you didn't discover the error 
reasonably soon, but it would be better for leaving the 
iterator out of a list comp to remain a syntax error, 
rather than produce an unexpected, but legal, object.

Besides, I think Guido should be very cautious about 
introducing new features that use punctuation, instead 
of keywords. We don't want to become perl do we? :-)



-- 
Steven.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-06 Thread Antoon Pardon
Op 2005-07-01, Mike Meyer schreef [EMAIL PROTECTED]:
 iK [EMAIL PROTECTED] writes:

 Seems like he wants python programmers to solve their problems all in the 
 same way. While that is great for corporate slaves it is terrible for the 
 creative programmer.

 No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic.

If Guido should change his mind on this, then it will be pythonic.
I don't think a concept that has so little meaning has any real
value.

 Python is quickly becoming the visual basic of the 21 century. If you want 
 to have fun while getting some work done you need to look elsewhere. It's a 
 shame... 

 If you'd rather spend your time figuring out which of multiple ways to
 do things is the best for the job at hand than producing code, there's
 a language that makes TMTOWTDI a way of life.

There are always many ways to do things, and depending on circumstances
the best way to do something may differ every time.

So if python no longer allows multiple ways to do things, it won't help
the programmer. The programmer will now face the question if python
is still the right language to do the job.

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


  1   2   3   >