My guess is this won't have the speed advantage of ?: in C-ish languages, but it's still convenient for conciseness. I'll post a speed comparison later.


Code:

def qco(switch, v1, v2):
     return {True : v1, False : v2}[bool(switch)]

#example
def max(v1, v2)
     return qco(v1 > v2, v1, v2)

Code:
def max(v1, v2):
    return (v1,v2)[not v1 > v2]


Evil or Very Mad

Edit:
Oh, and apparently Python 2.5 added functionality that lets you do this:

Code:
def max(v1, v2):
    return v1 if v1 > v2 else v2
the point of that is not the max function, that's just the example usage Razz it's the qco function simulating ?:

I didn't realize boolean values would be automatically int()d when used as slice indexes.

In this case, my function would take the form

Code:

def qco(switch, v1, v2):
    return (v1, v2)[not switch]



[edit]
wtf? really? After years of stonewalling and offering hackish solutions?

[edit2]


The real way, for everyone who hasn't upgraded to 2.5:


Code:
(switch and [v1] or [v2])[0]


or


Code:
(lambda: v1, lambda: v2)[not switch]()
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement