Syntax Highlighting
Tuesday, 1 January 2013
ProgEx: Python Ex rev 1 Code
# Number functions
# A program written for Exercise 1 of 15 programming exercises.
# As specified in knowing.net
# The aim of this exercise is to familiarise with basic code constructs,
# basic operators, standard libraries, simple maths, arrays, functional
# programming concepts (map and apply?), parsing input, error handling, etc.
#
# The aim of this module is to create a simple program that will
# take as its first argument one of the following arguments:
# sum, product, mean, sqrt,
# The remainder of the arguments will be a list numbers that the
# functions apply to.
# This module is inteded to be called from shell of the OS., eg
#
# c:\python\exercises\numberfun.py sum 2 3 4 5
# 14
#
# Extensions and maintenance guide:
# To add extra functions:
# - Define the function in the Function Definitions
# - Add the function to the function table with its 'call'
# - Implement any exceptional behaviour in the main program and
# document it.
from __future__ import division
import math
import cmath
import sys
# The module is divided into the following sections:
# 1) Function Definitions
# 2) Function Lookup table
# 3) Main program definition
# 4) The command to run
### Function Definitions
## sum
#def sum(lst):
# return reduce ((lambda x,y: x+y), lst, 0)
#
# sum is an inbuit function
## product
def product(lst):
return reduce ((lambda x,y: x*y), lst, 1)
## mean
def mean(lst):
return (reduce ((lambda x,y: x+y), lst, 1)) / len(lst)
## sqrt
def sqrt(lst):
return map (math.sqrt, lst)
def csqrt(lst):
return map (cmath.sqrt, lst)
## help
def numberfunhelp():
print """"
Help for numberfun: an exercise in learning."""
## Function table:
functiontable = {'sum': sum,
'product': product,
'mean': mean,
'sqrt': sqrt,
'help': numberfunhelp}
#########################################################
### Program Starts Here.
## Error check the arguments
## and run the program
def doit(lst): # lst is command line argument strings
numlst = [] # the numeric equivalent of the argument strings.
for el in lst[2:]:
try:
numlst.append(float(el))
except ValueError:
print '%s is not a valid number' % el
exit
# final chance for exceptional functions:
if any(map((lambda x: x<0), numlst)):
functiontable["sqrt"] = csqrt
if lst[1] in functiontable:
return map(functiontable[lst[1]], [numlst])[0]
else:
print "Function %s not implemented" % lst[1]
exit
print doit(sys.argv)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment