More Factorial Fun, Python and Lisp
This continues the factorial study started in the prior post. The factorial increases rapidly and can be programmed as a simple loop. The factorial, indicated with an exclamation point after a positive integer number is the product of all integers from 1 up to and including the integer.
Python
Python is powerful dynamic programming language. It has a large standard library and huge number of third party libraries. Python integrates well with other languages so that "low level" high efficiency languages can be used where needed. Notable Python packages include scipy, scientific-python, numpy, matplotlib and Sage. Scipy and Scientific python have numerical routines for science and engineering. Numpy includes fast numerical array and matrix operations. Matplotlib is an extensive plotting library. Saga is a very good math toolbox that runs a customized Python for math theory.The developers claim [http://www.python.org/about/]
- very clear, readable syntax
- strong introspection capabilities
- intuitive object orientation
- natural expression of procedural code
- full modularity, supporting hierarchical packages
- exception-based error handling
- very high level dynamic data types
- extensive standard libraries and third party modules for virtually every task
- extensions and modules easily written in C, C++ (or Java for Jython, or .NET languages for IronPython)
- embeddable within applications as a scripting interface
There are many differences between Python version 2 and Python version 3. Since Python 2 had some large libraries, many have not yet been ported to Python 3. For this factorial program the main difference is in the print statement.
1:#!/usr/bin/python
2:''' A program for computing the factorial of a number '''
3:while True:
4: line = input("Enter a number > 0, or 0 to quit :")
5: n = int(line)
6: if n < 1 : break
7: k=1
8: for i in range(1,n+1):
9: k *= i
10: print n,"! = ",k
Line by Line description
- A '# begins a one line comment. This comment on the first line indicates to use an shell or interpreter to run this program. If the file is made executable it can be executed with just its name.
- A special muti-line comment begins and ends with three quotes. This text will appear as documentation when a user ask for a description of the program with help().
- Begin the main loop. Continue to run while True is true. Note that capitalization is important and "true" does not equal "True". But "True" is true. The loop ends before the next line with the same indentation level or the end of the file.
- The "input" function will output the text argument to standard output then read standard input into a string. Convention is to use 4 spaces for each indentation level.
- The "int" function takes a string and converts it to an integer. Note that there is no type declarations, line is a string and n is an integer but that can change. We could have written "n = input("En ..." and "n = int(n)". Any variable can be any type at any time.
- Test the value of n and leave the main while loop if n <1
- Initialize k to 1
- Begin the factorial loop. Python does not have a typical index variable but will iterate over a list. The range command will generate a list running from the first number up to (not including) the second number.
- Multiply k by i
- Indicate the factorial loop has ended by returning to the indentation level of the for clause. Write to standard output, the value of n, some text then the value of k. The end of the file ends the main while loop.
#!/usr/bin/python3
''' A program for computing the factorial of a number '''
while True:
line = input("Enter a number > 0, or 0 to quit :")
try:
n = int(line)
except ValueError as err:
print(err)
continue
if n < 1 : break
k=1
for i in range(1,n+1):
k *= i
print ("{0}! = {1}".format(n,k))
An exception loop has been added that will check if the string input converts to an integer. The "try:" begins checking for exceptions and if a ValueError occurred print an error message and continue (i.e. return to the start of ) the while loop.
The print statement is different, the values to be written must be in parenthesis. A string format is used where the first format argument is placed at the "{0}" and the second at the "{1}". Using format removes the space after the value of "n" since a space is added between items in a print statement.
Excercises -
Save the first and/or second code (without line numbers) to fact.py
Make the file excetable, chmod u+x fact.py
Run the program, ./fact.py
Enter some numbers including 1,5,70,500, five and 0
Lisp (Common Lisp)
Lisp or LISt Programming language was written for artificial intelligence (AI) programming and has a different look. It is primarily a set of list, which are enclosed in parenthesis. The list can be a list of items or it can be a function (or macro). The first item in the list controls what it does. In a linguistic sense, Lisp commonly follows a Verb-Object-Subject sentence structure, which is one of the least common sentence structures in the world with only 3% of languages using it. An example list would be (* 1 2 3 4) which would multiply the values 1, 2, 3 and 4 returning their product. Normally lisp is run in an interpreter where each form is executed one at a time. A form is a list that does some action. Lisp takes some getting used to but provides an approach that is very practical and intuitive for some people. Lisp is also very flexible. The book
1:;; A program to compute the factorial of a number.
2:( loop
3: (format *query-io* "Enter a number > 0, or 0 to quit :" )
4: (setq n (parse-integer ( read-line *query-io*)))
5: (if (< n 1 ) (return) )
6: (setq k 1)
7: (loop
8: for i from 1 to n
9: do (setq k (* i k))
10: )
11: (format t "~a! = ~a~%" n k)
12:)
Line by Line description
- A comment in Lisp starts with a semicolon, ;. Convention is for normal comments to start with two semicolons and end of line comments to start with single semicolons that are aligned after all program text. Three semicolons are used for major comments.
- "( loop " begins a loop that ends at a matching close parenthesis it will process the instructions in order
- The format list will write to a stream with formatted text. "*query-io* is a global variable marked by the asterisk that points to the standard input and standard output. This is preferred to direct writing to standard output because "standard output" is often redirected to a file.
- "(setq" has three parts, the command setq, the variable name to be set, then the value to store in the variable. In this case 'n' is the variable and another list (or form) is the value. The (parse-integer takes a String and converts is to an integer. In this case the string comes from a '(read-line' which reads a string from the indicated '*query-io* stream.
- Note the list with a less than test then the variable n followed be the value 1. (< n 1) is equivalent to ( n < 1 ) in other languages and returns true if the value of n is less than 1. The if has a test followed by an action, in this case the action is to return or leave the loop.
- Set the value of k to 1. Note the there is no type specification for k. Lisp has dynamic typing so k could be set to a string or a stream or anything else for that matter.
- Begin the factorial loop
- The 'For' is an optional control for the loop. In this case 'i' will iterate from 1 to n.
- The 'do' is still part of the 'for' statement. The action within the loop is to set k equal to i*k.
- End of factorial loop
- Write a formatted string to 't'. 't' is short for standard output. Format instructions begin with tilde, ~. The '~a' writes the corresponding item in the list in human readable form. The ~% ends the line and sets the stream to the next line.
- Closes the outer main loop.
Save the code as fact.lisp without the line numbers.
Run the code 'clisp fact.lisp'
Test various numbers including 5,12,13,14,19,20,21 and 70
Enter 'five'
Since Lisp is an interpreted or shell language, the program itself can be made executable (at least on Unix type systems including Linux, BSD, Mac OSX) by adding "#!/usr/bin/clisp" as the first line and adding execute permission to the file (chmod u+x fact.lisp). Then just entering ./fact.lisp will run the program. In the added line, "/usr/bin/clisp", can be replaced with the full path of any lisp interpreter you want to use.
Currently, major programs written in Lisp are Maxima, a symbolic algebra program and EMACS, an extensible text editor. Both use their own Lisp dialect slightly different from Common Lisp. Common Lisp is a Language standard maintained by ANSI (American National Standards Institute).
Note that lisp is often run within a 'SLIME' environment which allows running programs as well as an interactive shell. The interactive shell is sometimes called REPL for read-eval-print loop and SLIME is Superior Lisp Interaction Mode for Emacs.
No comments:
Post a Comment