By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,222 Members | 2,478 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,222 IT Pros & Developers. It's quick & easy.

Calling all experts: Python Tips and Tricks

bartonc
Expert 5K+
P: 6,596
I've decide to compile a bunch of your favorite tips and tricks for the Articles section.

Post your favorite tips and tricks here, in this thread, and I'll copy the best ones to a Tips and Tricks article (to be created soon).

Thanks. And have fun!
Jul 28 '07 #1
Share this Question
Share on Google+
2 Replies


bartonc
Expert 5K+
P: 6,596
It's really not hard. Nor does it need to take much time. This thread is what I have in mind.

I know that you all have it in you. So c'mon...
Aug 9 '07 #2

ilikepython
Expert 100+
P: 844
Ok, I don't know if this is any good, but I'll post it anyway. I wrote a function that is like a binary search on a built in list object. I was doing one of the problems from project euler and my problem was I kept repeatedly checking wether an element was in a list. When I used this function the program ran much faster. But it only works on sorted lists:
Expand|Select|Wrap|Line Numbers
  1. def lookfor(s, obj, start, end, stopAt = 50):
  2.     if end - start < stopAt:
  3.         if obj in s[start:end]:
  4.             return True
  5.         else:
  6.             return False
  7.  
  8.     ind = start + ((end-start)/2)
  9.     it = s[ind]
  10.  
  11.     if it == obj:
  12.         return True
  13.     elif it > obj:
  14.         return lookfor(s, obj, start, ind)
  15.     elif it < obj:
  16.         return lookfor(s, obj, ind, end)
  17.  
It can also be written as a custom list object that inherits from list and overrides the __contains__ operator. What do you guys think?
Sep 22 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.