[Tutor] Efficiency and speed
eire1130 at gmail.com
Mon Mar 22 03:18:32 CET 2010
On Sat, Mar 20, 2010 at 1:17 PM, Steven D'Aprano <steve at pearwood.info>wrote:
> On Sat, 20 Mar 2010 05:47:45 am James Reynolds wrote:
> > This is a monte-carlo simulation.
> > The simulation measures the expiration of something and those
> > somethings fall into bins that are not evenly dispersed. These bins
> > are stored in the nx list mentioned previously.
> > So let's say you have the bins, a, b,c,d,e,f and you have the value z
> > from the sample list where z >b and <= a. In this case, it should
> > return the index value at position (a).
> I'm not sure I understand completely. An example might help. I *think*
> you have a list like this:
> nx = [10.0, 9.0, 7.0, 3.0, 2.0, 1.0]
> and if you have a value like z = 9.8 you want to return the index 0.
> That seems a bit funny. In my experience it is normal to have the bins
> in the opposite direction. I suppose it probably doesn't matter that
> much, but it does seem a bit unusual.
> If nx is fairly short (say, less than 40 or 50 items), then the fastest
> way is probably a linear search, something like this:
> def search_bins(nx, z):
> """Search bins nx for item z.
> >>> bins = [5.0, 4.0, 2.0, 1.0]
> >>> search_bins(bins, 1.2)
> If z is not in the bins, returns -1:
> >>> search_bins(bins, 5.1)
> for i, value in enumerate(nx):
> if z > value:
> return i-1
> return -1
> Steven D'Aprano
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Thank you to everyone who responded to this thread. I learned some very
important lessons, some of which I've been working on over the weekend. I
apologize for not responding sooner.
I tinkered around with the aforementioned algorithm and I ended up using the
bisect that Emilie showed earlier. I did end up making the nested for loop
work earlier using an if statement, but the bisect was much more efficient
(.24 seconds running 100K trials), which is a major improvement. I've just
started using profiler this weekend, and It's giving me some incite into how
the language functions.
On that end, I'm almost done readying "beginning Python: From Novice to
Professional" Can anyone recommend anything else for me to read after that?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor