[Tutor] installing python 2.4.1 over 2.4

2005-05-22 Thread Pujo Aji
Hello,

I have python 2.4.
I would like to install python 2.4.1, Should I uninstall python 2.4,
or just install 2.4.1?

Does it effect my ide such as pydev and komodo ?

Sincerely Yours,
pujo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting a directory

2005-05-24 Thread Pujo Aji
you can sort listsource based on listkey

For example:
you have listsource = ['c','b','a']
and listkey = [2,3,1] # this will be used to sort listsource.

def sortbasedlist(sources,keys):
  #combine (key,sources)
  Kombin = [(keys[i],sources[i]) for i in range(len(sources))]
  Kombin.sort()
  return [source for (key,source) in Kombin]

main program:

  print sortbasedlist(listsource,listkey) # this will result ('a','c','b')

And for your problem you can do something like this:
# suppose files already found and can be considered as source
filesKey = [x[-2:] for x in files]
Result = sortbasedlist(files,filesKey)

good luck.
pujo



On 5/24/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Jonas Melian wrote:
> > Kent Johnson wrote:
> >>files = glob.glob(os.path.join(dir_locales, "*_[A-Z][A-Z]"))
> >>files.sort(key=lastTwoChars)  # Note: NOT key=lastTwoChars()
> >
> > I get:
> > ::
> > files.sort(key=lastTwoChars)
> > TypeError: sort() takes no keyword arguments
> > ::
> >
> > Could it be by the Python version? I have Python 2.3.5
> 
> Yes, the key= parameter is new in Python 2.4. For Python 2.3 you can define a 
> comparison function, e.g.
> 
> def cmpLastTwoChars(a, b):
>return cmp(a[-2:], b[-2:])
> 
> files.sort(cmpLastTwoChars)
> 
> Kent
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Am I making this harder than it needs to be?

2005-05-25 Thread Pujo Aji
try this code:
L = [(1,11),(2,22)]
print max(L)
print min(L)

I don't know if that what you want.

good luck
pujo

On 5/25/05, Ron Phillips <[EMAIL PROTECTED]> wrote:
>  
> short version: I  need a way to get max and min E and N out of
> [(E0,N0),(E1,N1)...(En,Nn)] without reordering the list 
>   
> long version: 
>   
> I would like a list of geographic coordinates (Easting, Northing) to
> maintain a "bounding box"
> [(minEasting,minNorthing),(maxEasting,maxNorthing)]
> attribute. 
>   
> I did it like this: 
>   
> class geoCoordinateList(UserList):
> def __init__(self):
> UserList.__init__(self)
> self.boundingBox = geoBox(minEN=geoCoordinate(),
>   maxEN=geoCoordinate())
>  
> def append(self, geoCoord):
> self.extend([geoCoord])
> self.boundingBox.challenge(geoCoord)#bumps the max and min if
> necessary
>  
> but I'd have to override almost all the UserList methods, unless there's a
> way to call boundingBox.challenge() on any change to the list. 
>   
> The other way I thought would be to make a getBB method, like: 
>   
> def getBB(self):
> new=geoBox()
> for gC in self:
> new.challenge(gC)#bumps the corners if needed 
> self.boundingBox=new
> return(new)
>  
> but that seems like a lot of churning if nothing has changed. 
>   
> I suspect there's some slick, readable way to do this, and when I see it
> I'll say "Doh!" 
>   
>   
>   
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-05-26 Thread Pujo Aji
Actually you can do the same way:

# Convert intAscii to charAscii
S = [chr(x) for x in range(0,256)]
for x in S: print x

#Convert charAscii to intAscii
AsciiInt = [ord(x) for x in S]
for x in AsciiInt: print x

Best Regards,
pujo

On 5/26/05, John Carmona <[EMAIL PROTECTED]> wrote:
> With the help of Pujo Aji I have written this little script that print every
> single ASCII code>>
> 
> S = [chr(x) for x in range (0,256)]
> for x in S:
> print x,
> 
> The next step is to use the built-in functin ord() in order to convert each
> character to an ASCII integer. I have had a look at the ord() function but
> it says that it only take one argument i.e. ord('a'). How could I execute to
> convert each character into an ASCII integer?
> 
> Thanks in advance
> JC
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a generic table data structure for table / 2d array / lookup table?

2005-05-28 Thread Pujo Aji
You can create small class with handle table thing and use dictionary
as the main data.
Look at this code:

class mytable:
  def __init__(self):
self.dat = {}
pass
  def input(self,row,col,val):
self.dat[row] = {col:val}
pass
  def output(self,row,col):
try: return self.dat[row][col]
except: return None
pass

if __name__ == '__main__':
  mytab = mytable()
  mytab.input(1,'A','cat')
  
  # Ok
  print mytab.output(1,'A') # it will result 'cat'
  
  # Not Ok --> No Data
  print mytab.output(2,'B') # it will result None


Sincerely Yours,
Pujo Aji

On 5/28/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Marcus Goldfish wrote:
> > Before I try to reinvent the wheel, can anyone point me to a data
> > structure suitable for storing non-numeric, 2-d arrays.  For instance,
> > something that can store the following:
> >
> > A  B  C  D
> >  1   'cat' 3object  9
> >  J4  [1] 56
> >
> > where the column and row labels in this example are ['A','B','C','D']
> > and [1,'J'], respectively.  I need to access (set and get values) by
> > cell, row, and column.
> >
> > I have a solution using 2-tuple keys and a dict, e.g., d[('A',1)], but
> > it seems kludgy and doesn't handle the row/column access.
> >
> > Any pointers or code snippets would be appreciated!
> 
> You caught me in a good mood this morning. I woke to sunshine for the first 
> time in many days, that
> might have something to do with it :-)
> 
> Here is a dict subclass that extends __getitem__ and __setitem__ to allow 
> setting an entire row. I
> included extensive doctests to show you what it does.
> 
> Note: you can write d['A',1] instead of d[('A',1)], which looks a little 
> cleaner.
> 
> Kent
> 
> class Grid(dict):
>  """
>  A two-dimensional array that can be accessed by row, by column, or by 
> cell.
> 
>  Create with lists of row and column names plus any valid dict() 
> constructor args.
> 
>  >>> data = Grid( ['A', 'B'], [1, 2] )
> 
>  Row and column lists must not have any values in common.
> 
>  >>> data = Grid([1, 2], [2, 3])
>  Traceback (most recent call last):
>  ...
>  ValueError: Row and column lists must not have any values in common
> 
>  Here is an example with data:
> 
>  >>> rowNames = ['A','B','C','D']
>  >>> colNames = [1,'J']
>  >>> rawData = [ 'cat', 3, object, 9, 4, [1], 5, 6 ]
>  >>> indices = [ (row, col) for col in colNames for row in rowNames ]
>  >>> data = Grid(rowNames, colNames, zip(indices, rawData))
> 
> 
>  Data can be accessed by cell:
> 
>  >>> for i in indices:
>  ...print i, data[i]
>  ('A', 1) cat
>  ('B', 1) 3
>  ('C', 1) 
>  ('D', 1) 9
>  ('A', 'J') 4
>  ('B', 'J') [1]
>  ('C', 'J') 5
>  ('D', 'J') 6
> 
>  >>> data['B', 'J'] = 5
> 
> 
>  Cell indices must contain valid row and column names:
> 
>  >>> data[3]
>  Traceback (most recent call last):
>  ...
>  KeyError: 3
> 
>  >>> data['C', 2] = 5
>  Traceback (most recent call last):
>  ...
>  ValueError: Invalid key or value: Grid[('C', 2)] = 5
> 
> 
>  Data can be accessed by row or column index alone to set or retrieve
>  an entire row or column:
> 
>  >>> print data['A']
>  ['cat', 4]
> 
>  >>> print data[1]
>  ['cat', 3, , 9]
> 
>  >>> data['A'] = ['dog', 2]
>  >>> print data['A']
>  ['dog', 2]
> 
> 
>  When setting a row or column, data must be the correct length.
> 
>  >>> data['A'] = ['dog']
>  Traceback (most recent call last):
>  ...
>  ValueError: Invalid key or value: Grid['A'] = ['dog']
> 
>  """
> 
>  def __init__(self, rowNames, colNames, *args, **kwds):
>  dict.__init__(self, *args, **kwds)
>  self.rowNames = list(rowNames)
>  self.colNames = list(colNames)
> 
>  # Check for n

Re: [Tutor] Planning a program with algorithm?

2005-05-29 Thread Pujo Aji
Before you write algorithm it is always good to know every aspect of
the programing language you will use.

python has built in function like set, data like list, dictionary,
style like list comprehension, lambda etc that worth knowing
before you start to write algorithm.

It is always good to write program as soon as you have in my mind. in
old program paradigm sometimes we needs planning, python makes it
possible to do less planning because it is less typing language with
battery included style. sometimes python code is more clear than the
algorithm.  : )

About planning bigger project, I suggest you use extreme programming
style (like refactoring etc,), since good program sometimes needs you
to change your code quiet often.

pujo

On 5/29/05, . , <[EMAIL PROTECTED]> wrote:
> I know how to write a prog.
> 
> But, I don't know how to plan a prog. with algorithm.
> 
> If algorithm of a part of a prog. is like..
> ---
> create an empty jumble word
> while the chosen word has letters in it
> extract a random letter from the chosen word
> add the random letter to the jumble word
> ---
> 
> It would be like..
> ---
> jumble = ""
> while word:
> position = random.random(len(word))
> jumble += word[position]
> word = word[:position] + word[(position+1):]
> ---
> 
> 
> If the prog. is like..
> ---
> #Game List
> 
> list = ("GT4",
>  "GTA Sanandreas",
>  "Takken 5")
> 
> print "My Games: "
> for i in list:
>print i
> 
> print "\nI've got", len(list), "games."
> 
> add = raw_input(\n\nAdd more games: ")
> adding = (add)
> list += adding
> 
> print "Total games are..."
> print list
> 
> raw_input("exit.")
> ---
> 
> What would the algorithm be for the prog.?
> 
> Any useful advice for algorithm would be appreciated.
> 
> Thanks.
> 
> _
> Express yourself instantly with MSN Messenger! Download today it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] insering into lists through slices

2005-06-03 Thread Pujo Aji
when you operate slice be carefull of the position of pointer which
slice the list:

L = [0  , 1 , 2 , 3]
^ ^
 pos 0 1

That's why :
  L = [1,2,3]
  L[0:1] = [7]
  print L  # will replace element 1

  L = [1,2,3]
  L[1:1] = [7]
  print L # will insert 7 between element 1 and 2


pujo



On 6/3/05, venkata subramanian <[EMAIL PROTECTED]> wrote:
> Hi,
>   I am a newbie to Python (that's very guessable).
>   I simply fail to understand the semantics of the following piece of code.
>   #assuming ls=[1,2,3,4]
>   >>>ls[1:1]=[5,6]
>  #then ls becomes
>  >>> ls
> [1, 5, 6, 2, 3, 4]
> 
>  i would be happy to know how it works.
> 
>  Basically, ls[1:1] returns an empty list and assigning [5,6] to it,
> actually inserts the elements... but how?
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to generate random numbers in Python

2005-06-04 Thread Pujo Aji
Don't forget to call : import random

try:
import random
print random.randint(2,8)
print random.random()

good luck

pujo

On 6/4/05, Xiaoxia Xu <[EMAIL PROTECTED]> wrote:
> Hello,
> 
> I tried to use a Python library module random() to generate some
> noise to my data. But the interpreter gave me an error
> message saying NameError: name 'random' is not defined.
> I thought this error is because I don't have the pertinent
> library included. Could anyone tell me how can I get this
> to work?
> 
> Many thanks,
> 
> Ellen
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] resizing an array of strings?

2005-06-06 Thread Pujo Aji
Try this code:

def myfuncSplit(row,col,myList):
  RBig = []
  cou=-1
  for i in range(row):
RSmall= []
for j in range(col):
  cou+=1
  RSmall.append(myList[cou])
RBig.append(RSmall[:])
  
  return RBig
  

if __name__== '__main__':
  myString = ['hi','my','name','is','Jeff']
  result = myfuncSplit(2,2,myString)
  print result


On 6/6/05, Jeff Peery <[EMAIL PROTECTED]> wrote:
> Hello, I'm having a bit of trouble resizing/reshaping an array of strings.
> here's what I'm trying to do: 
>   
> myString = ['hi','my','name','is','Jeff'] 
> reshape(myString, (2,2)) 
>   
> What I get from this is something like: 
>   
> [['h','i'], 
> ['m','y']] 
>   
> What I want is: 
> [['hi','my'], 
> ['name','is']] 
>   
> How might this work best? 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running range scripts in IDE

2005-06-10 Thread Pujo Aji
On 6/10/05, typetext <[EMAIL PROTECTED]> wrote:
> I am using I. Langingham's Teach yourself Python in 24 hours, and up
> to chapter 4 I had no problem. I have installed the IDE , and as far
> as I know, all the other programs associated with Python, and had been
> batting along with no problem, using simple scripts such as "hello
> world" in notepad or notetab (another text processor) until I hit the
> range function. 

What IDE do you use ?

Then I tried to save and run a script with the
> following content.
> 
> range(10)
> 
> which returns the expected output when I type the command directly on
> the prompt line of IDE, but just returns either nothing or the words
> range(10) 

Can you show us what your input and output.


Don't forget to type print to show something in the console.

print range(10) # will give [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


good luck
pujo


when I use the run command and try to do it as script, saved
> as r10.py or a number of other names ending with the extention .py. I
> realize this might be an elementary question, but I am stuck. What am
> I doing wrong? I am using Windows XP.
> 
> Michael Riggs
> Seattle
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] is this a bug global i ???

2005-06-14 Thread Pujo Aji
I have code like this:

class A:
  def __init__(self,j):
self.j = j
  
  def something(self):
print self.j
print i# PROBLEM is here there is no var i in class A
but it works ???

if __name__ == '__main__':
  i = 10
  a = A(5)
  a.something()

I don't define global i but it will takes var i from outside of class A.

Can somebody explain this ???

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


[Tutor] can't see emacs timer in action

2005-06-14 Thread Pujo Aji
Hello,

I tried this code in emacs.
for i in range(3):
  time.sleep(1)
  print i

It shows the result but total result not second per second.

Any one experiance this problem

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


Re: [Tutor] can't see emacs timer in action

2005-06-15 Thread Pujo Aji
Hallo Danny,

If we always start interpreter everytime we want to run python in
emacs/xemacs, is it counter productive? I usually have to clean the
buffer/output pane  before running my program, so I always do this to
start my program:
C-c ! to start the interpreter
C-c o to change my windows
C-c C-c to run the program
C-x k ENTER to close it
C-c o to change my editor again
C-c ! to start the interpreter again

This is one cycle of running.

Is that normal ???

What is the difference between running C-c C-c directly and running it
after the interpreter?

I need to make shortcut for starting interpreter do you have any idea.

For this moment I use SciTE and I want to learn using xemacs.

Thanks in advance,

pujo

On 6/15/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> 
> 
> On Wed, 15 Jun 2005, Pujo Aji wrote:
> 
> > Thanks Danny,
> >
> > Btw, I use xemacs now does it has folding class and method capabilities?
> 
> Hi Pujo,
> 
> [Note: in replies, please make sure to put tutor@python.org in CC.]
> 
> 
> According to:
> 
>  
> http://groups.google.ca/group/comp.lang.python/msg/956f1c2d37f93995?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=2
> 
> Yes.  *grin*
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can't see emacs timer in action

2005-06-15 Thread Pujo Aji
thanks Noel,
It is great idea.

pujo

On 6/15/05, Max Noel <[EMAIL PROTECTED]> wrote:
> 
> On Jun 14, 2005, at 23:17, Pujo Aji wrote:
> 
> > I just use Ctrl+C Ctrl+C to run the code.
> > The code wait for 3 second and show all i all together.
> >
> > I can't feel every second pass.
> >
> > pujo
> 
>  Try running your script from a terminal (outside of emacs, that
> is).
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge
> a perfect, immortal machine?"
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can't see emacs timer in action

2005-06-17 Thread Pujo Aji
Hello Max,

the problem with running in a dos console terminal is that I have to
switch back and forth from terminal and my xemacs. and I found that in
windows dos console we have to specify buffer page. I do need a
dynamic buffer control so I don't need to specify the buffer if my
program run big things.
Do you have an advice?

pujo

On 6/15/05, Max Noel <[EMAIL PROTECTED]> wrote:
> 
> On Jun 14, 2005, at 23:17, Pujo Aji wrote:
> 
> > I just use Ctrl+C Ctrl+C to run the code.
> > The code wait for 3 second and show all i all together.
> >
> > I can't feel every second pass.
> >
> > pujo
> 
>  Try running your script from a terminal (outside of emacs, that
> is).
> 
> -- Max
> maxnoel_fr at yahoo dot fr -- ICQ #85274019
> "Look at you hacker... A pathetic creature of meat and bone, panting
> and sweating as you run through my corridors... How can you challenge
> a perfect, immortal machine?"
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can't see emacs timer in action

2005-06-17 Thread Pujo Aji
Hallo Danny,

I tried the emacs folding customization, but it doesn't work.
After I did it, my xemacs show tripple dot '...' near the method of
class it should be folded.
I don't know how to open my method.

Sincerely Yours,
pujo 
On 6/15/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> 
> 
> On Wed, 15 Jun 2005, Pujo Aji wrote:
> 
> > Thanks Danny,
> >
> > Btw, I use xemacs now does it has folding class and method capabilities?
> 
> Hi Pujo,
> 
> [Note: in replies, please make sure to put tutor@python.org in CC.]
> 
> 
> According to:
> 
>  
> http://groups.google.ca/group/comp.lang.python/msg/956f1c2d37f93995?q=emacs+folding+python&hl=en&lr=&ie=UTF-8&oe=UTF-8&rnum=2
> 
> Yes.  *grin*
> 
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can't see emacs timer in action

2005-06-17 Thread Pujo Aji
Hello Alan,

thanks for the advice,

but I don't understand why xemacs doesn't fix C-c C-c so we don't have
to do such many things. in fact C-c C-c is fail to represent the well
'run' behaviour of python ?
It would be nice to people who use python get the same benefit of
typing C-c C-c  and get the result it supposed to have in other
languages.
 
pujo

On 6/16/05, Alan G <[EMAIL PROTECTED]> wrote:
> > buffer/output pane  before running my program, so I always do
> > this to start my program:
> > ...
> > ...6 steps listed
> > ...
> 
> > This is one cycle of running.
> > Is that normal ???
> 
> I doubt it, I've never user python mode in emacs but I have
> used SQL and C++ modes and usually you just call C-c C-c from
> the code window and the rest all happens magically.
> 
> But even if you do have to do all of that the sionple solution
> is to record it as a macro
> 
> C-x (
> keys to press here
> C-x )
> 
> You can execute it again with
> 
> C-x e
> 
> And you can save it so that it will be available next time
> you start emacs. You can also bind it to a shortcut of your
> own - after all this is emacs you can do anything! :-)
> 
> > I need to make shortcut for starting interpreter do you have any
> idea.
> 
> record and save a macro
> 
> M-x apropos macro
> 
> is your friend...
> 
> Alan G.
> A one time emacs user...
> 
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] can't see emacs timer in action

2005-06-17 Thread Pujo Aji
Before I use xemacs I use emacs and both are the same.
I don't know if there is connection between cpython and problem in
showing real time console, because both use cpython.

I also want to hear people who use python and emacs/xemacs concerning
this problem.

pujo

On 6/17/05, Alan G <[EMAIL PROTECTED]> wrote:
> > but I don't understand why xemacs doesn't fix C-c C-c
> 
> Neither do I. BTW Do you know if this is specific to xemacs?
> Or does it also apply to python mode in vanilla GNU emacs too?
> 
> I really should get around to loading python-mode and
> trying it some day...
> 
> Alan G.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQL Connection Function

2005-06-21 Thread Pujo Aji
This a very simple connection using mysql.

1. connect to mysql:
db = mySQLdb.connect(user='root',passwd='something')

2. To execute and get the result:
c = db.cursor()
c.execute(sql comment)
result = c.fetchall()

you can wrap it in a class object.

pujo

On 6/21/05, Don Parris <[EMAIL PROTECTED]> wrote:
> As a newbie developer, the easiest way for me to connect to MySQL is to
> just copy & paste the connection commands into each funtion I write.
> However, I know that's far from ideal, and consumes more time than its
> worth.  I would like to create a MySQL connection function that I can just
> call up whenever I need it from within an other function.
> 
> ### The Connection Definition ###
> # def mysql_Conn():
> # Create a connection object and create a cursor.
> # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user",
>   passwd="password", db="chaddb_test")   # email text wrap here
> # Cursor = Con.cursor()
> 
> ### The function that Calls the Connection ###
> def mbr_Roster():
> mysql_Conn()
> 
> # Make SQL string and execute it.
> sql = "SELECT fst_name, lst_name FROM person\
> where env_num is not null\
> order by lst_name"
> Cursor.execute(sql)
> 
> # Fetch all results from the cursor into a sequence and close the
> # connection.
> Results = Cursor.fetchall()
> Con.close()
> 
> How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()?  Do I
> need to declare the cursor as a global variable?
> 
> >From the Traceback:
> global name 'Cursor' is not defined
> 
> 
> Don
> --
> evangelinuxGNU Evangelist
> http://matheteuo.org/   http://chaddb.sourceforge.net/
> "Free software is like God's love - you can share it with anyone anytime
> anywhere."
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Initialising attributes with random values

2005-07-05 Thread Pujo Aji
use : 

random.randint(1,5)

so complete code will be:

class something:
def __init__(self, name):
self.name = name
self.size = random.randint(1,5)
self.strength = random.randint(1,5)



pujo

On 7/5/05, Max Russell <[EMAIL PROTECTED]> wrote:
> Hello there;
> 
> If I have a class and want to initalise it, with
> random values assigned to the attributes, what is the
> best way of doing this?
> 
> For example:
> 
> def __init__(self, name, size = 0, strength = 0):
> self.name = name
> self.size = size
> self.strength = strength
> 
> starts with values of 0. But how can I neatly say,
> start with a random value from (for example) 1 - 5?
> 
> thanks
> Max
> 
> 
> 
> ___
> How much free photo storage do you get? Store your holiday
> snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup.

2005-07-12 Thread Pujo Aji
you can wrap your code with while statement that check a user input
received at the end of every calculation you made whether go back to
main menu or not.

pujo

On 7/12/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
>  
> It runs but now how do I make it go back to the previous menu (e.g. from Add
> to Calculate Menu?) 
>   
> Here is the latest screenshot: 
>   
> The Giant Calculator 
>   
> Copyright 2005 Written and debugged by Nathan Pinno 
>   
> OPTIONS MENU
> 1) Calculate
> 2) Shapes
> 3) Temperature
> 4) Formulas
> 5) Quit
> What option would you like:1
> CALCULATE MENU
> 1) Add
> 2) Subraction
> 3) Multiplication
> 4) Division w/o remainder
> 5) Division with remaider
> 6) Exponation
> 7) Square roots
> 8) Back to the previous menu.
> What option would you like:3
> First number:3
> Second number:2
> 3 * 2 =  6
> CALCULATE MENU
> 1) Add
> 2) Subraction
> 3) Multiplication
> 4) Division w/o remainder
> 5) Division with remaider
> 6) Exponation
> 7) Square roots
> 8) Back to the previous menu.
> What option would you like:7 
>   
> 
> >>> 
>   
> and the current code: 
>   
> # This program is designed as a big calculator with functions. 
>   
> # This first bunch of code is for the various menus. I decided to divide the
> calculations into seperate sub-menus,
> #so that the main menus would not be that long.
> def main_menu():
>global option
>print "OPTIONS MENU"
>print "1) Calculate"
>print "2) Shapes"
>print "3) Temperature"
>print "4) Formulas"
>print "5) Quit"
>option = input("What option would you like:" ) 
>   
> def cal_menu():
> global cal_opt
> print "CALCULATE MENU"
> print "1) Add"
> print "2) Subraction"
> print "3) Multiplication"
> print "4) Division w/o remainder"
> print "5) Division with remaider"
> print "6) Exponation"
> print "7) Square roots"
> print "8) Back to the previous menu."
> cal_opt = input("What option would you like:" ) 
>   
> def shape_menu():
> global shape_opt
> print "SHAPES MENU"
> print "Important: The figure that is used for pi is 3.14."
> print "1) Squares"
> print "2) Circles"
> print "3) Rectangles"
> print "4) Triangles"
> print "5) Cones"
> print "6) Cylinders"
> print "7) Semicircles"
> print "8) Main menu"
> shape_opt = input("What option would you like?" ) 
>   
> def temp_menu():
> global temp_opt
> print "1) Convert degrees Kevins to degrees Celsius"
> print "2) Contvert Fahrenheit to Celsius"
> print "3) Convert Celsius to Fahrenheit"
> print "4) Convert Celsius to Kelvins"
> print "5) Convert Kelvins to Fahrenheit"
> print "6) Convert Fahrenheit to Kelvins"
> print "7) Main Menu"
> temp_option = input("Choice: ") 
>   
> def formula_menu():
> global formula_opt
> print "1) Interest"
> print "2) Distance"
> print "3) Uniform motion"
> print "4) Momentum"
> print "5) Uniformly accelerated motion"
> print "6) Falling bodies"
> print "7) Weight"
> print "8) Main menu"
> fourmula_option = input("Choice: ") 
>   
> #Code for main part of program.
> print "The Giant Calculator"
> print
> print "Copyright 2005 Written and debugged by Nathan Pinno"
> print 
> main_menu()
> if option == 1:
> cal_menu()
> if cal_opt == 1:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "+", Y, "= ",X + Y
> cal_menu()
> elif cal_opt == 2:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "-", Y, "= ",X - Y
> cal_menu()
> elif cal_opt == 3:
> X = input("First number:" )
> Y = input("Second number:" )
> print X, "*", Y, "= ",X * Y
> cal_menu()
> elif cal_opt == 4:
> X = input("First number:" )
> Y = input("Second number:" )
> if Y == 0:
> print "Division by zero ot allowed!"
> Y = input("Second number:" )
> else:
> print X, "/", Y, "= ",X / Y
> cal_menu()
> elif cal_opt == 5:
> X = input("First number:" )
> Y = input("Second number:" )
> if Y == 0:
> print "Division by zero ot allowed!"
> Y = input("Second number:" )
> else:
> print X, "/", Y, "= ",X / Y," R ", X % Y
> cal_menu()
> elif cal_opt == 6:
> X = input("First number:" )
> Y = input("Power:" )
> print X, "**", Y, "= ",X**Y
> cal_menu()
> elif cal_opt == 7:
> X = input("Number to be squared:" )
> print "The square root of", X, " = ",X**0.5
> cal_menu()
> elif cal_opt == 8:
> main_menu()
> else:
> print "That's not an option. Try again."
> cal_menu
> elif option == 2:
> shape_menu()
> if shape_opt == 1:
> print "1) Circumference"
> print "2) Area"
> print "3) Shapes Menu"
>

Re: [Tutor] This should be easy

2005-07-18 Thread Pujo Aji
the code looks ok for me,

Can you post more specific, including the error ?

pujo

On 7/18/05, nephish <[EMAIL PROTECTED]> wrote:
> Hey there,
> 
> i have a script that i am trying to use to add a record to a MySQL
> database.
> 
> i keep getting a syntax error.
> 
> this works
> cursor.execute("INSERT INTO Table ( numberone ) VALUES ( 'one');")
> 
> but this does not
> cursor.execute("INSERT INTO Table ( numberone, numbertwo ) VALUES
> ( 'one','two');")
> 
> what is getting scrambled here?
> 
> the error i get is syntax error in MySQL query, check the documentation,
> blah blah blah
> 
> thanks
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting started

2005-07-20 Thread Pujo Aji
try python 2.4.1
from this web site:
http://www.python.org/download/

cheers,

pujo


On 7/20/05, Brett C. <[EMAIL PROTECTED]> wrote:
> Which Python version should I download, I have Windows XP and am just
> getting started in the programming area so alot of the descriptions are to
> confusing for me to understand, anyhelp would be appreciated
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] matplotlib (pylab) backends

2005-07-27 Thread Pujo Aji
Hello

I write a program which launch pylab from windows GUI (using wxpython).
I found some problem here.

If I use the default backends program  in matplotlibrc which is TkAgg
I have this result:
1. I click button the plot is showed
2. I close the plot
3. I click the button to show the plot the second time. it shows the
plot but I can't closed it (it hangs.

If I use the WX as my backends program ( i have to change manually in
matplotlibrc) I have this result:
1. I click button the plot is showed
2. I close the plot
3. I click the button to show the plot the second time. it shows perfect.
4. I close my GUI this time the program doesn't totally close (I can
check from windows manager process).

What's the problem here. I use pylab.show() to show the program.

Sincerely Yours,
pujo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Multiple Simultaneous Loops

2005-09-15 Thread Pujo Aji
assume:
you have two list with the same size
L1 = [1,2,3]
L2 = [11,22,33]
 
you can zip the L1 and L2 into L
L = zip(L1,L2)  # L = [(1,11),(2,22),(3,33)] 
 
then you can process:
for x in L:
  dosomething(x[0])...
  dosomething(x[1])...
 
I'm not so sure about your problem but
If you want to do something parallel processing then you should go to threading or pyro.
 
Cheers,
pujo
On 9/15/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
I roughly want to be able to do:for f, x in bunch_of_files, range(z):so that x iterates through my files, and y iterates through something else.
Is this something I can do?If so, what would be the best way to create a range of indeterminate length?If not, is there a nice way I can do it, rather than than incrementinga variable (x = x + 1) every loop?
Or maybe can I access the number of times the loop has run?  ('x = x +1' is so common there must be some more attractive shortcut).So far in learning Python I've founbd that when I feel you should be
able to do something, then you can.  This seems a pretty intuitivething to want to do, so I'm sure it must be possible, but I can't findanything on it.Many thanksEd___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simplifying with string-formatting operator

2005-09-23 Thread Pujo Aji
hello,
 
you can use this model:
    day, month, year = input("Please enter the day, month and year numbers: ")     date1 = '%s/%s/%s' % (month, day, year)
    months = {1:"January", 2:"February", 3:"March", 4:"April",  5: "May", 6: "June", 7: "July", 8: "August",  9: "September", 10: "October", 11: "November", 12: "December"} 
        date2 = '%s %s, %s' % (months[int(day)], day, year)    print 'the date is %s or %s' % (date1, date2)
 
cheers,pujo
 
On 9/23/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:
Hello Does anyone have any idea on how i could simplify the following program by using strings? 
# dateconvert2.py #    Converts day month and year numbers into two date formats import string def main():    # get the day month and year    day, month, year = input("Please enter the day, month and year numbers: ") 
   date1 = str(month)+"/"+str(day)+"/"+str(year)    months = ["January", "February", "March", "April",  "May", "June", "July", "August", 
 "September", "October", "November", "December"]    monthStr = months[month-1]    date2 = monthStr+" " + str(day) + ", " + str(year) 
   print "The date is", date1, "or", date2 main() ___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Binary 2 text & text 2 binary

2005-09-24 Thread Pujo Aji
If your symbol are specific it is better to use dictionary.
then if the user give an input you can take character by character and translate into your binary.
This is the code textTobinary:
    mydic = {'A' : "0101", 'B' : "0110", 'C' : "0111"}    strinput = 'ABBC'    result = [mydic[x] for x in strinput_process]    print result 
Cheers,
pujo 
On 9/24/05, Joseph Quigley <[EMAIL PROTECTED]> wrote:
Hi I'm playing with a Binary to text & text to binary converter. I can'tfigure out how to replace the characters (first stage: text to binary).
I thought lists would be the best but I really don't know how to usethem... here's my code:#! /usr/bin/env pythonA = "0101"B = "0110"C = "0111"D = "01000100"
E = "01000101"F = "01000110"G = "01000111"H = "01001000"I = "01001001"J = "01001010"K = "01001011"L = "01001100"
M = "01001101"N = "01001110"O = "0100"P = "0101"Q = "01010001"R = "01010010"S = "01010011"T = "01010100"
U = "01010101"V = "01010110"W = "01010111"X = "01011000"Y = "01011001"Z = "01011010"# SymbolsexclamationPoint = "0010 0001"
hash = "0010 0011"dollar = "001 0100"percent = "0010 0101"_and = "0010 0110"parentheses = "0010 1000"closeParentheses = "0010 1001"comma = "0010 1100"
dash = "0010 1101"period = "0010 1110"underline = "0101 "# Numberszero = "0011">two = "00110010"three = "00110011"
four = "00110100"five = "00110101"six = "00110110"seven = "00110111"eight = "00111000"nine = "00111001"ltra = "a"ltrb = "b"
ltrc = "c"while True:   text = raw_input("Enter text: ")   text = list(text)Thanks,   Joe___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with pi and the math module.

2005-09-24 Thread Pujo Aji
hi,
 
if you use : import math
you can type: diameter * math.pi
 
if you use from math import *
you can type: diameter * pi
 
Cheers,
pujo 
On 9/24/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:

Hi all,
 
I need help with pi and the math module. I had import math at the top of a program, but when it came to diameter*pi, it said that pi was not defined.
 
How do I use it correctly?
 
Thanks,
Nathan Pinno___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating strings

2005-09-25 Thread Pujo Aji
I will use simple function:
 
def getscore(val):    if 90 < val <=100:    return 'A'    elif val >= 80:    return 'B'    elif val >= 70:    return 'C'    elif val >= 60:    return 'D'
    else:    return 'F'    def main():    g = input('Enter score:')    print 'the score of the exam is %s' % (getscore(int(g)))Cheers,
pujo 
On 9/25/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:
Hello How would I get the following program to accept inputs of exam scores from 0-100 with A being 100-90, B being 89-80, C being 79-70, D being 69-60, and F being everything less than 60? 
import string def main():   scores = ["F", "D", "C", "B", "A"]   g = input("Enter a score number (0-100): ")   print "The score of your exam is", scores [g-0] + "." 
main()    ___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Flattening multi-dimentional list

2005-09-29 Thread Pujo Aji
Hi,
 
Use this:def _flatten(seq,myhasil):
  for isi in seq:
if type(isi) != str:
  try:
_flatten(isi,myhasil)
  except:
myhasil.append(isi)
else:
  myhasil.append(isi)
  
def flatten(seq):
  '''code to flatten tupple'''
  hasil = []
  _flatten(seq,hasil)
  return hasil
http://www.uselesspython.com/showcontent.php?author=38
Cheers,
pujo 
On 9/29/05, Bernard Lebel <[EMAIL PROTECTED]> wrote:
Hello,I have this list wich is made of tuples. I wish I could "flatten" thislist, that is, to extract each element in the tuples and build a new
flat list with it. Is there any shortcut to do that or do I have to gothrough some list comprehension-like procedure?(I have looked at sets but I have to keep things ordered).ThanksBernard
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] installing pydev

2005-10-02 Thread Pujo Aji
I think you should use simple project, and then add a file with extention py
 
Cheers,
pujo 
On 10/2/05, Mohammad Moghimi <[EMAIL PROTECTED]> wrote:
HiI have download pydev(org.python.pydev.feature-0_9_8_2.zip) from sourceforge.  Then I extract it to my eclipse directory. But When I try to create a new project, there isn't any python related project to select. I have installed python interpreter before. What is my problem and how can I fix it? should I donwload other files to install python plugin properly?
-- -- Mohammaddo you Python?!! ___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Help Needed

2005-10-05 Thread Pujo Aji
hi,
 
make sure in the 
option/general/Startup preferences/at startup/open edit windowoption/general/Startup preferences/autosave preferences/NoPrompt
 
run the program by clicking F5
 
Cheers,
pujo 
On 10/5/05, Steve Haley <[EMAIL PROTECTED]> wrote:


Hello,
 
I am trying to learn Python which I am brand new to.  I have run into a problem that I would appreciate help with.
 
When I am in Python Shell of the IDLE GUI, when I click Edit/Run Script, I am getting a dialog box that is titled "Not saved" and states "The buffer for Python shell is not saved.  Please save it first." With an "OK" button that just takes me back to the Shell window.  I am going through a book (which suggests this resource as a good place to ask questions) and Edit/Run Script was working just fine the other day.  

 
I don't have a clue what is wrong or how to fix it.  I have searched the 
Python.org website but was unable to find any reference to this.  Any help would be greatly appreciated.
 
Thanks very much,
Steve
[EMAIL PROTECTED]
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] handling of tabular data

2005-10-09 Thread Pujo Aji
Hi Frank,
 
you can use Numeric.py it is also powerfull to handle averages, min, max, matrix algebra, etc..
see: http://www.pfdubois.com/numpy/
 
You just need to use a list. 
 
If your data is big and you need more power I suggest you use database like mysqldb for python.
It is also fun to combine database and python all together.
 
Cheers,
pujo 
On 10/8/05, Frank Hoffsümmer <[EMAIL PROTECTED]> wrote:
HelloI often find myself writing python programs to compute averages, min,max, top10 etc of columns in a table of data
In these programs, I always capture each row of the table in a tuplethe table is then represented by a list of tuplescomputing averages, min, max and other meta-information is then donewith for loops or some list comprehension.
now I wonder, whether I shouldn't be using classes instead of liststo capture the table rowswith the little I know about classes, I assume that then I would havea list of class instances as representation of my tabular data
but given such a list of class instances, i would still need forloops to get to e.g. the minimal value of a certain attribute in allclasses in that list. OR?and what would be the benefit of using classes then?
what is the best practice, can anyone shed some light on thisthanks-frank___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how to speed up this code?

2005-10-12 Thread Pujo Aji
I have code like this: 
def f(x,y):     return math.sin(x*y) + 8 * x  
def main():     n = 2000     a = zeros((n,n), Float)     xcoor = arange(0,1,1/float(n))     ycoor = arange(0,1,1/float(n)) 
    for i in range(n):         for j in range(n):             a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x 
    print a[1000,1000]     pass 
if __name__ == '__main__':     main() 
I try to make this run faster even using psyco, but I found this still slow, I tried using java and found it around 13x faster... 
public class s1 { 
        /**          * @param args          */         public static int n = 2000;         public static double[][] a = new double[n][n];         public static double [] xcoor = new double[n]; 
        public static double [] ycoor = new double[n]; 
        public static void main(String[] args) {                 // TODO Auto-generated method stub                 for (int i=0; i                        xcoor[i] = i/(float)(n);                         ycoor[i] = i/(float)n; 
                } 
                for (int i=0; i                        for (int j=0; j                                a[i][j] = f(xcoor[i], ycoor[j]);                         }                 } 

                System.out.println(a[1000][1000]); 
        }         public static double f(double x, double y){                 return Math.sin(x*y) + 8*x;         } 

}  Can anybody help? 
pujo 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to speed up this code?

2005-10-13 Thread Pujo Aji
hello chun,
 
I use Numeric.
using 'while' instead of for, has the same effect. still slow
 
pujo 
On 10/13/05, w chun <[EMAIL PROTECTED]> wrote:
On 10/12/05, Pujo Aji <[EMAIL PROTECTED]> wrote:> I have code like this:
>> def f(x,y):> return math.sin(x*y) + 8 * x>> def main():> n = 2000> a = zeros((n,n), Float)> xcoor = arange(0,1,1/float(n))> ycoor = arange(0,1,1/float(n))
>> for i in range(n):> for j in range(n):> a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x>> print a[1000,1000]>> if __name__ == '__main__':
> main()>> I try to make this run faster even using psyco, but I found this still> slow, I tried using java and found it around 13x faster...>>  Can anybody help?>> pujo
are zeros() and arange() from NumPy or SciPy?  i'll assume so, sothey're pretty fast already.  on 1st glance, i would recommend using awhile loop instead of range(), which creates a data structure (list of
2000 elements) twice:   i = 0   while i < n:   j = 0   while j < n:   a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x   j += 1   i += 1
there are probably other improvements that can be made.  i also tookout your 'pass' stmt.  :-)HTH,--wesley- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"Core Python Programming", Prentice Hall, (c)2006,2001
   http://corepython.comwesley.j.chun :: wescpy-at-gmail.comcyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to speed up this code?

2005-10-13 Thread Pujo Aji
Hello Andrew,
 
Thanks for the info.
I wonder if everytime we have to solve loop inside loop which use big array will force us to think another algorithm like matrix model. Since this model is suitable with Numeric.py 
 
I think looping style sometimes easier to describe our problem. 
pujo 
On 10/13/05, Andrew P <[EMAIL PROTECTED]> wrote:
It's way past my bedtime, but any use of numpy/numarray that involves two nested for loops to step over each element is the wrong solution :)  You need to figure out how to get rid of that inner for.  That is what is slowing you down.  
Compare these two ways to multiply a 1000 element array by 100.  The first one steps over the elements one at a time, multiplying each one in turn.  The second multiplies the entire array at once.  Which boils down to looping over 2000 rows, instead of 4,000,000 elements :)
If I was more awake, I'd try to figure out how you can do that.  But this should give you an idea of what arrays are useful for, and how to approach the problem.>>> def time_loop(num):...     a = arange(1000)
...     b = zeros(1000)...     t = time.clock()...     for i in range(num):...         for i in range(len(a)):...             b[i] = a[i] * 100.0...     print time.clock() - t...     >>> time_loop(10)
59.7517100637>>> def time_numeric(num):...     a = arange(1000)...     b = zeros(1000)...     t = time.clock()...     for i in range(num):...         b = a*100...     print 
time.clock() - t...     >>> time_numeric(10)1.44588097091

On 10/13/05, Pujo Aji <
[EMAIL PROTECTED]> wrote:


I have code like this: 
def f(x,y):     return math.sin(x*y) + 8 * x  
def main():     n = 2000     a = zeros((n,n), Float)     xcoor = arange(0,1,1/float(n))     ycoor = arange(0,1,1/float(n)) 
    for i in range(n):         for j in range(n):             a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x 
    print a[1000,1000]     pass 
if __name__ == '__main__':     main() 
I try to make this run faster even using psyco, but I found this still slow, I tried using java and found it around 13x faster... 
public class s1 { 
        /**          * @param args          */         public static int n = 2000;         public static double[][] a = new double[n][n];         public static double [] xcoor = new double[n]; 
        public static double [] ycoor = new double[n]; 
        public static void main(String[] args) {                 // TODO Auto-generated method stub                 for (int i=0; i                        xcoor[i] = i/(float)(n);                         ycoor[i] = i/(float)n; 
                } 
                for (int i=0; i                        for (int j=0; j                                a[i][j] = f(xcoor[i], ycoor[j]);                         }                 } 

                System.out.println(a[1000][1000]); 
        }         public static double f(double x, double y){                 return Math.sin(x*y) + 8*x;         } 

}  Can anybody help? 
pujo 











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

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


Re: [Tutor] Focus on the functions [Was Re: if-else statements]

2005-10-16 Thread Pujo Aji
Dear Norman,
 
You can reuse function, this make your code more easy to handle.
Suppose you have  code  to calculate area of rectangle, but this time you like to calculate 3 times:
 
width = 3; length = 2
print 'area', width * length
 

width = 1; length =32
print 'area', width * length
 

width = 31; length = 22
print 'area', width * length
 
it is better if you have function func_area
 
def func_area(width,length):
    return func_area(width,length)
 
then your code becomes:

width = 3; length = 2
print 'area', func_area(width,length)
 

width = 1; length =32
print 'area', func_area(width,length)
 

width = 31; length = 22
print 'area', func_area(width ,length)
 
 
And something happened that a new area formulation of rectangle is = width * length * length (of course this is wrong, it is only an example that your formula or code sometime needs to be changed), so instead of writing all of this formulation one by one which prone to error, you can change only your defined function func_area. 

 
def func_area(width,length):
 return width * length * length
 
 
And you get the right result. The key here is that you can change your code easily.
 
The next day you create a code in another module for example new_module.py then you would like to use your func_area which in old_module.py, then you can just import and use it.
 
in your new_module.py you can type:
import old_module
 
print 'area of rectangle according old module is : ', old_module.func_area(11,22)
 
The key here is that you can reuse your function when you need it in other module.
 
Hope this help you understand a little bit the function of a function
 
Cheers,
pujo
 
 
 
 
Cheers,
pujo
 
 
 
 
 
 
On 10/16/05, Norman Silverstone <[EMAIL PROTECTED]> wrote:
> I apologize to the list again for the noisy contentless ranting I made> yesterday, so I'll try making it up by doing concrete demos of a
> function-focused approach.  This will critique Zelle's Chapter Two and> Chapter Five, and see what things would look like if under a function> regime.>< snip>I am an elderly person somewhat physically handicapped with some
experience  programming in basic and pascal, many years ago. In order tokeep myself mentally active I decided to have a look once again atprogramming and chose python as a good language to start with. So, I had
a look at 'Dive into Python', bought a couple of books, 'PythonProgramming for the Absolute Beginner' and 'Learn to program UsingPython'.All was well to start with until I came to the section on functions. I
am finding it very difficult to grasp the reasoning behind the use offunctions and how and when to use them. I keep trying to see if any ofthe snippets of programs that I have already come across aretransferable into functions without a great deal of success. The problem
appears to be that, and here I agree with the writer, functions areintroduced as something on their own, well after manipulating strings,lists, dictionaries, tuples, loops etc are dealt with.Having studied the examples given here, I am beginning to get some
understanding of what is going on. If only I could find many moreexamples like these, in simple English, I would be a very happy student.> Anyway, hope this helps!It certainly helps me.Norman
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] what does %25f mean?

2005-10-24 Thread Pujo Aji
it will reserve the 25 space for your number.
example:
    print '%25.2f' % (1.222,)
 
It will use 25 space and 2 digit of your 1.222result is: 
 1.22
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
what does %25f mean?___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary

2005-10-24 Thread Pujo Aji
you work with dictionary.
In dictionary you work with the key to get your value. You don't care about how python arrange the key.
your key here are: 'res', 'com', 'ind', and  'other'
when you want to get your value you just type:
landUse['res'] this you will get 1
landUse['ind'] this you will get 3
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
I typed:landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}and when i checked landUse, I found it become:
{'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}why the order is changed?___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] string

2005-10-24 Thread Pujo Aji
please show us the code
 
cheers,
pujo 
On 10/24/05, Shi Mu <[EMAIL PROTECTED]> wrote:
what does the following sentence mean? does it mean i can not usedouble-quoted string?SyntaxError: EOL while scanning single-quoted string
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Pujo Aji
Hello,
 
I'm not so sure about your problem, but 
probably this code can help
 
    sumHead, sumTail = 0,0
    listHeadTime = []    listTailTime = []        for i in range(100):    time_start = time.clock()    coin = random.randint(0,1) # 0 head, 1 tail    time_stop = time.clock()    time_duration = time_stop - time_start
        if coin == 0:    sumHead += 1    listHeadTime.append(time_duration)    else:    sumTail += 1    listTailTime.append(time_duration)
    print sumHead, sumTail    print listHeadTime    print listTailTime
 
Cheers,
pujo 
On 10/26/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> >  My goal, create a program that flips a coin 100 times, at the end it> > says the number of times it flipped heads and flipped tails.
>> Do you might if we simplify the problem slightly?  Say that you're only> flipping the coin two times.  Can you write code to say how many times> it flips heads and tails?  Once you get that working, then modify that
> program to do it for three coins, then four.Duh: I forgot to add: can you try to do the above without loops?  Sincethere's so little coin flipping going on, the code to do this shouldn't betoo long to write, even without loops.
(... although it will get longer for each additional coin we flip.  Whenwe want to scale our solution to more coins, then that's where loops cancome into play.)___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while/if/elif/else loops

2005-10-31 Thread Pujo Aji
Let's comment something:1. If you have error please show us your error message.2. When you code python be aware of indention, be persistent for example use tab space 4.3. import should be on the top of your code.
4. to choose random between integer 1 or 0 use randint(0,1)5. your last code use Print it should be print (small letter please).Cheers,pujoOn 10/31/05, 
Zameer Manji <[EMAIL PROTECTED]> wrote:
-BEGIN PGP SIGNED MESSAGE-Hash: SHA512I'm new to programming and python. I've have recently been experimentingwith while/if/elif/else loops and I've created a simple number guessinggame. Now I want to create a coin tossing game, but I don't know how to
structure it in python. The code I already have (but it's not working)is below.#Coin Toss Gameprint "This game will simulate 100 coin tosses and then tell you thenumber of head's and tails"
import randomtosses = 0heads = 0tails = 0while tosses = 100<0:   coin = randrange(1)   tosses +=1   if coin == 0:  heads +=1  print "Heads"else:
  tails +=1  Print "Tails"-BEGIN PGP SIGNATURE-Version: GnuPG v1.4.2 (MingW32)iQEVAwUBQ2accw759sZQuQ1BAQqoyQgAsmVhRidMC1/WpQms6fChX+z62DWSpmRWqiY9F7bZAYZusyNsHHDUpuTAYdI0LXxgLVmYBKDz3tKhVCbEZTn9FUwgw5A2thYy
I5o82tWXZnIpgmFIN2AysAj2dCI4mSfi/IJjE5JvG+IFELWigMb9Pf6tap4HiB71IBayql8MN1XrA2zv8fXQs35zVwxnBUSvAHZuUBLi4hDcPxY/d71X/JHqfqpf3svSClzUlYqLhXld+39/aiRFKOXHyVCnfsEUcAXB45r110Q3K+7KegwgX4Js8qL5dA66d74HlLMb6Cp6G5AlNdQoKDin8jlMloxeQpb60hS+HmnBwkEFukyNHA==
=QMuB-END PGP SIGNATURE-___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while/if/elif/else loops

2005-11-02 Thread Pujo Aji
Hello,I see two things can be changed a little bit.1. redundant: while, if2. print style at the last statement.see below:#Coin Toss Game#Zameer Manjiimport randomprint "This game will simulate 100 coin tosses and then tell you the
number of head's and tails"tosses = 0heads = 0tails = 0while tosses<100:    coin = random.randrange(2)    tosses +=1    if coin == 0:    heads +=1    print "Heads"
    else:    tails +=1    print "Tails"print "100 tosses have been simulated. Please wait for your results"print "Out of %s, %s were heads and %s were tails" % (tosses, heads, tails)
cheers,pujoOn 11/1/05, Zameer Manji <[EMAIL PROTECTED]> wrote:
Ok after looking at everyones replies my program looks like this:#Coin Toss Game#Zameer Manjiimport randomprint "This game will simulate 100 coin tosses and then tell you thenumber of head's and tails"
tosses = 0heads = 0tails = 0while tosses<100:if tosses<100:coin = random.randrange(2)tosses +=1if coin == 0:heads +=1print "Heads"
else:tails +=1print "Tails"else:print "100 tosses have been simulated. Please wait for your results"print "Out of", tosses, ",", heads, "were heads and", tails, "were tails."
This is the results:>>>  RESTART>>>This game will simulate 100 coin tosses and then tell you the number of
head's and tailsHeads...  (To save space the results have been stripped)HeadsOut of 100 , 48 were heads and 52 were tails.Thank you for your help everyone.___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] avoid eval how???

2005-11-03 Thread Pujo Aji
Hello
 
I have a dynamic functions which created by some algorithms during runtime.
These functions are in string type.
When I want to use it, I can use eval command.
But can someone give me more suggestion about how to handle this problem, I want to avoid eval.
 
Example :
L = ['x+sin(x)', '1/(2.2 + pow(2,3)/sin(30)']
 
 
Sincerely Yours,
pujo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RSH?

2005-11-03 Thread Pujo Aji
try pyro.
 
Cheers,
pujo 
On 11/3/05, Mike Hansen <[EMAIL PROTECTED]> wrote:
Anyone know of a way to have Python run a command on a remote machine? In myparticular case, I want to run a python program on Windows and run a command on
VMS. Would the telnetlib module do it, or is there something better?Mike___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sorting a dictionary

2005-11-04 Thread Pujo Aji
Hallo,
 
you can also sort based on the values:
  
>>> list_of_nums = nums.items()>>> list_of_nums.sort(lambda x,y: cmp(x[1],y[1]))
Cheers,
pujo
 
 
 
On 11/4/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Fri, 4 Nov 2005, Johan Geldenhuys wrote:> In my new project I needed a dictionary with TCP/UDP port numbers as
> keys and the service for that key as the value. I got the info from the> services file in Linux and compiled a dictionary as I needed.>> The only thing that I want to do is to sort the dictionary from the
> smallest key number to the largest key number.Hi Johan,Is this so you can more easily read the dictionary better?  Be aware thatdictionaries in Python are implemented as "hashtables", and these
hashtables are deliberately "misordered" to make them work fast.We can take the items() of a dictionary, and sort those.  For example:##>>> nums = {'one' : 1, 'two' : 2, 'three' : 3 }
>>> nums{'three': 3, 'two': 2, 'one': 1}>>> nums.items()[('three', 3), ('two', 2), ('one', 1)]##We see that items() is a list of key-value pairs.  We can sort lists by
using their sort method().##>>> list_of_nums = nums.items()>>> list_of_nums.sort()>>> list_of_nums[('one', 1), ('three', 3), ('two', 2)]##Is this what you're looking for?  If you have more questions, please feel
free to ask.___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Percentage

2005-11-07 Thread Pujo Aji
don't forget to use dot or converge into float.perc = 42./250or perc = float(42)/250otherwise:it is treated as integer.pujoOn 07 Nov 2005 11:50:05 -0200, 
Jorge Godoy <[EMAIL PROTECTED]> wrote:
Johan Geldenhuys <[EMAIL PROTECTED]> writes:> What is the syntax if I want to work out what percentage 42 is out of 250?If you want it as a factor to multiply / divide by something:
perc = 42/250If you want it to "read" as percentage:perc_100 = (42/250)*100Sds,--Jorge Godoy  <[EMAIL PROTECTED]>___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Percentage

2005-11-07 Thread Pujo Aji
nice syntax.
 
Cheers,
pujo 
On 07 Nov 2005 12:18:44 -0200, Jorge Godoy <[EMAIL PROTECTED]> wrote:
Pujo Aji <[EMAIL PROTECTED]> writes:> don't forget to use dot or converge into float.
Or import division from __future__.>>> from __future__ import division>>> 42 / 2500.16801>>>--Jorge Godoy  <
[EMAIL PROTECTED]>___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] lists and strings

2005-11-08 Thread Pujo Aji
yes it is...
 
convert list to string:
    L = [1,2,3]    L = [str(x) for x in L]    s = string.join(L,' ')    print len(s) 
convert list to a file
    myF = open(namaFile,"w")    for s in myList[:-1]:    myF.write(str(s)+"\n")    myF.write(str(myList[len(myList)-1]))    myF.close() 
 
Cheers,
pujo 
On 11/8/05, Mike Haft <[EMAIL PROTECTED]> wrote:
 
Hello,I've been working on a problem and have now sorted most of it (thanksto some help from the list). 
All the ways of writing data to a file I know keep telling me that listscan't be written to the file. I'm trying to convert data from one set offiles into files of a different format. But the easiest way to get the 
data from the first set of files is in a list(s).So, is there any way to convert lists to strings? Or a way to write liststo a file?ThanksMike___ 
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to launch executable from a Python script??

2005-11-08 Thread Pujo Aji
Try to add .py in PATHEXT environment windows XP
After that, you can call your python program just like you call exe file.
 
Hope this help.
pujo  
On 11/8/05, Chris Irish <[EMAIL PROTECTED]> wrote:
Hello all :)I made a GUI app with pyGTK that I want to be able to launch a game I'vedownloaded from the pygame website when a button is clicked.  I was able
to do this on a linux box since the file was a .py file, but I'm notsure how to do it on a windows box since the file is an executeable.  Onlinux I did this:import osolddir = os.getcwd()   #to keep a reference to the old
directory to switch games lateros.chdir('spacinVaders-0.1')   #switch to the game's directoryos.spawnlp(os.P_NOWAIT, 'pythonw', 'pythonw', 'play.py')and it would launch fine can someone help me with this??
Thanks in advance. Chris :P___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another Quick Question

2005-11-13 Thread Pujo Aji
I use windows, it works for meHave checked your sound card, volume before trying the code?pujoOn 11/14/05, Johan Geldenhuys <
[EMAIL PROTECTED]> wrote:


  
  


Could this be a OS thing?
I use Linux and it works here.

Steve Haley wrote:

  
  
  
  
  Folks,
   
  I'm one of the people new
to Python who has started
going through a beginner's book to learn the basics of the language
("Python
Programming for the Absolute Beginner").  In the second chapter the
author (Michael Dawson) illustrates the use of escape sequences with,
among
other things, the "\a" to sound the system bell.  However, when I
run the little program myself, the program runs but I get no sound –
all is
get is the word BEL in while letters on a blue background.  I've turned
the volume up all the way and still no sound.  I know the speakers on
my laptop
work because I just finished my daily session trying to learn a little
Spanish
which involves sound.
   
  I went to the language
reference which also seems to
indicate I should get a sound with exactly what the author is saying. 
The
exact line is:
   
  print "\a"
   
  I'm not sure why but this
kind of thing bothers me. 
Can anyone suggest why my laptop won't produce a bell?  Does the fact
that I'm running version 2.1 have something to do with it?  Does my
laptop have something against me and just doesn't want to ring its bell
for me? (just kidding with that last one)
   
  Thanks in advance.
  Steve
   
  
  
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
  




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


Re: [Tutor] Inheriting from parent object

2005-11-14 Thread Pujo Aji
if you want to copy object just use:
import copy
newobj = copy.deepcopy(objparent) 
or just create object which has direct correlation with the parent like:
newobj = objparent 
Cheers,
pujo
 
On 11/14/05, Alan Gauld <[EMAIL PROTECTED]> wrote:
> I want to create a property that will inherit it's value from the same> property in it's parent object, but will check it's parent's propety
> everytime it is called.  But that can be over-ridden, and I don't have> to know what the objects parent is.Ed you are using a lot of OOP terminology here to decribesomething that looks decidedly non OOP. Can you clarify exactly
what you mean by the terms:   object, property, inherit and parent.Also can you describe the problem you are trying to solve rather thanthe solution you think you need? It may be that there is a simpler
paradigm you can use. I'm not sure I really understand what youare trying to achieve.> object.x = 3> object.subobject.x = inherit()> print object.subobject.x #prints 3> object.x = 4
> print object.subobject.x #prints 4> object.subobject.x = 5> print object.subobject.x #prints 5object it the built-in object class that provides new-style classes,is that theone you are using here? Or is it just a generic name for
illustration? Is object an instance or a class?> What could I put in the inherit() function that would look for the> same property of it's parent and return that, whilst keeping it as> general as possible?
I also don't understand what the inherit() function is supposed to do.You provide it with no context in which to operate.Unless it relies on hard coded global variables there is noway it can know about object, subobject or x.
Normal OOP inheritance relies on creating instances from classes,but you don't appear to want to do that, it looks more like youare building some kind of containment lattice. I think I need morebackground.
Alan GAuthor of the learn to program web tutorhttp://www.freenetpages.co.uk/hp/alan.gauld___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to identify a list element is in the range of a tuple element or a list element

2005-11-17 Thread Pujo Aji
for b you can use this code:
    a = [10,3,4.6,2.3,4.8,10.8,4.1]    b = ['1-4','4.1-8','8.1-12','12.1-16']    for x in a:    for y in b:    low,up = y.split('-')    if  float(low) < x < float(up):
    print '%s   %s - %s' % (x, low, up)    break    Cheers,
pujo 
On 11/17/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Srinivas Iyyer wrote:> Dear group,>> I have a list of numbers:>> a = [10,3,
4.6,2.3,4.8,10.8,4.1]> b = ['1-4','4.1-8','8.1-12','12.1-16']> c = ((1,4),(4.1,8),(8.1-12),(12.1,16))>> Now I want to find if elements of list a are in the> range of list b and in the range of tuple b.
>> I know (and my limited knowledge on range function) is> not allowing me to think of a new way.>> Could any one please help me.>> I wish to have the answer as:>
> 10   8.1-12> 31-4> etc.>A brute-force approach is straighforward. I ignore b since it has the same values as c, and I corrected the third entry in c to be a tuple.>>> a = [10,3,
4.6,2.3,4.8,10.8,4.1]>>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16))>>> for x in a:...   for lower, upper in c:... if lower <= x <= upper:...   print '%-5s%s-%s' % (x, lower, upper)
...10   8.1-1231-44.6  4.1-82.3  1-44.8  4.1-810.8 8.1-124.1  4.1-8If a and c are large this could be slow, it could be optimized by searching in c instead of exhaustive search, or by terminating the inner loop when a match is found or when lower > x.
Kent--http://www.kentsjohnson.com___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lists with just an item

2005-11-21 Thread Pujo Aji
Hi,
 
    mydic = {'one': 1, 'two': 2}        # to access key:    for x in mydic.keys():    print x        # to access value --> use key    print mydic['one']
 
Cheers,
pujo
On 11/21/05, Negroup - <[EMAIL PROTECTED]> wrote:
Hi all.In my application I have chosen as data structure a list ofdictionaries. Each dictionary has just one key and the corresponding
value.structure = [{'field1': lenght1}, {'field2': lenght2}, ]Initially, to obtain the key and the value I used this code,for structure in record_structure:field_name = structure.keys
()[0]displacement = structure[field_name]but after some thoughts I arrived to:field_name, displacement = structure.items()[0]which to me seems a lot better.At this point I don't like much that [0] to access a list that I know
always contains a single element. Can I improve the code withsomething better?Thanks!___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Numeric array incosistence in unittest

2005-11-21 Thread Pujo Aji
hello, 
I found that if I use Numeric.array into unittest it is not consistance, Is that normal ? 
 
import unittestimport Numeric
class myTest(unittest.TestCase):    def runTest(self):    var1 = Numeric.array([1,22])    var2 = Numeric.array([1,33])    self.assertEqual(var1,var2)

if __name__ == '__main__':        unittest.main()
 
This will not raise any error ??? 
Any idea? 
Sincerely Yours, pujo 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] running a program

2005-11-28 Thread Pujo Aji
this should be the same as running other python code.assuming you use windows,  you can type from dos command :python namefile.pyCheers,pujoOn 11/28/05, 
David Jimenez <[EMAIL PROTECTED]> wrote:
Hello everybody,I have a very simple question: how can I run a script that uses module Tkinter without using IDLE? Thank you,David  
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.

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


Re: [Tutor] rare matrix

2005-11-30 Thread Pujo Aji
try numeric or numpy in :http://www.numpy.org/Cheers,pujoOn 11/30/05, János Juhász <
[EMAIL PROTECTED]> wrote:Dear All,do you know any python solution to handle big big rare matrices effectively
with python.I would make matrix multiplications with 3000x3000 matrices, but with 1-2%data in them.Could you recommend any starting point for that ?Yours sincerely,__
János Juhász___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


[Tutor] python swig problem

2005-12-01 Thread Pujo Aji
Hi,  I tried to follow the example in swig homepage.  I found error which I don't understand. 
 I use bcc32, I already include directory where my python.h exist in  bcc32.cfg.   /* File : example.c */  
 #include    double My_variable = 3.0;   int fact(int n) {       if (n <= 1) return 1;       else return n*fact(n-1); 
  }   int my_mod(int x, int y) {       return (x%y);   }   char *get_time() 
  {       time_t ltime;       time(

[Tutor] distutils python 2.4.2 winxp, microsoft visual studio 2005 problem

2005-12-05 Thread Pujo Aji
Hello,I try to call setup build and found this problem:running buildrunning build_ext*** Failed: error: The .NET Framework SDK needs to be installed before building extensions for Python.I have .NET Framework SDK already.
Is there anyone experiance this problem ?I also found some information about this : http://www.vrplumber.com/programming/mstoolkit
But I think this is only for .NetFramework 1.1 and visual studio 7I have Visual studio express 2005 which use .NetFramework 2.0Can anybody helps?Thankspujo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Timer

2005-12-06 Thread Pujo Aji
Probably the simplest thing is to make the computer sleep in a specific time.Example:def main():    time.sleep(2) # sleeping 2 second    print 'finish'Cheers,pujo
On 12/6/05, Joseph Quigley <[EMAIL PROTECTED]> wrote:
I'd like to make a 30 minute timer. How an I do that? With time?
Thanks,
   Joe-- There are 10 different types of people in the world.Those who understand binary and those who don't.

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


Re: [Tutor] information needed to make a connection between computers

2005-12-12 Thread Pujo Aji
yes you can do that in python.But I recommend to use pyro.http://pyro.sourceforge.net/pujoOn 12/11/05, 
John Walton <[EMAIL PROTECTED]> wrote:
 Hello again! I'm still working on that  instant messenger (for science fair), and I have been reading about  networking in some Java tutorials. In one part of it, it said to have a  connection with another computer, you need to know the IP name of the  computer you want to connect with. I don't know whether or not this is  the same for Python, but could someone please tell me what information  of the computer you want to connect with the you actually need for a  connection? In other words (or plain english), what information do I  need to get a connection with another computer (IP address, name, IP  name)? Also, could you tell me how to find it on a computer? Since I'll  be testing the instant messenger on the three computers in my house, I  just need to know how to find the information on the computer I'd  currently be on (not from any remote location). Thanks!  :)
  -John  
	
		Yahoo! Shopping 
Find Great Deals on Holiday Gifts at 
Yahoo! Shopping 
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Guess my number game

2005-12-15 Thread Pujo Aji
Hi, your guess still use random.randrange that's make computer doesn't care about whether guess is low or higher than your number.This code should be like this:    print "\t\t\tWelcome to \"Guess My Number\"!"
    print "\nThink of a number between 1 and 50."    print "I will try to guess it in as few attempts as possible.\n"    number = input ("Enter the number: ")        #the computer guesses the number using the random function
    guess = random.randrange (50) + 1    tries = 1        #FIXME    while (guess != number):    if (guess > number):    print "You chose", guess, "the number is Lower ..."
    guess = random.randint(1, guess-1)    else:    print "You chose", guess, "the number is Higher ..."    guess = random.randint(guess+1, 50)
    tries += 1        print "You guessed it! The number was", number    print "And it only took you", tries, "tries!\n"    raw_input ("Press  to exit.")
Hope this helppujoOn 12/15/05, William Mhlanga <[EMAIL PROTECTED]> wrote:
I have been trying to write a guess my number game (using Michael Dawsons book), where the computer guesses the number that I thought of. Here is my code so far,#The Guess My Number Game

##The computer picks a random number between 1 and 50#The player tries to guess it and the computer lets#the player know if the guess is too high, too low#or right on the money#If the player fails to guess the number after 5 tries
#the game ends and the computer prints a chastising message#print "\t\t\tWelcome to \"Guess My Number\"!"import randomprint "\nThink of a number between 1 and 50."
print "I will try to guess it in as few attempts as possible.\n"number = input ("Enter the number: ")#the computer guesses the number using the random functionguess = random.randrange

 (50) + 1tries = 1#FIXMEwhile (guess != number):    if (guess > number):    print "You chose", guess, "the number is Lower ..."    else:    print "You chose", guess, "the number is Higher ..."
    guess = random.randrange (50) + 1    tries += 1print "You guessed it! The number was", numberprint "And it only took you", tries, "tries!\n"raw_input ("Press  to exit.")
The program works ok, but the computer sometimes repeats the same numbers when asked to guess. How can I rewrite it so that it guesses like what a human being does i.e. if the number is less than 20, you do not guess numbers above 20.
Thanks for your help.

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


Re: [Tutor] float question

2005-12-20 Thread Pujo Aji
Th format %x1.x2fwhere x1 is the total space and x2  is decimal digit place.If your data is longer than the specified x1 and x2.the data rules.Look at 3.14 takes 4 places total# 4 places rules
>>> '%3.2f' % 3.14'3.14'# perfect>>> '%4.2f' % 3.14'3.14'# try this >>> '%5.2f' % 3.14' 3.14'Cheers,pujo
On 12/20/05, linda.s <[EMAIL PROTECTED]> wrote:
On 12/20/05, Danny Yoo <[EMAIL PROTECTED]> wrote:>>> On Mon, 19 Dec 2005, linda.s wrote:>> > what does 2 mean in %2.4f ?
>> Hello,>> It's a "minimal field width" modifier, according to:>>http://docs.python.org/lib/typesseq-strings.html
>>> Let's try experimenting with it.>> ##> >>> '%20f' % 3.14> '3.14'> >>> '%20.2f' % 3.14> '3.14'
> ##>>> Does this make sense?  If you have more questions, please feel free to> ask.Danny,Thanks. Still confused. I changed the code a little.>>> '%3.2f' % 3.14
'3.14'>>> '%4.2f' % 3.14'3.14'there is no difference in the above two codes. so what does 3 and 4 mean?___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Differnce between java and python

2005-12-21 Thread Pujo Aji
Hi,you can check this website:http://www.ferg.org/projects/python_java_side-by-side.htmlabove all.python is very compact, clear language.
I did some code using C# for 1 year, and when I move to python I can rewrite it even more in about 3 months.My code becomes clearer than ever beforeCheers,pujo
On 12/21/05, shivayogi kumbar <[EMAIL PROTECTED]> wrote:
sir plz tell me the main differnces between java and python?And What are the advantages of python?

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


Re: [Tutor] Numeric import error

2005-12-22 Thread Pujo Aji
Can you open the python interpreter and write:import NumericWhat kind of error message you have?Cheers,pujoOn 12/22/05, Johan Geldenhuys
 <[EMAIL PROTECTED]> wrote:Hi all,
I have installed Numeric (Suse 10.0) and it is in my site-packagesfolder, but I can't import the module.Any idea how to fix this/TIAJohan___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numeric import error

2005-12-22 Thread Pujo Aji
Do you have other modules in your site-packages directory ?Such as spe, pyro, pyrobot etc.On 12/22/05, Johan Geldenhuys <
[EMAIL PROTECTED]> wrote:


  
  


>>> import Numeric
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named Numeric

Pujo Aji wrote:
Can you open the python interpreter and write:
import Numeric
  
What kind of error message you have?
Cheers,
pujo
  
  On 12/22/05, Johan Geldenhuys
   <[EMAIL PROTECTED]>
wrote:
  Hi
all,


I have installed Numeric (Suse 10.0) and it is in my site-packages
folder, but I can't import the module.

Any idea how to fix this/

TIA

Johan
___

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




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


Re: [Tutor] Numeric import error

2005-12-22 Thread Pujo Aji
Can you find numeric.py inside your numeric folder ?On 12/22/05, Pujo Aji <[EMAIL PROTECTED]> wrote:
Do you have other modules in your site-packages directory ?Such as spe, pyro, pyrobot etc.
On 12/22/05, Johan Geldenhuys <

[EMAIL PROTECTED]> wrote:


  
  


>>> import Numeric
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named Numeric

Pujo Aji wrote:
Can you open the python interpreter and write:
import Numeric
  
What kind of error message you have?
Cheers,
pujo
  
  On 12/22/05, Johan Geldenhuys
   <[EMAIL PROTECTED]>
wrote:
  Hi
all,


I have installed Numeric (Suse 10.0) and it is in my site-packages
folder, but I can't import the module.

Any idea how to fix this/

TIA

Johan
___

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






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


[Tutor] Numeric RandomArray seed problem.

2006-01-01 Thread Pujo Aji
Hello,I tried calling RandomArray.seed()by calling RandomArray.get_seed() I get the seed number (x,y).My problem is that x is always 113611 any advice?Thankspujo
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numeric RandomArray seed problem.

2006-01-01 Thread Pujo Aji
Thank you Kent.pujoOn 1/1/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Pujo Aji wrote:> Hello,>> I tried calling RandomArray.seed()> by calling RandomArray.get_seed() I get the seed number (x,y).> My problem is that x is always 113611 any advice?Take a look at the source for 
RandomArray.seed(). It more-or-less splitsthe decimal representation of the current time in half, using the highdigits for x and the low digits for y. So x will change slowly, everyfew hours.Kent
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] "while" loop for satisfing two conditions , advice requested

2006-01-15 Thread Pujo Aji
in understanding while loop someone should understand "if conditional" first.In "If conditional" there are common relational symbol "and" and "or"Let's discuss  "and" conditional
Condition 1 Condition 2  ResultTrue    True    TrueTrue    False  FalseFalse  True    False
False  False  FalseIn short, and equal True if and only if both condition are true."If the while loop result condition  is true it will execute its block."
example:x = 1y = 1while x==1 and y==1: # it will be processed if x==1 and y==1 are both true, in this case it is!another example:x=1y=2while x==1 and y==1:

 # it will be processed if x==1 and y==1 are both true, in this case it is not!
Hope this help!pujoOn 1/15/06, John Joseph <[EMAIL PROTECTED]> wrote:
Hi   I am trying to use "while" loop  , here I wantwhile loop to check for two conditions , I  am notgetting an idea  how to use "while" loop for  checkingtwo conditionsI  used "&" condition , but it is not
giving me the expected resultsI used in this way while (condition no 1) & (condition no2):print "Results" I request guidanceThanks
 Joseph John___NEW Yahoo! Cars - sell your car and browse thousands of new and used cars online! 
http://uk.cars.yahoo.com/___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] string object into reference

2006-01-17 Thread Pujo Aji
Hello Kirk,If I'm not mistaken your idea is referencing two columns: first column is your acid name and the later is your surface area.Later you want to connect the surface area if you name the acid name.If that what you want another question arises... is your acid name is unique.
If it is you can make dictionary types.A   csbB   dskC   dskyou can create mydic = []mydic['A'] = 'csb'mydic['B'] = 'dsk'mydic['C'] = 'dsk'you have to transform the file into a list and after that start building the dictionary variable.
After this dictionary variable is filled. you can get the surface area by typing the acid name such as:print mydic['A'] # will result 'csb'Cheers,pujoOn 1/17/06, 
Kirk Vander Meulen <[EMAIL PROTECTED]> wrote:
Hi, just joined.  I've got a question that I'm guessing there's a
ridiculously easy answer to, but I'm having trouble (no excuses, I'm
just dumb!)...

My problem is I want to make a string object into a reference to
another object.  To be more specific, I'm reading through a text
file of amino acids.  The first item on each line is the amino
acid name, and a later item is its exposed surface area.  For each
amino acid, I want to add up the surface area as I go through the text
file.  So what I'm doing is, for each line, assigning the
reference 'residue' to the amino acid name.  I'd like to then make
the string referred to by 'residue' (eg, 'CYS' or 'TRP') a reference to
an object that I will subsquently increment by the surface area value.

Thanks for any help.  Perhaps I just need to be pointed to a
relevent thread or given the correct words to search for in the
archives or manual.

Kirk

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


Re: [Tutor] Python + MySQL , my first simple program does not gives results

2006-01-19 Thread Pujo Aji
You should fetch the results.   try: 

   result
= cursor.fetchall()   print result

Cheers,pujo import MySQLdbclass learnpython_db:def __init__(self):
db =MySQLdb.connect(host="localhost",user ="john",password = "asdlkj", db = learnpython)cursor = db.cursor()cursor.execute
(" describe contact" )
cursor.execute(" SELECT * fromcontact" )___Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com___Tutor maillist  -  
Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Pujo Aji
Hello Jon,Why don't use randint so you can record the index and the value Example:    WORDS = ("python", "program", "code", "xylophone")    Indword = random.randint
(0,len(WORDS)-1)    word = WORDS[Indword]    print Indword    print wordCheers,pujoOn 1/19/06, Jon Moore <
[EMAIL PROTECTED]> wrote:HelloI need some help for a program I am writing as a newbie to Python.
I have created a series:WORDS = ("python", "program", "code", "xylophone")
and then assigned one of them randomly to the variable 'word':word = random.choice(WORDS)I know that if I do:

print wordThe randomly chosen word will be displayed. I also know that if I type:print WORDS[x]I will get the corresponding word back. But how do I find 'programaticaly' the index number for the string that 
random.choice has chosen?The reason I ask is that I an writing a simple word jumble game and need to link the randomly chosen word to a hint should the user need one.-- Best Regards

Jon Moore

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


Re: [Tutor] how to do multiple searching against many lists

2006-01-19 Thread Pujo Aji
Yes you can.you can make:    search_list =['cat','python','parrot','donkey','e.coli']    animals = ['python','cat','tiger','donkey','zebra','lemur']    birds = ['parrot','mina','oriole','blue jay']    bacteria = ['
e.coli','bacillus','staphy','acetobacter']    mydic = {}    for animal in animals :     mydic[animal] = 'animal'        for bird in birds:    mydic[bird] = 'bird'        for bacteri in bacteria:
    mydic[bacteri] = 'bacteria'            for x in search_list:    print x, mydic[x]Don't forget to include 'python' in animals group.Cheers,pujo
On 1/19/06, Srinivas Iyyer <[EMAIL PROTECTED]> wrote:
Hi Group,my Problem:I have soms list for variety of animals, birds,bacteriaI have another list:search_list =['cat','python','parrot','donkey','e.coli']animals = ['cat','tiger','donkey','zebra','lemur']
birs = ['parrot','mina','oriole','blue jay']bacteria =['e.coli','bacillus','staphy','acetobacter']my output should look like this:cat '\t' animalpython '\t' animalparrot '\t' birddonkey '\t'animal
e.coli '\t' bacteriaCan I do this using dictionaries , so that to make itfaster?ThanksSrini__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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] processing a text file w/ OO?

2006-01-22 Thread Pujo Aji
you can use regex if you want.It gives you power to do text processing.OO will give you benefit because your program becomes clearer while it  is developedCheers,pujo
On 1/23/06, Michael <[EMAIL PROTECTED]> wrote:
Hi.I'm processing a tab-delimited text file where I read in a file,perform a bunch of operations on the items, and then write them outagain to a fixed-width text file.I've been doing this with a very functional approach:
- loop over lines- read line into dictionary- process dictionary values ( format phone numbers and dates andamounts, etc.)- pad dictionary values with spaces- write dictionary values out to file
Anyway, this all works fine. Not knowing much about OO, I'm wonderingif there's a way to approach this from an object-orientedperspective. Is there anything to be gained? Or is this type ofproblem best tackled with a functional approach?
TIA.___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] How can I clean the screen

2006-01-23 Thread Pujo Aji
Try :import osos.system('cls')you will able to see the effect when you run in windows console.Cheers,pujoOn 1/23/06, Suri Chitti
 <[EMAIL PROTECTED]> wrote:Dear group,
   If I am executing a python prog from the command line andneed to clear the screen (like using the cls command at the windows cmdprompt) midway into the program, how do I do it??  Any inputs will be
greatly appreciated.Thanks.___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting started - IDLE won't run

2006-03-23 Thread Pujo Aji
Hello Ross,Can you see pythonw in the task manager process after you run idle ?Please look at this website concerning some firewall that can stop idle:
http://www.python.org/download/releases/2.4.2/bugs/Cheers,pujoOn 3/23/06, Shaun Ross <[EMAIL PROTECTED]
> wrote:






Hi Group,
 
I'm just getting started with Python. I've 
downloaded and installed the latest version (2.4.2 for Windows). I'm running 
Windows XP Prow SP2 on my Toshiba Satellite P4 Centrino 2GHz with 2GB RAM. I'm 
using Trend-Micro PC-Cillin 2006 anti-virus & firewall.
 
The problem is that Python GUI (IDLE) doesn't run 
properly. It starts running when I click on the link / icon and then 
just seems to vanish (the hourglass displays, you can hear the hard drive 
read/write and then nothing). 
 
Python Command Prompt runs as 
expected.
 
I've tried the recommendations on the Python for 
windows download page without success.
 
Please advise what I need to do to fix 
this.
 
Thanks,
Shaun

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


Re: [Tutor] Object Oriented Programmin

2006-03-28 Thread Pujo Aji
Object is object, means like ordinary object we know.Let's say good things about objecs paradigm.First you can create object of course. object can contain property and action.You can put your object as part as other object. It makes sense since for example object hand is part of object body in human term.
You can derive a new object from your old one (with its property and action). You can, in this new object,  add a new function or change the function from the old one. This will make your old object untouchable and your new object easy to build (you don't have to build from the start)
Let's start with a simple code.We can create a simple dog classclass dog:    def __init__(self, name):    self.name = name    pass    def action(self):
    print 'run'class doberman(dog):    def __init__(self, name):    dog.__init__(self,name)    def bark(self):    print 'wuu'class coco(dog):    def __init__(self, name):
    dog.__init__(self,name)        def action(self):    print 'jump'        def bark(self):    print 'waa'#--d1 = doberman('deni')
d1.action()  # 'run'd1.bark()    # 'wuu'    d2 = coco('mayin')d2.action() # 'jump'd2.bark()    # 'waa'Note:Each has name as an ID.
a doberman uses the same action like dog classa coco uses  different action than the original action from dog which is 'run'In this example we can see we can change one object easily and doesn't change the original class which is dog. This make less prone to error.
both doberman and coco can use bark but the result will be differentboth doberman and coco can access name this also result in different way.It is nice since you can use the same word bark to all of the new dogs you've created.
I try to describe as simple as I can. In this example you can put another function like getname in dog class so that all type of dogs has this function automaticaly.Hope this helppujo
On 3/28/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
Hi ALLI have gone through the object oriented programming in Python, I amnot able to understand OOP concept in python,is there a methodical way to understand it and simplfy thingsThanks in Advance
RegardsKaushal___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Alternating patterns

2006-03-28 Thread Pujo Aji
Hi,you can also use simple way of iterating using modus:    L = [1,2]    for i in range(6):    print L[i%len(L)]121212Cheers,pujo
On 3/29/06, kevin parks <[EMAIL PROTECTED]> wrote:
 -->> Message: 10> Date: Tue, 28 Mar 2006 22:43:38 -0500> From: Kent Johnson <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Alternating patterns> Cc: tutor@python.org> Message-ID: <[EMAIL PROTECTED]>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>> kevin parks wrote:>> I have a set that i iterate over... but each time through it i would>> like to alternate between the original set and a variation of the set>> that has one of the members of the set altered (by + or - 1)
 So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like>> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7,
>> 9, 11] But then back again to the original  on the next pass (+1 back to 4,):>> [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc.
>>> How can one make such alternating patterns?>> itertools.cycle() will repeat a sequence indefinitely:> In [2]: from itertools import cycle>> In [3]: i=cycle([1,2])
>> In [5]: for j in range(6):> ...: print i.next()> ...:> ...:> 1> 2> 1> 2> 1> 2>> For non-repeating sequences I would look at writing a generator
> function> for the sequences.>> Kentokay.. i am painfully unaware of generators, iterators, sets, genexesand a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that
i find the online docs kind of terse and few of the Python books yetcover these newer constructs in detailitertools looks very cool are there any toots on the above and onSets & itertools? It really seems like it would help to know these for
my work... That liddo bit right up there with itertools.cycle alreadyhas me a drooling... (so helpful that would be!)-kp--___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] get a character of an ascii-value

2006-03-28 Thread Pujo Aji
Hello use this function:    print ord('a')    print chr(97)Cheers,pujoOn 3/29/06, Keo Sophon <
[EMAIL PROTECTED]> wrote:Hi all,I wonder how to get a character of an Ascii-value.  For example, i have r =
37. So i wanna print the character of 37. Is there any function?Thanks,Sophon___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ASCII

2006-03-28 Thread Pujo Aji
Hi Kaushal,Please clarify the problem more specific.Or you can tell us that you have a problem and want to use python to solve it?Sincerely Yours,pujoOn 3/29/06, 
Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
Hi AllHow do i use this ASCII values in my day to day activities, I am going throughlearning python,Please illustrate with examplesThanks in AdvanceRegardsKaushal___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ASCII

2006-03-29 Thread Pujo Aji
Hello,Basicaly, You use ASCII or Unicode when you have to deal with character conversion for example coding with a different language symbol, chinese letter etc. Sincerely Yours,Pujo
On 3/29/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
On 3/29/06, Pujo Aji <[EMAIL PROTECTED]> wrote:>> Hi Kaushal,>> Please clarify the problem more specific.> Or you can tell us that you have a problem and want to use python to solve
> it?>> Sincerely Yours,> pujo>>> On 3/29/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:> >> Hi All
>> How do i use this ASCII values in my day to day activities, I am going> through> learning python,>> Please illustrate with examples>> Thanks in Advance>
> Regards>> Kaushal> ___> Tutor maillist  -  Tutor@python.org> 
http://mail.python.org/mailman/listinfo/tutor>>Hi PujoIts a very general question not related to python at all, I have aminimum knowledge in ASCII just wanted to know how it is used and how
it helps outRegardsKaushal
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newbie question about default arguments

2006-03-29 Thread Pujo Aji
Hello Josh,you wrote a different problem. The tutorial should be like this:
Important warning:  The default value is evaluated only once.
This makes a difference when the default is a mutable object such as a
list, dictionary, or instances of most classes.  For example, the
following function accumulates the arguments passed to it on
subsequent calls:


def f(a, L=[]):L.append(a)return Lprint f(1)print f(2)print f(3)


This will print


[1][1, 2][1, 2, 3]


If you don't want the default to be shared between subsequent calls,
you can write the function like this instead:


def f(a, L=None):if L is None:L = []L.append(a)return LLook the second example use None instead of []To explain more detail let's create an example :
def f1(a, L=[]):    L.append(a)    return Ldef f2(a, L=None):    if L is None:    L = []    L.append(a)    return Ldef main():    m = f2(3)    print m # produce [3]
    m = f2(4)    print m # produce [4]        #     m = f1(3)    print m # produce[3]    m = f1(4)    print m # produce[3,4]    passin f1 : when we don't put the second argument the L=[] is created only once. The second input in f1 will be accumulated.
in f2: when we don't put the second argument L is given a None value. Inside this function if L is None then L = [] this will always make L = [] that's way no accumulation happened.Hope this help.pujo
On 3/29/06, Josh Adams <[EMAIL PROTECTED]> wrote:
Hi all,I was going through the tutorial at http://docs.python.org/tut/node6.html when Icame to the bit about default arguments with this code:def f(a, L=[]):
L.append(a)return Lprint f(1)print f(2)print f(3)returns:[1][1, 2][1, 2, 3]>From the postings here, I think I understand that this occurs because L is only
initialized when f is first run.  However, this code gives some different results:def f2(a, L=[]): if L == []: L = [] L.append(a) return Lprint f2(1)print f2(2)
print f2(3)returns:[1][2][3]I'm not too clear on why this doesn't return the same results as the first.  Cansomeone enlighten me?Thanks,Josh___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Pujo Aji
Hello,On 4/12/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote:
Hi AllI am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm8.7 List slices>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3]['b', 'c']  -> I understood this 
>>> list[:4]  -->  Does this mean its list[0:4]   ':' here means --> from the first element to element index 4
['a', 'b', 'c', 'd']  > I didnot understood this >>> list[3:] -->  Does this mean its list[3:0]
   ':' here means --> from element index 3 to the last element  ['d', 'e', 'f'] > I didnot understood this 
>>> list[:] -->  Does this mean its list[0:0]   ':' here means --> from the first element to the last element
['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this 
Please explain meThanks in AdvanceRegardsKaushalHope, this helpspujo 
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Explanation of Lists data Type

2006-04-12 Thread Pujo Aji
Sorry for the last explanationsthere is a correction!On 4/12/06, Pujo Aji <[EMAIL PROTECTED]> wrote:
Hello,
On 4/12/06, Kaushal Shriyan <[EMAIL PROTECTED]
> wrote:
Hi AllI am referring to http://www.ibiblio.org/obp/thinkCSpy/chap08.htm
8.7 List slices>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> list[1:3]['b', 'c']  -> I understood this 

>>> list[:4]  -->  Does this mean its list[0:4]   ':' here means --> from the first element to element index 3 # corrected

['a', 'b', 'c', 'd']  > I didnot understood this >>> list[3:] -->  Does this mean its list[3:0]
   ':' here means --> from element index 3 to the last element  ['d', 'e', 'f'] > I didnot understood this
 
>>> list[:] -->  Does this mean its list[0:0]   ':' here means --> from the first element to the last element

['a', 'b', 'c', 'd', 'e', 'f'] > I didnot understood this 

Please explain meThanks in AdvanceRegardsKaushalHope, this helpspujo
 

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



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


Re: [Tutor] underscore function

2006-04-13 Thread Pujo Aji
Python programmers prefer to use name convention to make method of class "looks" private.Usually they use of '_' before the private method or private attribute name.This private method like the one you mentioned def _abc is not intentionaly used outside the class other then it is used among other class methods privately.
Example:class A:    def __init__(self, myvar):    self._myvar = myvar    def _makedouble(self):    '''this method is private'''    self._myvar = self._myvar * 2        def printvarADouble(self):
    self._makedouble()    print self._myvardef main():    o = A(2)    o.printvarADouble() # 4You may use def abc instead of def _abc, again it is only a convention.
Hope this helps,
pujoOn 4/13/06, linda.s <
[EMAIL PROTECTED]> wrote:
I got a sample code and found somefunction definition looks like def _abcThere is one underscore before the function name "abc",what does it mean?___

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

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


Re: [Tutor] MySQLdb question

2006-04-14 Thread Pujo Aji
I think you can wrap the select sql command with a function which return a string.this function receive a particular hostname in a string format and return the whole 'SELECT ... FROM.. WHERE' style including the hostname from the function argument.
Cheers,pujoOn 4/14/06, Patty <[EMAIL PROTECTED]> wrote:
Hi,I have a data structure in a python file that looks something like this:my_map= { "host1":  {"target1", "target2", "target3" },   "host2":  {"target4", "target5", "target6" },
 }I have a method that has two parameteres (ahost, atarget), which I want to useto retrieve data from the database. In my database each host has a column andeach target has a row. The way I have it now is something like this:
cursor.execute("""SELECT host1, host2, host3, host4, host5, host6 FROM targetsWHERE target_name = %s """, (target))This is very inefficient because I'm retrieving data that I don't need. Instead,
I want to use the parameters in my method, but I'm not sure how to do itcursor.execute("""SELECT %s FROM targetsWHERE target_name = %s """, (ahost, target))  # I tried this, but it
didn't work.I also tried this, but got a error:cursor.execute("""SELECT %s FROM targetsWHERE target_name = %s """ %  (ahost, target))Can anybody show me the right way to do it?
Thanks,Patty___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] is gotchas?

2006-11-06 Thread Pujo Aji
For small string object python has optimization method so it is really the same object!Cheers,pujoOn 11/7/06, Tim Johnson <
[EMAIL PROTECTED]> wrote:* Kent Johnson <
[EMAIL PROTECTED]> [061106 10:31]:>> In [9]: a=[1,2]>> In [10]: b=[1,2]  Hmmm! Hmmm!  Lookee here:  ## console session>>> a=[1,2]>>> b=[1,2]>>> a is b
False>>> c='1'  ## one byte>>> d='1'  ## one byte>>> c is dTrue>>> c='1,2'>>> d='1,2'>>> c is dFalseThe Hmmm! is emmitted because I'm thinking that if everything is an
object in python, then why does `c is d` evaluate to True whenthe assigned value is 1 byte and evaluate to False when the assignedvalue is more that 1 byte?I think I ran into this before and that's why I never used `is'.
Good thread. Beats flame wars.thankstim--Tim Johnson <[EMAIL PROTECTED]>  http://www.alaska-internet-solutions.com
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] free IDE for Python?

2006-11-13 Thread Pujo Aji
Try scite:http://www.scintilla.org/SciTE.htmlpujoOn 11/14/06, Vadhri, Srinivas <
[EMAIL PROTECTED]> wrote:












Hi

 

A newbie to Python. What is the free IDE for Python
development activities? ActiveState's Komodo IDE needs a license and a
fee. 

 

Any recommendations?

 

Regards,

Srinivas Vadhri

 







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