[OEIS] Python-development. Was: Request for more Python programs

Antti Karttunen antti.karttunen at gmail.com
Wed Jan 3 08:10:45 CET 2007


I wrote:

>
>
> Now, I'm just a beginner myself with Python,
> and don't know whether it for example allows
> defining of the cached/memoized recursive functions,
> where the function to be defined can itself
> access (transparently!) its own cache.
> But what I have read for example from
>
> http://myhdl.jandecaluwe.com/doku.php/meps:mep-100
>
> about the "decorators", it seems promising.
> And also, if one could include both the ordinary
> returning functions and yielding generators
> under the same framework (the former under
> the latter?), it might be very good for
> the self-describing sequences, of which
> there are many in OEIS.
>
Funny, I perused my archives and found this code from the May of
last year, that I didn't even remember to have written.
(Hmm, needs some polishing touches...) Anyway,
the idea works: fibo(47) gives the result back "immediately".
Free to use and improve for any SeqFan!

from array import *

def gen_n_items(n,item):
  for i in xrange(n): yield(item)

# Some things to fix here!

def memoed(fun):
    maxmemosize = 131 # 072
    notfilled = 0L
    memo = array('L')
    def wrapper(n):
        memsiznow = len(memo)
        if None == n: return(memo) # For debugging
        elif n >= memsiznow:
              newsize = min(maxmemosize,max(n+1,2*memsiznow))
              memo.extend(gen_n_items(newsize-memsiznow,notfilled))

        res = memo[n]
        if(notfilled == res):
              res = fun(n)
              memo[n] = res
              return(res)
        else: return(res)
    return wrapper


# Try fibo(47) for example. (The last that fits into long!)

@memoed
def fibo(n):
  '''Fibonakin luvut.'''
  if(n < 2): return(n)
  else: return(fibo(n-2)+fibo(n-1))



@memoed
def A001477(n):
  '''Produces non-negative integers in funny way.'''
  if(n < 2): return(n)
  else: return(A001477(n-1)+(A001477(n-1)-A001477(n-2)))










More information about the SeqFan mailing list