A new to Python question

Robert Kern rkern at ucsd.edu
Sat May 14 15:33:37 EDT 2005


David wrote:
> Thank you very much.  Tulpes are really neat now that I've looked at
> them.  So after just fixing it, I changed it up and I would like to
> show it off now.
> 
> #! /usr/bin/python
> #This program takes two vectors and multiplies them
> #against a 10X10 array.  It also then gives the dot product,
> #sum, and max value of the array.
> 
> import Numeric
> def abc(package):
>     """Takes two arrays and performs predetermined calculations,
>        Then returns the solutions back as the same array, along
>        with the dot product, sum, and max value of the array.
> 
>        Data slots:
>            0 - First Array
>            1 - Second Array
>            2 - Dot product
>            3 - Sum
>            4 - Max Value"""
>     f = Numeric.zeros((10,10))
>     for i in range(10):
>         for j in range(10):
>             f[i,j] = (i+1)+(j+1)
> 
>     e = Numeric.matrixmultiply(f, package[0])
>     g = Numeric.matrixmultiply(Numeric.transpose(f),package[1])
>     package[0] = e
>     package[1] = g
>     package[2] = Numeric.dot(package[0],package[1])
>     package[3] = Numeric.sum(package[0])
>     package[4] = package[1][Numeric.argmax(package[1])]
>     return package
> 
> data = [Numeric.arange(1,11),Numeric.arange(1,11)*2,0,0,0]
> #data = [Array X, Array Y, Dot product, Sum, Max Value]
> 
> print 'Array X:',data[0]
> print 'Array Y:',data[1]
> 
> data = abc(data)
> 
> print 'Calling function abc'
> print 'Array X:',data[0]
> print 'Array Y:',data[1]
> print 'Dot Product of X and Y:',data[2]
> print 'Sum of array X:',data[3]
> print 'Max value of array Y:',data[4]
> 
> I think its just wonderful now, but if you got any other suggestions,
> Please do tell.  Thanks everyone.

It's still not very Pythonic. Don't bother putting outputs in the 
argument list. There are some good use cases for doing so, but until 
you've been writing Python code for a while and the Pythonic idioms come 
naturally to you, you should probably resist the urge. Python is not 
Fortran.

def abc(x, y):
    ...
    e = Numeric.matrixmultiply(f, x)
    g = Numeric.matrixmultiply(Numeric.transpose(f), y)
    dotp = Numeric.dot(x, y)
    sumx = Numeric.sum(x)
    maxy = Numeric.maximum.reduce(y)
    return e, g, dotp, sumx, maxy

x = Numeric.arange(1,11)
y = x*2

x, y, dotp, sumx, maxy = abc(x, y)

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the Python-list mailing list