Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Sep 19th, 2005, 1:36 PM   #11
coldDeath
Expert Programmer
 
coldDeath's Avatar
 
Join Date: Aug 2005
Location: UK
Posts: 862
Rep Power: 3 coldDeath is on a distinguished road
Send a message via AIM to coldDeath Send a message via Yahoo to coldDeath
Quote:
Originally Posted by Dietrich
How would you replace lambda in dictionary usage?
# Python can do a switch/case like thingy using a dictionary and lambda
# basis for a nice calculator

def do_operation(op, a, b):
    """here a dictionary combined with the lambda inline function acts like switch/case"""
    return {'+': lambda: a + b,
            '-': lambda: a - b,
            '*': lambda: a * b,
            '/': lambda: a / b
           }[op]()

print do_operation('+', 2, 5)
That is a nice bit of coding GJ
__________________
Join us at #programmingforums @ irc.freenode.net!

My software never has bugs. It just develops random features.
coldDeath is offline   Reply With Quote
Old Sep 21st, 2005, 3:20 PM   #12
LegionZero
Newbie
 
LegionZero's Avatar
 
Join Date: Jul 2005
Location: Tijuana, B.C.
Posts: 19
Rep Power: 0 LegionZero is on a distinguished road
Send a message via MSN to LegionZero Send a message via Yahoo to LegionZero
This is a very nice article, very insightful. File > Print... (select printer) press Enter Thank you
__________________
War cannot be avoided until the physical cause
for its recurrence is removed and this, in the last analysis,
is the vast extent of the planet on which we live. ~ Nikola Tesla
LegionZero is offline   Reply With Quote
Old Sep 21st, 2005, 5:12 PM   #13
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
Quote:
Originally Posted by Dietrich
How would you replace lambda in dictionary usage?
def add(a, b):
    return a + b
def sub(a, b):
    return a - b
def mul(a, b):
    return a * b
def div(a, b):
    return a * b
ops = {"+" : add, "-" : sub, "*" : mul, "/" : div}

def do_operation(op, a, b):
    return ops[op](a, b)

Quote:
Originally Posted by Dietrich
Using the timeit module, map() comes out the winner over its list comprehension equivalent by a nose.
Funny, I find the opposite. Care to post your benchmark?
Cerulean is offline   Reply With Quote
Old Sep 22nd, 2005, 2:13 AM   #14
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by Cerulean
def add(a, b):
    return a + b
Funny, I find the opposite. Care to post your benchmark?
Cerulean's way is preferable, but if you really really want wrapped dispatch:
import operator
def do_operation(op, a, b):
    return {'+': operator.add,
            '-': operator.sub,
            '*': operator.mul,
            '/': operator.div}[op](a, b)

print do_operation('+', 2, 5)
The relative difference between the speed of map() and listcomps varies depending on version - Dietrich might be running on 2.2 or 2.3 rather than 2.4?

--OH.
hydroxide is offline   Reply With Quote
Old Sep 22nd, 2005, 2:22 AM   #15
hydroxide
Programmer
 
Join Date: Apr 2005
Posts: 73
Rep Power: 4 hydroxide is on a distinguished road
Quote:
Originally Posted by Arevos
Python is a language that is often underestimated, and often underused. Beneath its deceptively simple exterior, Python has some very powerful features that you may not be aware of.
Another useful technique - objects can behave like state-ful functions by using the __call__ hook:

class Accumulator(object):
    def __init__(self, start=0):
        self.val = start

    def __call__(self, delta=1):
        self.val += delta
        return self.val

    def __str__(self):
        return str(self.val)

x = Accumulator()
y = Accumulator(4)
print x, y
print x(2), y()
print x(1), y(-2)
print x, y
print x(), y()
--OH.
hydroxide is offline   Reply With Quote
Old Sep 22nd, 2005, 5:46 AM   #16
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
A couple more interesting tricks in Python 2.4:

Generator Comprehensions

Exactly like a list comprehension, but returns a generator object instead of a list. e.g:
(i for i in range(10) if (i % 2) == 0)

Decorators

Syntaxtic sugar for wrapping a function in another.

e.g:
def bar(f): ...

@bar
def foo(x): ...
Is equivalent to:
def bar(f): ...

def foo(x): ...
foo = bar(foo)
Arevos is offline   Reply With Quote
Old Sep 22nd, 2005, 3:01 PM   #17
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
/me doesn't like the decorator syntax :-(
Guido's call (and the communities, there was a vote if i'm not mistaken), but I would have liked something like
def static foo(x): ...
a bit better
Cerulean is offline   Reply With Quote
Old Sep 22nd, 2005, 3:49 PM   #18
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4 Arevos is on a distinguished road
I'm with you there. The decorator syntax sucks - and doesn't actually reduce your linecount, either.
Arevos is offline   Reply With Quote
Old Sep 23rd, 2005, 6:37 PM   #19
Dietrich
Professional Programmer
 
Dietrich's Avatar
 
Join Date: Feb 2005
Posts: 434
Rep Power: 4 Dietrich is on a distinguished road
Smile

Thanks Cerulean and hydroxide for the "replacement of lambda" suggestions.

Here is my code to time map() versus list comprehension:
# 85% of the time map() beats list comprehension by 5 - 10% on Windows XP  Python 2.4.1

import timeit

tt = timeit.Timer('map(str, [2, 3, 5, 1])')
te = (1000000 * tt.timeit(number=100000)/100000)
print "Function map(str, [2, 3, 5, 1]) uses %0.5f ms/pass" % te

tt = timeit.Timer('[str(x) for x in [2, 3, 5, 1]]')
te = (1000000 * tt.timeit(number=100000)/100000)
print "LC [str(x) for x in [2, 3, 5, 1]] uses %0.5f ms/pass" % te
Did the decorator syntax come from Java?
__________________
I looked it up on the Intergnats!
Dietrich is offline   Reply With Quote
Old Sep 24th, 2005, 7:39 AM   #20
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
If you're going to be calling a function in each iteration in the list then map is probably faster, yes. It's the fact that list comprehensions allow you to get away with not having to call a function that makes them faster for a bunch of situations
Cerulean is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 2:54 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC