Friday, September 07, 2007

Working the Snake - Python

I finally found my way to (Iron) Python[1][2] - well I did some Python in the beginning of my studies but lost focus after some time. The experience was quite impressive, since development time is greatly reduced by such a dynamic language. I managed to get some small programs running in less then 1 hour and of course I want to share them with you - precious audience. Since these are my first scripts, I assume that they are not quite correct/stable/... - they are simple and not very error-safe (no checking of arguments ) ...

The first is some simple factorial program, which tries to find the greatest common divisor (gcd)of two numbers by employing the fact that gcd (x, y) = gcd (y, r) where r = x mod y. Since I do not know how a scope for loops can be created (scoping a while/for loop) I did the routine recoursively. The second function builds on the first and is allows to ask whether some number x is a prime number by using the simple strategy of finding a gcd within the range of 1..root(x)


import System
def gcd(x,y):
  if y == 1 : return 1
  elif y == 0: return y
  elif x == y : return y
  elif x return gdc(y,x)
  n = x % y
  if n == 0: return y
  return gcd(y, n)

def IsPrime(x):
  if x == 1 : return 1
  elif x == 2 : return 1
  elif x == 3 : return 1
  tempsqrt = System.Math.Sqrt(x)
  tempsqrt = System.Convert.ToInt32(tempsqrt)
  for i in range(tempsqrt) :
  j = i + 1
  divisor = gcd(x,j)
  if divisor != 1 : return 0
  return 1


The second program is about the all time recursion favorite - the fibonaci numbers ...

the Fibonaci (Fib ) numbers are defined as follows

Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-2) + Fib(n-1)

example

n 0 1 2 3 4 5 6
Fib (n) 0 1 1 2 3 5 8
and here is the program - putting python suggar just around the exemplified formulae

import System
def Fibonaci(n):
  if n <= 0: return 0
  if n == 1: return 1
  return Fibonaci(n-2) + Fibonaci(n-1)

References:

[1] IronPython - www.codeplex.com/IronPython
[2] Python - www.python.org

No comments: