Friday, September 15, 2006

Reversing lists

There is more than one way to do a thing, and more than one language :)

Program 1
Language: Python
def reverse(l):
    if(l==[]):
        return []
    else:
        return (reverse(l[1:])+list(a[0]))


Program 2
Language: Python
def reverse(l):
    return l[::-1]

Program 3
Language: Python
a=range(10)
a.reverse()

Program 4
Language: elisp (!!)
(defun consx (l x)
  "like cons but first arg is a list"
  (if (eq l '())
      (list x)
    (cons (car l) (consx (cdr l) x))))

(defun reverse(l)
  "reverse a list"
  (if (eq l '())
      ()
    (consx (reverse (cdr l)) (car l))))

(reverse '(1 2 3))

Monday, September 11, 2006

The quest for the ninja monkey.

I rechristened the site name, in the hopes of reviving something which was lost. Behold for I give you the random permutation.
Language: Python
# Deutsche bank's online banking page uses a O(n^3) algorithm to generate a
# random character array.
# This is a O(n) way to do the same, for any array.

def randomPermute(array):
    import random
    for i in range(len(array)):
        randIndex=random.randint(i,len(array)-1)                               
        (array[i],array[randIndex])=(array[randIndex],array[i])
    return array

# Lets experiment with the english alphabet
import string
print randomPermute(list(string.ascii_letters[:26]))