Here below a little program in IronPython that implements 2 classes. There is the main class, called Fiborial (Fibo(nnacci)+(Facto)rial) that implements the

*Fibonacci*and the

*Factorial*algorithms in two ways, one

*Recursive*(using recursion) and the other

*Imperative*(using loops and states). The second class is just an instance class that does the same thing, but its there just to show the difference between static and instance classes, and finally a main function called as module level code.

You can also find 3 more little examples at the bottom. One prints out the Factorial's Series and Fibonacci's Series, the second one just shows a class that mixes both: static and instance members, and finally the third one that uses different return types for the Factorial method to compare the timing and result.

As with the previous posts, you can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you some more basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2011/01/new-series-factorial-and-fibonacci.html

WARNING: the code that you will see below is not following python(ic) guidelines/idiomatic coding, I did it in purpose to compare python's syntax and features side by side with other programming languages... For instance, instead of using a python int or long I imported and used System.Numerics.BigInteger instead. Other examples, naming convention and so on, so bear with me!

**The Fiborial Program**

# Factorial and Fibonacci in IronPython import clr clr.AddReference('System.Numerics.dll') from System.Numerics import BigInteger from System import Console from System.Diagnostics import Stopwatch # Instance Class # static classes are not supported in Python class StaticFiborial: # Static Field __className = '' # no builtin static constructor/initializer support # you can initialize field at this point and even add extra code __className = 'Static Initializer' print __className # Static Method - Factorial Recursive @staticmethod def factorialR(n): if n == 1: return BigInteger.One else: return BigInteger.Multiply(BigInteger(n), StaticFiborial.factorialR(n-1)) # Static Method - Factorial Imperative @staticmethod def factorialI(n): res = BigInteger.One for i in range(n, 1, -1): res = BigInteger.Multiply(res, BigInteger(i)) return res # Static Method - Fibonacci Recursive @staticmethod def fibonacciR(n): if n < 2: return 1 else: return StaticFiborial.fibonacciR(n - 1) + StaticFiborial.fibonacciR(n - 2) # Static Method - Fibonacci Imperative @staticmethod def fibonacciI(n): pre, cur, tmp = 0, 0, 0 pre, cur = 1, 1 for i in range(2, n + 1): tmp = cur + pre pre = cur cur = tmp return cur # Static Method - Benchmarking Algorithms @staticmethod def benchmarkAlgorithm(algorithm, values): timer = Stopwatch() i = 0 testValue = 0 facTimeResult = BigInteger.Zero fibTimeResult = 0 # 'if-elif-else' Flow Control Statement if algorithm == 1: print '\nFactorial Imperative:' # 'For in range' Loop Statement for i in range(values.Count): testValue = values[i] # Taking Time timer.Start() facTimeResult = StaticFiborial.factorialI(testValue) timer.Stop() # Getting Time print ' (' + str(testValue) + ') = ', timer.Elapsed elif algorithm == 2: print '\nFactorial Recursive:' # 'While' Loop Statement while i < len(values): testValue = values[i] # Taking Time timer.Start() facTimeResult = StaticFiborial.factorialR(testValue) timer.Stop() # Getting Time print ' (' + str(testValue) + ') = ', timer.Elapsed i += 1 elif algorithm == 3: print '\nFibonacci Imperative:' # 'For in List' Loop Statement for item in values: testValue = item # Taking Time timer.Start() fibTimeResult = StaticFiborial.fibonacciI(testValue) timer.Stop() # Getting Time print ' (' + str(testValue) + ') = ', timer.Elapsed elif algorithm == 4: print '\nFibonacci Recursive:' # 'For in List' Loop Statement for item in values: testValue = item # Taking Time timer.Start() fibTimeResult = StaticFiborial.fibonacciR(testValue) timer.Stop() # Getting Time print ' (' + str(testValue) + ') = ', timer.Elapsed else: print 'DONG!' # Instance Class class InstanceFiborial(object): # Instances Field __className = '' # Instance Constructor def __init__(self): self.__className = 'Instance Constructor' print self.__className # Instance Method - Factorial Recursive def factorialR(self, n): # Calling Static Method return StaticFiborial.factorialR(n) # Instance Method - Factorial Imperative def factorialI(self, n): # Calling Static Method return StaticFiborial.factorialI(n) # Instance Method - Fibonacci Recursive def fibonacciR(self, n): # Calling Static Method return StaticFiborial.fibonacciR(n) # Instance Method - Fibonacci Imperative def fibonacciI(self, n): # Calling Static Method return StaticFiborial.fibonacciI(n) # Console Program def main(): print 'Static Class' # Calling Static Class and Methods # No instantiation needed. Calling method directly from the class print 'FacImp(5) = ', StaticFiborial.factorialI(5) print 'FacRec(5) = ', StaticFiborial.factorialR(5) print 'FibImp(11)= ', StaticFiborial.fibonacciI(11) print 'FibRec(11)= ', StaticFiborial.fibonacciR(11) print '\nInstance Class' # Calling Instance Class and Methods # Need to instantiate before using. Calling method from instantiated object ff = InstanceFiborial() print 'FacImp(5) = ', ff.factorialI(5) print 'FacRec(5) = ', ff.factorialR(5) print 'FibImp(11)= ', ff.fibonacciI(11) print 'FibRec(11)= ', ff.fibonacciR(11) # Create a (Python) list of values to test # From 5 to 50 by 5 values = [] for i in range(5,55,5): values.append(i) # Benchmarking Fibonacci # 1 = Factorial Imperative StaticFiborial.benchmarkAlgorithm(1, values) # 2 = Factorial Recursive StaticFiborial.benchmarkAlgorithm(2, values) # Benchmarking Factorial # 3 = Fibonacci Imperative StaticFiborial.benchmarkAlgorithm(3, values) # 4 = Fibonacci Recursive StaticFiborial.benchmarkAlgorithm(4, values) # Stop and exit Console.Read() if __name__ == '__main__': main()

And the Output is:

Humm, looks like Fibonnaci's algorithm implemented using recursion is definitively more complex than the others 3 right? I will grab these results for this and each of the upcoming posts to prepare a comparison of time execution between all the programming languages, then we will be able to talk about the algorithm's complexity as well.

**Printing the Factorial and Fibonacci Series**

import clr clr.AddReference('System.Numerics.dll') from System.Numerics import BigInteger from System.Text import StringBuilder from System import Console class Fiborial: # Using a StringBuilder as a list of string elements @staticmethod def getFactorialSeries(n): # Create the String that will hold the list series = StringBuilder() # We begin by concatenating the number you want to calculate # in the following format: "!# =" series.Append("!") series.Append(n) series.Append(" = ") # We iterate backwards through the elements of the series for i in range(n, 0, -1): # and append it to the list series.Append(i) if i > 1: series.Append(" * ") else: series.Append(" = ") # Get the result from the Factorial Method # and append it to the end of the list series.Append(Fiborial.factorial(n).ToString()) # return the list as a string return series.ToString() # Using a StringBuilder as a list of string elements @staticmethod def getFibonnaciSeries(n): # Create the String that will hold the list series = StringBuilder() # We begin by concatenating the first 3 values which # are always constant series.Append("0, 1, 1") # Then we calculate the Fibonacci of each element # and add append it to the list for i in range(2, n+1): if i < n: series.Append(", ") else: series.Append(" = ") series.Append(Fiborial.fibonacci(i)) # return the list as a string return series.ToString() @staticmethod def factorial(n): if n == 1: return BigInteger.One else: return BigInteger.Multiply(BigInteger(n), Fiborial.factorial(n-1)) @staticmethod def fibonacci(n): if n < 2: return 1 else: return Fiborial.fibonacci(n - 1) + Fiborial.fibonacci(n - 2) def main(): # Printing Factorial Series print "" print Fiborial.getFactorialSeries(5) print Fiborial.getFactorialSeries(7) print Fiborial.getFactorialSeries(9) print Fiborial.getFactorialSeries(11) print Fiborial.getFactorialSeries(40) # Printing Fibonacci Series print "" print Fiborial.getFibonnaciSeries(5) print Fiborial.getFibonnaciSeries(7) print Fiborial.getFibonnaciSeries(9) print Fiborial.getFibonnaciSeries(11) print Fiborial.getFibonnaciSeries(40) Console.Read() if __name__ == '__main__': main()

And the Output is:

**Mixing Instance and Static Members in the same Class**

Instance classes can contain both, instance and static members such as: fields, properties, constructors, methods, etc.

from System import Console # Instance Class class Fiborial: # Instance Field __instanceCount = 0 # Static Field __staticCount = 0 print "\nStatic Constructor", __staticCount # Instance Read-Only Property # Within instance members, you can always use # the "self" reference pointer to access your (instance) members. def getInstanceCount(self): return self.__instanceCount InstanceCount = property(getInstanceCount, None, None) # Static Property # looks like it is not supported even if the code identify it as such @staticmethod def getStaticCount(): return Fiborial.__staticCount #StaticCount = property(getStaticCount, None, None) # The problem seems to be the use of: property(getStaticCount,..) # it requires an instance method and not a static one (Test.getStaticCount) # Instance Constructor def __init__(self): self.__instanceCount = 0 print "\nInstance Constructor", self.__instanceCount # No Static Constructor #@staticmethod #def __init__(): # Fiborial.__staticCount = 0 # print "\nStatic Constructor", Fiborial.__staticCount # Instance Method def factorial(self, n): self.__instanceCount += 1 print "\nFactorial(" + str(n) + ")" # Static Method @staticmethod def fibonacci(n): Fiborial.__staticCount += 1 print "\nFibonacci(" + str(n) + ")" def main(): # Calling Static Constructor and Methods # No need to instantiate Fiborial.fibonacci(5) # Calling Instance Constructor and Methods # Instance required fib = Fiborial() fib.factorial(5) Fiborial.fibonacci(15) fib.factorial(5) # Calling Instance Constructor and Methods # for a second object fib2 = Fiborial() fib2.factorial(5) print "" # Calling Static Property # using the static method referenced by the property #print "Static Count =", Fiborial.StaticCount print "Static Count =", Fiborial.getStaticCount() # Calling Instance Property of object 1 and 2 print "Instance 1 Count =", fib.InstanceCount print "Instance 2 Count =", fib2.InstanceCount Console.Read() if __name__ == '__main__': main()

And the Output is:

**Factorial using int, float, System.Numerics.BigInteger**

So, it looks like integers in python can hold big integers, so using (Iron)Python int/long or System.Numerics.BigInteger is the same so not much to say here.

NOTE: as with the previous scripts you need to manually add a reference to the System.Numerics.dll assembly to your project or SearchPath + clr.AddReference so you can add it to your code.

import clr clr.AddReference('System.Numerics.dll') from System.Numerics import BigInteger from System import Console from System.Diagnostics import Stopwatch # Int/Long Factorial def factorial_int(n): if n == 1: return int(1) else: return int(n * factorial_int(n - 1)) # double/float Factorial def factorial_float(n): if n == 1: return float(1.0) else: return float(n * factorial_float(n - 1)) # BigInteger Factorial def factorial_bigint(n): if n == 1: return BigInteger.One else: return BigInteger.Multiply(BigInteger(n), factorial_bigint(n-1)) timer = Stopwatch() facIntResult = 0 facDblResult = 0.0 facBigResult = BigInteger.Zero i = 0 print "\nFactorial using Int/Long" # Benchmark Factorial using Int64 for i in range(5,55,5): timer.Start() facIntResult = factorial_int(i) timer.Stop() print " (" + str(i) + ") =", timer.Elapsed, " :", facIntResult print "\nFactorial using Float/Double" # Benchmark Factorial using Double for i in range(5,55,5): timer.Start() facDblResult = factorial_float(i) timer.Stop() print " (" + str(i) + ") =", timer.Elapsed, " :", facDblResult print "\nFactorial using BigInteger" # Benchmark Factorial using BigInteger for i in range(5,55,5): timer.Start() facBigResult = factorial_bigint(i) timer.Stop() print " (" + str(i) + ") =", timer.Elapsed, " :", facBigResult Console.Read()

And the Output is:

## No comments:

## Post a Comment