Re: [Tutor] From Numpy Import *

2007-11-09 Thread Evert Rol
 Thank-you!  It is important for us to avoid potential code  
 conflicts and so we'll standardize on the import package name  
 syntax.

 On a related note:
 We are using both NumPy and SciPy.  Consider the example y = Ax  
 where A is a sparse matrix.  If A is qualified as a scipy object  
 then do y and x also have to be scipy objects or can they be numpy  
 objects?


scipy is mostly written with numpy as its core, so in general you  
should be able to use numpy objects with scipy objects (not sure, but  
I guess most scipy objects will have a numpy object as their base).
The best is simply to try it out! In this particular case, x can be a  
numpy array; y is created in the process, so will be the type of  
object most suited to the outcome of the equation (ie, you cannot  
state beforehand if it's a numpy or scipy object); in this case,  
again a numpy array.
See also the scipy tutorial on the scipy.org website, where numpy and  
scipy objects are freely mixed.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] __doc__ strings for attributes?

2007-11-09 Thread Wesley Brooks
Dear Users,

How can I add information to an object to explain what it expects as
it's attributes? For instance I may have an object that creates a CAD
file based on a set of default values which are set by the __init__
but can be altered before it runs. for example;

class MakeBasicShape:
def __init__(self):
self.boundsOptions = ['cuboid', 'cylinder', 'cad']
self.boundsInfo = ['cuboid', [0.,10.,0.,10.,0.,10.]']

def MakeIt(self):
assert self.boundsInfo[0] in self.boundsOptions,
   Option not recognised: %s, self.boundsInfo[0]
if self.boundsInfo[0] == 'cuboid'
bounds = self.boundsInfo[1]
 # code to make box
elif self.boundsInfo[0] == 'cylinder'
[height, radius, noSides] = self.boundsInfo[1]
 # code to make cylinder
elif self.boundsInfo[0] == 'cad'
fileName = self.boundsInfo[1]
 # code to load CAD file
return shape


if __name__ == '__main__':
shapeFactory0 = MakeBasicShape()
shape0 = shapeFactory.MakeIt() # a box

shapeFactory1 = MakeBasicShape()
shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
shape1 = shapeFactory.MakeIt() # a cylinder

shapeFactory2 = MakeBasicShape()
shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
shape2 = shapeFactory.MakeIt() # a CAD file

While this example could be coded with different functions for making
a box, cylinder, and loading the CAD file I wanted to use attributes
to control the object to simplify interaction with it from the user
interface code. I would like to move away from getters and setters as
they're taking up vast chunks of my code at the moment and do very
little!

Can I also stop new attributes being added to the MakeBasicShape class?

Thanks in advance of any help.

Wesley Brooks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __doc__ strings for attributes?

2007-11-09 Thread Evert Rol
 How can I add information to an object to explain what it expects as
 it's attributes? For instance I may have an object that creates a CAD
 file based on a set of default values which are set by the __init__
 but can be altered before it runs. for example;

Why don't you specify a doc-string in your class declaration?

class MakeBasicShape:
 basic information

 detailed information about attributes
 


But, with what you do, why don't you add parameters to MakeIt()?

 def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
 self.boundsInfo = [shape, bounds]


Or perhaps, let your class be the object you're creating (and rename  
it to 'BasicShape'; verbs in class names seem a bit odd to me)? The  
__init__ method would then fulfill the function of the MakeIt method,  
and things would become:
shape0 = BasicShape()
shape1 = BasicShape('cylinder', [20.,10.,36.])
etc.

That is, unless you're doing other things in your factory object that  
don't show up here.


 def MakeIt(self):
 assert self.boundsInfo[0] in self.boundsOptions,
Option not recognised: %s, self.boundsInfo[0]

I also wouldn't use assert, but try: except:  in MakeIt() for example  
(assert is really for debugging, but here it looks more like you're  
trying to prevent user mistakes).


Anyway, hope that that gets you further.

   Evert


 if self.boundsInfo[0] == 'cuboid'
 bounds = self.boundsInfo[1]
  # code to make box
 elif self.boundsInfo[0] == 'cylinder'
 [height, radius, noSides] = self.boundsInfo[1]
  # code to make cylinder
 elif self.boundsInfo[0] == 'cad'
 fileName = self.boundsInfo[1]
  # code to load CAD file
 return shape


 if __name__ == '__main__':
 shapeFactory0 = MakeBasicShape()
 shape0 = shapeFactory.MakeIt() # a box

 shapeFactory1 = MakeBasicShape()
 shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
 shape1 = shapeFactory.MakeIt() # a cylinder

 shapeFactory2 = MakeBasicShape()
 shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
 shape2 = shapeFactory.MakeIt() # a CAD file

 While this example could be coded with different functions for making
 a box, cylinder, and loading the CAD file I wanted to use attributes
 to control the object to simplify interaction with it from the user
 interface code. I would like to move away from getters and setters as
 they're taking up vast chunks of my code at the moment and do very
 little!

 Can I also stop new attributes being added to the MakeBasicShape  
 class?

 Thanks in advance of any help.

 Wesley Brooks

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __doc__ strings for attributes?

2007-11-09 Thread Wesley Brooks
Thanks for the comments.

shape0 = BasicShape()
shape1 = BasicShape('cylinder', [20.,10.,36.])

I like this way of doing things, I could inherit the 3D data object's
class and get it to build on itself. I could for example use a
function definition like the following:

def __init__(*args, **paramDict):
self.args = args
self.xScanSpacing = paramDict['xScanSpacing']
etc.

and I get a very flexible base to expand on. I do however get a real
problem when it comes to documenting the expected keywords and running
into huge doc strings, when I prefer concise documentation.

I like the following:

class a:
def __init__(*args, **paramDict):
expectedParam = ['xScanSpacing', 'yScanSpacing']
paramDocDict = {'xScanSpacing': 'float mm spacing for x axis
hatches', ...}

To find out what parameters this object works with I could do;

 aa = a()
 aa.expectedParam
['xScanSpacing', 'yScanSpacing']
 aa.paramDocDict['xScanSpacing']
'float mm spacing for x axis hatches'

Is there an standard way of doing this?

This isn't as nice to use as the doc strings and dir function. For
example if I wanted to find out what I can do with a string I could
call dir(' ') on the interpreter and have a list of functions and
attributes contained in the string object. If I wanted a quick
explanation of one function I could run;

 print ' '.strip.__doc__
S.strip([chars]) - string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping


Cheers,

Wesley Brooks.

On 09/11/2007, Evert Rol [EMAIL PROTECTED] wrote:
  How can I add information to an object to explain what it expects as
  it's attributes? For instance I may have an object that creates a CAD
  file based on a set of default values which are set by the __init__
  but can be altered before it runs. for example;

 Why don't you specify a doc-string in your class declaration?

 class MakeBasicShape:
  basic information

  detailed information about attributes
  


 But, with what you do, why don't you add parameters to MakeIt()?

  def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
  self.boundsInfo = [shape, bounds]


 Or perhaps, let your class be the object you're creating (and rename
 it to 'BasicShape'; verbs in class names seem a bit odd to me)? The
 __init__ method would then fulfill the function of the MakeIt method,
 and things would become:
 shape0 = BasicShape()
 shape1 = BasicShape('cylinder', [20.,10.,36.])
 etc.

 That is, unless you're doing other things in your factory object that
 don't show up here.


  def MakeIt(self):
  assert self.boundsInfo[0] in self.boundsOptions,
 Option not recognised: %s, self.boundsInfo[0]

 I also wouldn't use assert, but try: except:  in MakeIt() for example
 (assert is really for debugging, but here it looks more like you're
 trying to prevent user mistakes).


 Anyway, hope that that gets you further.

Evert


  if self.boundsInfo[0] == 'cuboid'
  bounds = self.boundsInfo[1]
   # code to make box
  elif self.boundsInfo[0] == 'cylinder'
  [height, radius, noSides] = self.boundsInfo[1]
   # code to make cylinder
  elif self.boundsInfo[0] == 'cad'
  fileName = self.boundsInfo[1]
   # code to load CAD file
  return shape
 
 
  if __name__ == '__main__':
  shapeFactory0 = MakeBasicShape()
  shape0 = shapeFactory.MakeIt() # a box
 
  shapeFactory1 = MakeBasicShape()
  shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
  shape1 = shapeFactory.MakeIt() # a cylinder
 
  shapeFactory2 = MakeBasicShape()
  shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
  shape2 = shapeFactory.MakeIt() # a CAD file
 
  While this example could be coded with different functions for making
  a box, cylinder, and loading the CAD file I wanted to use attributes
  to control the object to simplify interaction with it from the user
  interface code. I would like to move away from getters and setters as
  they're taking up vast chunks of my code at the moment and do very
  little!
 
  Can I also stop new attributes being added to the MakeBasicShape
  class?
 
  Thanks in advance of any help.
 
  Wesley Brooks
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __doc__ strings for attributes?

2007-11-09 Thread Kent Johnson
Wesley Brooks wrote:

 I do however get a real
 problem when it comes to documenting the expected keywords and running
 into huge doc strings, when I prefer concise documentation.

 Is there an standard way of doing this?

docstrings are the only standard way to document classes and functions. 
Here is an example of long docstrings with lots of potential keyword args:
http://matplotlib.sourceforge.net/matplotlib.axes.html

Kent



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __doc__ strings for attributes?

2007-11-09 Thread Kent Johnson
Wesley Brooks wrote:
 Dear Users,
 
 How can I add information to an object to explain what it expects as
 it's attributes? For instance I may have an object that creates a CAD
 file based on a set of default values which are set by the __init__
 but can be altered before it runs. for example;
 
 class MakeBasicShape:
 def __init__(self):
 self.boundsOptions = ['cuboid', 'cylinder', 'cad']
 self.boundsInfo = ['cuboid', [0.,10.,0.,10.,0.,10.]']
 
 def MakeIt(self):
 assert self.boundsInfo[0] in self.boundsOptions,
Option not recognised: %s, self.boundsInfo[0]
 if self.boundsInfo[0] == 'cuboid'
 bounds = self.boundsInfo[1]
  # code to make box
 elif self.boundsInfo[0] == 'cylinder'
 [height, radius, noSides] = self.boundsInfo[1]
  # code to make cylinder
 elif self.boundsInfo[0] == 'cad'
 fileName = self.boundsInfo[1]
  # code to load CAD file
 return shape

I would write this as a factory function and use a dict as a lookup 
table to get the correct class to return:

assuming:
class Cuboid(object):
   # etc...

_makers = dict(cuboid=Cuboid, cylinder=Cylinder, cad=Cad)

def makeBasicShape(shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
   try:
 maker = _makers[shape]
   except KeyError:
 # Code to handle invalid shape option
   else:
 return maker(*bounds)

Kent

 
 
 if __name__ == '__main__':
 shapeFactory0 = MakeBasicShape()
 shape0 = shapeFactory.MakeIt() # a box
 
 shapeFactory1 = MakeBasicShape()
 shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
 shape1 = shapeFactory.MakeIt() # a cylinder
 
 shapeFactory2 = MakeBasicShape()
 shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
 shape2 = shapeFactory.MakeIt() # a CAD file
 
 While this example could be coded with different functions for making
 a box, cylinder, and loading the CAD file I wanted to use attributes
 to control the object to simplify interaction with it from the user
 interface code. I would like to move away from getters and setters as
 they're taking up vast chunks of my code at the moment and do very
 little!

Simple getters and setters are not needed in Python. The flexibility 
they give in Java and C++ is provided by Python properties.

 Can I also stop new attributes being added to the MakeBasicShape class?

Yes, but it is rarely worth the trouble; Python culture tends to a 
philosophy of we're all adults here and doesn't try too hard to 
prevent programmers from shooting themselves in the foot.

The preferred way to do this IIRC is to define __setattr__ on your class 
and check for valid attribute names.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __doc__ strings for attributes?

2007-11-09 Thread Evert Rol
 Thanks for the comments.

 shape0 = BasicShape()
 shape1 = BasicShape('cylinder', [20.,10.,36.])

 I like this way of doing things, I could inherit the 3D data object's
 class and get it to build on itself. I could for example use a
 function definition like the following:

 def __init__(*args, **paramDict):
 self.args = args
 self.xScanSpacing = paramDict['xScanSpacing']
 etc.

Careful; your 'self' argument is here included in *args. You'll want  
__init__(self, *args, ...)


 and I get a very flexible base to expand on. I do however get a real
 problem when it comes to documenting the expected keywords and running
 into huge doc strings, when I prefer concise documentation.

 I like the following:

 class a:
 def __init__(*args, **paramDict):
 expectedParam = ['xScanSpacing', 'yScanSpacing']
 paramDocDict = {'xScanSpacing': 'float mm spacing for x axis
 hatches', ...}

 To find out what parameters this object works with I could do;

 aa = a()
 aa.expectedParam
 ['xScanSpacing', 'yScanSpacing']
 aa.paramDocDict['xScanSpacing']
 'float mm spacing for x axis hatches'

 Is there an standard way of doing this?

In line with Kent's remark, I think you'll need doc strings. It's the  
whole point of documentation probably. And if you use the class often  
enough, you'll know the defaults and meaning of parameters anyway; no  
quick lookup needed (after all, here you need to first obtain an  
object from your class, then get the keyword names, before you can  
ask for the actual specifics; by that time, a 'help' on the class  
will have given you the information needed.)

Btw, consider using the help function instead of print the doc string  
(function/method/class.__doc__) additionally gives you the function  
declaration, as long as it's a Python-written function. Ie, you'll  
directly see the required parameters (in won't work for builtin  
functions like map, or the string-strip as below, but will work for  
home-written stuff).
It also gives you a lot more information in general. Compare help 
(dict) versus print dict.__doc__



 This isn't as nice to use as the doc strings and dir function. For
 example if I wanted to find out what I can do with a string I could
 call dir(' ') on the interpreter and have a list of functions and
 attributes contained in the string object. If I wanted a quick
 explanation of one function I could run;

 print ' '.strip.__doc__
 S.strip([chars]) - string or unicode

 Return a copy of the string S with leading and trailing
 whitespace removed.
 If chars is given and not None, remove characters in chars instead.
 If chars is unicode, S will be converted to unicode before stripping


 Cheers,

 Wesley Brooks.

 On 09/11/2007, Evert Rol [EMAIL PROTECTED] wrote:
 How can I add information to an object to explain what it expects as
 it's attributes? For instance I may have an object that creates a  
 CAD
 file based on a set of default values which are set by the __init__
 but can be altered before it runs. for example;

 Why don't you specify a doc-string in your class declaration?

 class MakeBasicShape:
  basic information

  detailed information about attributes
  


 But, with what you do, why don't you add parameters to MakeIt()?

  def MakeIt(self, shape='cuboid', bounds=[0.,10.,0.,10.,0.,10.]):
  self.boundsInfo = [shape, bounds]


 Or perhaps, let your class be the object you're creating (and rename
 it to 'BasicShape'; verbs in class names seem a bit odd to me)? The
 __init__ method would then fulfill the function of the MakeIt method,
 and things would become:
 shape0 = BasicShape()
 shape1 = BasicShape('cylinder', [20.,10.,36.])
 etc.

 That is, unless you're doing other things in your factory object that
 don't show up here.


 def MakeIt(self):
 assert self.boundsInfo[0] in self.boundsOptions,
Option not recognised: %s, self.boundsInfo[0]

 I also wouldn't use assert, but try: except:  in MakeIt() for example
 (assert is really for debugging, but here it looks more like you're
 trying to prevent user mistakes).


 Anyway, hope that that gets you further.

Evert


 if self.boundsInfo[0] == 'cuboid'
 bounds = self.boundsInfo[1]
  # code to make box
 elif self.boundsInfo[0] == 'cylinder'
 [height, radius, noSides] = self.boundsInfo[1]
  # code to make cylinder
 elif self.boundsInfo[0] == 'cad'
 fileName = self.boundsInfo[1]
  # code to load CAD file
 return shape


 if __name__ == '__main__':
 shapeFactory0 = MakeBasicShape()
 shape0 = shapeFactory.MakeIt() # a box

 shapeFactory1 = MakeBasicShape()
 shapeFactory1.boundsInfo = ['cylinder' ,[20.,10.,36]]
 shape1 = shapeFactory.MakeIt() # a cylinder

 shapeFactory2 = MakeBasicShape()
 shapeFactory2.boundsInfo = ['cad' ,'/home/Wes/BigHand.stl']
 shape2 = shapeFactory.MakeIt() # a CAD 

[Tutor] Type() Getting Type Error

2007-11-09 Thread Chernev Chernev
I'm debugging a script and want to check the type of an object.

So in the script I write:
print type([object]

This bombs, and I get
TypeError: 'str' object is not callable'

I've also tried
x = type([object])
print x

Same thing.

In the interactive, 'type([object])' works fine.

What am I missing here?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type() Getting Type Error

2007-11-09 Thread Kent Johnson
Chernev Chernev wrote:
 I'm debugging a script and want to check the type of an object.
 
 So in the script I write:
 print type([object]
 
 This bombs, and I get
 TypeError: 'str' object is not callable'
 
 What am I missing here?

Probably you have a variable named 'type' in your script that is hiding 
the builtin 'type' object.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type() Getting Type Error

2007-11-09 Thread Evert Rol

On 9 Nov 2007, at 14:48 , Chernev Chernev wrote:

 I'm debugging a script and want to check the type of an object.

 So in the script I write:
 print type([object]

 This bombs, and I get
 TypeError: 'str' object is not callable'

 I've also tried
 x = type([object])
 print x

 Same thing.

Works fine for me for both cases. What version of Python are you  
running? Both 2.5 and 2.3 seem to work for me (on Mac OS X).

Is there anything else in your script that can cause this error?



 In the interactive, 'type([object])' works fine.

 What am I missing here?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type() Getting Type Error

2007-11-09 Thread Chernev Chernev
On Nov 9, 2007 10:09 AM, Kent Johnson [EMAIL PROTECTED] wrote:
  So in the script I write:
  print type([object]
 
  This bombs, and I get
  TypeError: 'str' object is not callable'
 
 Probably you have a variable named 'type' in your script that is hiding
 the builtin 'type' object.

Just so.  I renamed that variable and the script ran fine.

Thank you, and thanks to everyone who looked at this.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New Introductory Book

2007-11-09 Thread bhaaluu
Algorithm Education in Python
http://www.ece.uci.edu/~chou/py02/python.html

This article from Pai H. Chou at University of California, Irvine
shows how well the Python programming language maps itself
to the pseudocode used in _Introduction to Algorithms Second Editon_
[Corman, Leiserson, Rivest, Stein. 2001. McGraw-Hill. ISBN 0262032937].

Excerpt from the article:
quote
7. Conclusions and Future Educational Plans
This paper reports our use of Python in an algorithms course in the
past two years. As an
algorithm-oriented language, Python enables our students to learn key
concepts in algorithm
design, instead of struggling with low-level, idiosyncratic features
of conventional programming
languages. The way Python handles data types represents a perfect
match with the way
textbooks present algorithms, and its interpretive nature encourages
students to experiment
with the language.
/quote

I have a copy of Corman, and it really is amazing how Python all the
pseudocode is!

On Nov 8, 2007 6:01 PM, Danyelle Gragsone [EMAIL PROTECTED] wrote:
 This is why I am going for programming instead of just CS. I am a very
 hands on person.. although I know theory is good.. I just think it
 needs to be evened out a bit :D.

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/python/index.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Type() Getting Type Error

2007-11-09 Thread Alan Gauld

Chernev Chernev [EMAIL PROTECTED] wrote

 So in the script I write:
 print type([object]
 
 This bombs, and I get
 TypeError: 'str' object is not callable'

 In the interactive, 'type([object])' works fine.

Looks like you have defined type as a local variable 
somewhere in your script and this is masking the 
type() function.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] In-place expansion of list members... possible?

2007-11-09 Thread Ricardo Aráoz
Kent Johnson wrote:
 Marc Tompkins wrote:
 I'm working with delimited files (ANSI X12 EDI nonsense, to be 
 precise.)  First I load the records to a list:
 tmpSegs = inString.split(self.SegTerm)

 Now, I want to replace each string in that list with a string:

 for seg in tmpSegs:   # 'seg' is short for 'segment'
 seg = seg.split(self.ElemSep)

 It doesn't work.  If I check the contents of tmpSegs, it's still a list 
 of strings - not a list of lists.  So I do this instead:
 tmpSegs2 = []
 for seg in tmpSegs:
 tmpSegs2.append(seg.split(self.sElemSep))
 del tmpSegs

 This works.  And, for the size of files that I'm likely to run into, 
 creating the extra list and burning the old one is probably not going to 
 swamp the machine - but it feels clumsy to me, like if I just knew the 
 secret I could be much more elegant about it.
 
 Creating a new list is fine, actually. You can do it more elegantly with 
 a list comprehension, and it's fine to assign to the same name, which 
 will implicitly delete the old list:
 tmpSegs = [ seg.split(self.ElemSep) for seg in tmpSegs ]
 
 If you really want to replace elements in the same list you can use 
 enumerate to get indices:
 
 for i, seg in enumerate(tmpSegs):
tmpSegs[i] = seg.split(self.ElemSep)
 
 or use slice assignment:
 tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]

Won't the slice assignment create a new list and then assign it to the
old list (which the OP is trying to avoid)?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] manipulating data

2007-11-09 Thread Ricardo Aráoz
Kent Johnson wrote:
 Bryan Fodness wrote:
 I would like to have my data in a format so that I can create a contour plot.

 My data is in a file with a format, where there may be multiple fields

 field = 1

 1a   0
 
 If your data is really this regular, it is pretty easy to parse. A 
 useful technique is to access a file's next method directly. Something 
 like this (not tested!):
 
 f = open('data.txt')
 fields = {} # build a dict of fields
 try:
while True:
  # Get the field line
  line = f.next()
  field = int(line.split()[-1]) # last part of the line as an int
 
  f.next() # skip blank line
 
  data = {} # for each field, map (row, col) to value
  for i in range(20): # read 20 data lines
line = f.next()
ix, value = f.split()
row = int(ix[:-1])
col = ix[-1]
data[row, col] = int(value)
 
  fields[field] = data
 
  f.next()
 except StopIteration:
pass
 

Or maybe just (untested) :

fields = {} # build a dict of fields
for line in open('data.txt') :
if line :# skip blank lines
if line.split()[0] = 'field' :
field = int(line.split()[-1])
else :
fields[field] = tuple(line.split())




___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] parsing an array

2007-11-09 Thread sith .
newfile = open('y.txt')
   for line in newfile:
  ...  print line.rstrip()
  
3 5 7
  11 8 10
   
  Hi,
I'm trying to parse an array.  Now that I can open and read lines in my array, 
how can I access individual elements of my multidimensional array?  I'd like to 
loop through the array and compare values in each line.  
If w is the array, if w[0][1]w[0][2], write w[0][0] to w[0][3]
Numpy?  Thanks.

 __
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Calling a function within a function within a class...

2007-11-09 Thread Trey Keown
Hey all...
I'm creating a module for my program, and I need to call a function.
Here's how it's set up:
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
class DoStuff:
def Thing1(self):
def ThingToCall(self):
print It worked!
def Thing2(self):
#Call the function ThingToCall here.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Thanks for any help. I haven't used classes that much before...

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling a function within a function within a class...

2007-11-09 Thread Eric Brunson
Trey Keown wrote:
 Hey all...
 I'm creating a module for my program, and I need to call a function.
 Here's how it's set up:
 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 class DoStuff:
 def Thing1(self):
 def ThingToCall(self):
 print It worked!
 def Thing2(self):
 #Call the function ThingToCall here.
 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 Thanks for any help. I haven't used classes that much before...

 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
   

Unless someone knows something very clever, I don't think you can.  One 
of the few reasons to declare a function like that is to make the scope 
local to Thing1() so you can pretty much expressly *not* call it from 
outside that scope.  If you don't have a good reason for declaring the 
function in that manner, you shouldn't, especially if you have a need to 
call externally from enclosing scope.

The obvious question is, why would you do that?  :-)

e.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parsing an array

2007-11-09 Thread O.R.Senthil Kumaran
* sith . [EMAIL PROTECTED] [2007-11-09 17:53:53]:

 newfile = open('y.txt')
for line in newfile:
   ...  print line.rstrip()
   
 3 5 7
   11 8 10

This example is different from a array handling one. This is a file handle with 
with reading the contents of the file through a loop.


   Hi,
 I'm trying to parse an array.  Now that I can open and read lines in my 
 array, how can I access individual elements of my multidimensional array?  
 I'd like to loop through the array and compare values in each line.  
 If w is the array, if w[0][1]w[0][2], write w[0][0] to w[0][3]
 Numpy?  Thanks.

You dont require Numpy for a simple task as this.
Suppose your array is:

a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]

You cannot modify the same array when you are looping through it. You have to 
loop through the copy of the contents :- a[:].

# Untested code

for i in a[:]: # You are looping through the copy of contents
   for j in i:
   # implement your logic with j
   if j  i[0]: # or any dynamic conditional check.
  a[i][j] = j


Does this help you?

Thanks,

-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Swapping variables ...

2007-11-09 Thread Aditya Lal
 After quizzing newbies in C on swapping without 3rd variable, I found this
to be really *cool* construct to swap :)
x = 10
y = 20
x,y = y,x

--
Aditya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] *args, **kargs as arguments

2007-11-09 Thread O.R.Senthil Kumaran
I know it can be a FAQ, but still I want ask to clarify my doubts and
assumptions.

I find usually in derived classes, a construct like this:

class Derived(BaseClass):
def __init__(self, *args, **kargs):
BaseClass.__init__(self, *args, **kargs)


- *args, **kargs passes a tuple and a dictionary to the BaseClass constructor.

My assumption is the BaseClass will always have a constructor that will
be receiving the tuple and a dictionary. Am I right?

Something of the sort.

class BaseClass:
def __init__(self, atuple, adict):

I also found a construct something like this:

class URLopener:
def __init__(self, proxies=None, **x509):

This is specifically from urllib.py where my doubts stem from.
Is the above construct still receiving a tuple and a dictionary?


Another doubt is, if we are not explicitly passing a dictionary, and the
dictionary is not a default argument, then is the dictionary values being 
passed through the namespace? 

I am scanning through the urllib.py code to understand the urlopen method and I 
am having the above doubts when trying to understand it. Please help.

Thank you.
-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] In-place expansion of list members... possible?

2007-11-09 Thread Kent Johnson
Ricardo Aráoz wrote:
 Kent Johnson wrote:
 or use slice assignment:
 tmpSegs[:] = [ seg.split(self.ElemSep) for seg in tmpSegs ]
 
 Won't the slice assignment create a new list and then assign it to the
 old list (which the OP is trying to avoid)?

Yes, it will, thanks! You can assign a generator expression to the list:
tmpSegs[:] = ( seg.split(self.ElemSep) for seg in tmpSegs )

I don't know if that creates a temp list or assigns directly into the 
old list though. At the byte-code level at least it seems to assign the 
iterator to the slice.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] *args, **kargs as arguments

2007-11-09 Thread wesley chun
hi, and welcome to Python!!

 class Derived(BaseClass):
 def __init__(self, *args, **kargs):
 BaseClass.__init__(self, *args, **kargs)

 - *args, **kargs passes a tuple and a dictionary to the BaseClass constructor.

 My assumption is the BaseClass will always have a constructor that will
 be receiving the tuple and a dictionary. Am I right?

not quite.  you're on the right track though. a couple of thoughts.
let's take this question outside of classes for a moment.

1. you are not receiving a tuple or dict. rather, any variables
(non-keyworded and keyworded) will be passed to those designated
variables if there are no direct variables corresponding to those
parameters. let's talk about the '*' for a moment.  when placed in a
function signature, it means to accept a variable number of arguments.
 for example:

def foo(x, *rest):
 pass

you can call foo() with one argument only, i.e., foo(123), foo('xxx'),
etc.  but you can also call this argument with any number of
parameters, i.e., foo(123, 'xyz'), foo(3.14, 'xyz', 123), etc.  the
1st argument will be assigned to 'x' while the rest of the arguments
get put into the tuple 'rest':  x = 3.14 and rest = ('xyz', 123). if
only 'x' is passed in, the 'rest' is an empty tuple. this differs
from:

def foo(*all):
pass

in the earlier example, 'x' is required.  in this example, no
parameters are required. foo() is just as good as foo(123), foo(123,
'xyz'), etc.

2. this is not a question you asked, but sometimes people get confused
when '*' is used in function *calls* (vs. signatures as in the above).
when you define a function like this:

def foo(x, y, z):
pass

you must call foo() with 3 parameters, i.e., foo(12, 'abc', 3.14).
one use of the * is to designate its members as parameters to the
called function. the use case comes up when you have a list, say t =
[12, 'abc', 3.14].  to call the function, you would have to do this:
foo(t[0], t[1], t[2]).

now, intuitively, you would naturally ask the question, can i pass in
the entire list such that all of its elements are assigned to the
individual parameters?  the answer is YES: foo(*t) does the same
thing, but is easier on the programmer, yet does not make the code
significantly more complicated

3. the same arguments above apply to '**', dictionaries, and keyworded
arguments like, foo=123.

4. also not 100%-related to your question:  __init__() is not really a
constructor in the true sense.  in Python, the *interpreter* creates
the instance object *for* you, one of the reasons why there is no
new keyword.  __init__() is the 1st method that the interpreter
calls after it creates the instance for you.  when you instantiate a
class, you call the class as if it were a function, i.e., Derived().
in the example above with __init__(self, *t, **d), this just means
that this function can take any number of both keyworded or
non-keyworded parameters.

 class BaseClass:
 def __init__(self, atuple, adict):

this signature differs from __init__(self, *atuple, **adict) because
the former takes exactly 2 arguments (in addition to 'self') while
this latter one can take any number of arguments.

 I also found a construct something like this:

 class URLopener:
 def __init__(self, proxies=None, **x509):

this function potentially takes a single object (assigned to proxies)
and any number of keyworded arguments (which go into the 'x509' dict).

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor