portable fortune program

Christopher Browne cbbrowne at acm.org
Sun Apr 28 16:06:48 EDT 2002


In the last exciting episode, jacob at boris.cd.chalmers.se.cd.chalmers.se (Jacob Hallen) wrote::
> In article <z4Xy8.72324$z55.71416 at atlpnn01.usenetserver.com>,
> Steve Holden <sholden at holdenweb.com> wrote:
>>"J.Jacob" <joost_jacob at hotmail.com> wrote in message
>>news:13285ea2.0204270857.2f34f8a4 at posting.google.com...
> ... Complicated suggestion by Steve deleted.
>>>
>>> # file fortune.py
>>> import random, os
>>>
>>> def randlistindex(yourlist):
>>>     "Return a random index number into yourlist"
>>>     return random.randint(0, len(yourlist)-1)
>>>
>>> def quote():
>>>     """
>>>     Return a quote <string> from file allfortunes,
>>>     assume the file allfortunes is located in the same
>>>     directory as this module."""
>>>     datafile = os.path.join(
>>>       os.path.dirname(__import__(__name__).__file__),
>>>       'allfortunes' )
>>>     quotesfile = open(datafile)
>>>     quoteslist, quote = [], ''
>>>     for s in quotesfile.readlines():
>>>         if s[0] == '%':
>>>             if quote:
>>>                 quoteslist.append(quote)
>>>                 quote = ''
>>>         else: quote = quote + s
>>>     if quote: quoteslist.append(quote)
>>>     print quoteslist[randlistindex(quoteslist)],
>
> Simple suggestion by me added:
>
> 1. Get the size of the file.
> 2. Get a random number 0 - size-1.
> 3. Index to this point in the file.
> 4. Iterate back to the nearest previous '%'.
> 5. Print fortune from there.
>
> This will of course skew the probability of getting printed towards longer
> cookies, but nobody will notice that.

The approach I take is to read through the cookies, one by one, and at
each one, randomly choose to keep the current cookie, thus:

(defun end-of-cookie ()
  (incf *total-cookies*) ;;; Increment count
  (if (= (random *total-cookies*) 0)
      (setq *keptcookie* *currentcookie*))
  (setq *currentcookie* '()))  

This gives an equal probability for each cookie in the file.

That's not as fast as your approach, but has similar memory
consumption characteristics, and is unbiased.

If efficiency were truly important, it would make sense to set up a
separate array, associate 1 with the start point of message 1, 2 with
the start point of message 2, and so forth, and you'd run through the
cookies to rebuild the hash table every time the cookies are changed.
-- 
(reverse (concatenate 'string "moc.enworbbc@" "sirhc"))
http://www.cbbrowne.com/info/multiplexor.html
When there's a will, I want to be in it. 



More information about the Python-list mailing list