[Tutor] Re: This Deletes All my Files

2005-02-04 Thread Andrei
Chad Crabtree  yahoo.com> writes:

> I've tried this and I cannot figure out why this does not work.  I 
> figure this has something to do with order of operations.  I figured 
> someone would know exactly why it doesn't work.  Wouldn't this start 
> inside parens then from left to right?
> 
> open(item,'w').write(open(item,'r').read().replace(' ',''))

Well, what your code says is this:
1. open item for writing and return a file object
2. call on that file object the write method (at this point its contents are
wiped out)
3. open that same file for reading (but it's empty now)
4. read everything from it (nothing)
5. write nothing back to the file.

You can test it by implementing a dummy open method and a dummy file class which
log what happens to them:

>>> s = "d:/tests/test.txt"
>>> class dummyfile(object):
... def open(self, *args):
... print "dummyfile.open:", args
... def write(self, *args):
... print "dummyfile.write:", args
... def read(self, *args):
... print "dummyfile.read:", args
... return ""
>>> def dummyopen(filename, type):
... print "dummyopen:", filename, type
... d = dummyfile()
... d.open(filename, type)
... return d

>>> dummyopen(s, 'w').write(dummyopen(s, 'r').read())
dummyopen: d:/tests/test.txt w
dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing
dummyopen: d:/tests/test.txt r
dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading
dummyfile.read: ()
dummyfile.write: ('',)

> spend 5 hours RTFM.  I got it to work by breaking it up to several 
> statements, but I would like to know.

And that's the way you *should* write it - code like this doesn't deserve to
work anyway :). 

Yours,

Andrei

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


[Tutor] Re: Small GUI toolkit and executable creators

2005-02-04 Thread Andrei
Patrick Kirk wrote on Fri, 04 Feb 2005 21:47:58 +:

> I'm writing an application that will distributed by download and want it 
> to be as small as possible.  The target platform is Windows.

Python isn't the right choice if your aim is minimum "executable" size. I
wouldn't worry too much about it though, people are perfectly used to
downloading multi-megabyte applications and service packs which run into
the hundreds of megabytes.

> For the GUI toolkit, I am looking at wxPython and tkinter.  For a small 
> application with only 4 working forms, which can be expected to produce 
> the smaller programs?

I have no idea. The number of forms is not relevant, since it's the toolkit
that takes up all the space, not the forms. I can tell you that a packaged
wxPython app is roughly 4 MB, don't know about Tkinter. wxPython looks
better (more native) though.

> Has anyone any comments on which produces smaller executables and and if 
> either is qualitively better than the other.

You shouldn't expect much difference in that respect, since they all do
pretty much the same thing: pack up the junk and put an exe stub on it, and
there's only so much compressing you can do.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Negative IF conditions

2005-02-11 Thread Andrei
Mark Brown wrote:
I'm a newbie and was wondering which of these IF conditions is better 
structure:

   1. if not os.path.exists('filename'):
   2. if os.path.exists('filename') == False:
I prefer the "if not" variety.
Yours,
Andrei
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: References in loops

2005-02-12 Thread Andrei
Matt Dimmic wrote:
In Python, one bug that often bites me is this:
(example A)
aList = [1,2,3]
for i in aList:
i += 1
print aList
--> [1,2,3]
Numbers are immutable, so the element 1 can't change into a 2 inside the 
list. If 1 was not immutable, e.g. a list you could modify it and then 
it would be "updated" in the original list too.

This goes against my intuition, which is that aList == [2,3,4], probably
because so much in Python is passed by reference and not by value. Of
course I can always use range() or enumerate():
I tend to use list comprehensions for this:
aList = [elem+1 for elem in aList]
but it's barely shorter than the explicit loop, so not necessarily an 
improvement from that point of view. But at least it prevents the bug 
from biting :).

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


[Tutor] Re: Accessing local variables from nested functions.

2005-02-13 Thread Andrei
Karl Pflästerer wrote on Sun, 13 Feb 2005 12:15:03 +0100:

> what's the Python way of accessing local variables in nesting functions? For 

> then there's no problem in running such function, but what if I'd like to 
> modify var1 so that the change were vissible in p()?

I'd use return in the form of

def p():
v = 3
def q():
return v+1
v = q()

If you need to modify a lot of p-vars inside q, I'd say it's probably wiser
to go with a class and appropriate methods.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Active Python

2005-02-17 Thread Andrei
Robert Campbell  mchsi.com> writes:
> I am not a programmer, but have decided to learn Python.  I am 
> wondering if anyone has used the Activestate ActivePython and what are the 
> advantages/disadvantages of using it rather than the standard Python 
> tools.

I use it, but I haven't used an official Python distro in quite some time, so
perhaps my info is outdated. Anyway, what I like about it is that it comes with
the Win32 stuff (including the PythonWin IDE) and that it has a better help
system. I think the official distro by now also has HTMLHelp, but I don't know
if it also includes Dive into Python, FAQ's and HowTo's like the ActiveState one
does. It's nothing that you can't download on your own for free, but it's just
more comfortable to get it all in a single package.

Andrei

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


[Tutor] Re: Class in a class

2005-02-18 Thread Andrei
Luis N  gmail.com> writes:

> Does it make sense to do this:
> 
> In [2]: class AB:
>...: pass
> In [3]: a = AB()
> In [4]: a
> In [5]: class BC:
>...: def __init__(self, foo):
>...: self.foo = foo
> In [6]: b = BC(a)
> In [7]: b.foo

This case is not that different from what you probably already do in classes,
given the fact that all attributes are objects anyway. Compare the following two
classes which have pretty much identical structure:

class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
# x and y would be simple floats, but nothing
# stops you from using more fancy attributes,
# like in the Line class below

class Line(object):
def __init__(self, point1, point2):
self.points = [point1, point2]
# note how self.points is a complex
# data structure (list object)!

Certainly if we can use standard objects like floats, lists or dictionaries as
attributes, we can also use objects of our own design:

class Triangle(object):
def __init__(self, line1, line2, line3):
self.lines = [line1, line2, line3]
self.points = []
for line in self.lines:
for point in line.points:
if point not in self.points:
self.points.append(point)

And you could go even higher, to a tetraeder made out of triangles, if you
extended Point to also allow z coordinates.

Andrei

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


[Tutor] Re: Functions Calling Functions

2005-02-25 Thread Andrei
Luke Jordan wrote on Fri, 25 Feb 2005 11:04:11 -0800:

Hi Luke,

> I'm working on a command-line game. Is there anything wrong with
> having each 'chapter' of the game be a function that links to other
> chapters by calling them? I only ask because when a recent traceback
> returned about 40 lines worth of error message, I realized that the
> functions are all being run 'within each other' (ah-ha!).

For a quick'n'dirty prototype while learning Python, I'd say it's
acceptable - although it's likely to end up costing you more time than if
you took a more thought-out approach. If it's something that you intend to
develop, distribute and maintain, I think it's not a good idea at all. It
would be better to find the functionality that your game offers, split it
into separate functions and call those functions using data form a
dictionary/list/database. 

E.g. let's say you have a game with three rooms arranged in a triangle. In
each room the user can play some mini-game or go to one of the connected
rooms. Having functions call each other could end up in the program
crashing if the user just walks from room to room, because you've in effect
got a recursive function going on, basically doing this:

  >>> def a(): c()
  >>> def c(): a()
  a()
  # huge traceback here

Instead, you could have the data in a format like this:

rooms = {
 1: ['First room', guess, 2, 3],
 2: ['Second room', hangman, 3, 1],
 3: ['Third room', safecracker, 1, 2],
 }

The keys in the dictionary are the room numbers. The properties of each
room are described in the form of a list, giving a room name, a mini-game
(which is the name of a function implementing the actual mini-game), the
number of the room to the left and the number of the room to the right.

Now all you'd need is to impelement a "while True" main loop which would
call a function DiplayRoom using one of the room-lists as argument.
DisplayRoom would display the name of the room and offer the user the
choice to play the mini-game or leave to the left or to the right.
Once the user chooses to leave, the new room number is returned as result
and the main loop calls DisplayRoom again, but this time using the
properties list of the new room. 

This approach offers the following advantages:
- you'll never be more than three functions deep or so (depending on the
precise implementation), so it's impossible for the user to crash your
program just by walking around.
- it's very easy to extend the program with new rooms or re-arrange the
'map', since you just have to modify the data. Modifying data is safer and
easier than modifying code.
- it's easier to debug than when you have a billion lines of call stack.
- I expect it to consume less memory

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Newbie simple question

2005-02-25 Thread Andrei
Valone, Toren W. wrote on Fri, 25 Feb 2005 14:14:59 -0800:

> I need to know how to read the next line while in the "for line in" loop.

If you want to skip some of the lines (whatever their source may be), I
think you should *not* use a for..in loop, but a while loop, in which you
read/skip lines manually as needed.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Linked List

2005-03-04 Thread Andrei
Shitiz Bansal wrote on Fri, 4 Mar 2005 09:19:41 -0800 (PST):

> Any body has any idea on how to implement a linked
> list in python?

Perhaps like this:

>>> class node(object):
... def __init__(self, item, next=None):
... self.item = item
... self.next = next
>>> a = node('item a')
>>> b = node(3)
>>> c = node((3,4))
>>> d = node('last item')
>>> a.next = b
>>> b.next = c
>>> c.next = d
>>> mynode = a
>>> while mynode:
... print mynode.item
... mynode = mynode.next
item a
3
(3, 4)
last item

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Re: Q & A

2005-03-04 Thread Andrei
Chelan Farsight wrote on Fri, 4 Mar 2005 12:37:58 -0600:

> actions of Mr. Chui.  I simply wanted to make sure that I have joined
> the right list.  Are we allowed to ask total n00b questions on this
> list?  If not what level of understanding is presumed before someone
> should post a question?

The Tutor list is for beginners, which includes people who haven't
programmed before. I'd say it even includes homework where the student in
question has actually tried doing something and ran into a snag, but not in
the case where the student just posts a "solve this homework for me".

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: xmlrpc server

2005-03-24 Thread Andrei
Luis N wrote on Thu, 24 Mar 2005 05:31:03 +0200:

 
> py-xmlrpc uses a scant 4mb of memory, does only one thing, and does it
> well, serve xmlrpc requests. It appears significantly faster than
> Twisted.
> 
> SimpleXMLRPCServer, as a CGI solution, appears acceptable, given that
> it be run from FastCGI or mod_python to give it that extra boost.

Unless you are aware right now of certain limitations which make one of the
solutions a priori unusable for whatever you want to do, I'd say just go
with the one which you find easiest to use and try to code in such a way
that it's reasonably easy to replace it with something else later. For
example 20 MB memory use doesn't sound like much to me on a modern
computer, but I'd leave Nevow out of the choice of your XMLRPC server.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Module Loop doesn't work (Joseph Q.)

2005-04-01 Thread Andrei
Joseph Quigley wrote on Fri, 01 Apr 2005 10:07:08 -0600:

>   I have some code on a geek dictionary that I'm making where the command 
> geeker() opens a module for the "real" geek dictionary (where you can type 
> a word to see what it is geekified). Supposedly, you type lobby() to go 
> back to what I call  the lobby (where you can get info on the web site and 
> email and version). But it just loops back to the Geeker>>> prompt where 
> you type the word that you want geekified. I even tried having it restart 
> the whole program by importing the index module that I wrote. But it still 
> won't restart the program!

Without seeing your code, I doubt anyone will be able to solve your problem
except by pure chance. In addition to that, I'm confused by the use of
function calls in what seems te be essentially a menu system. 

Speaking in general terms, the way you could handle this is as follows:
- have a main menu loop (what you call the lobby) which accepts user input
and based on that input calls other functions which perform certain tasks
(e.g. open a webpage or go to the dictionary part)
- the dictionary part would in turn be another loop accepting words as
input which get 'translated', until the user gives a blank string or
whatever as input in order to terminate the loop (and automatically fall
back into the loop of the lobby)

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Self referencing within a dictionary

2005-04-02 Thread Andrei
Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:

> I know that as above doesn't work, but was just wondering if it's
> possible, and if it's a
> Bad Thing?

Max has already shown it's possible. Whether it's a Bad Thing... I don't
see why it would be. But I also can't imagine right now any realistic cases
where it would be useful to have a dictionary contain itself as a value.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Re: Self referencing within a dictionary

2005-04-03 Thread Andrei
John Fouhy wrote on Sun, 03 Apr 2005 09:53:56 +1200:

> Andrei wrote:
>> Liam Clarke wrote on Sat, 2 Apr 2005 22:12:49 +1200:
>>>I know that as above doesn't work, but was just wondering if it's
>>>possible, and if it's a Bad Thing?
>> Max has already shown it's possible. Whether it's a Bad Thing... I don't
>> see why it would be. But I also can't imagine right now any realistic cases
>> where it would be useful to have a dictionary contain itself as a value.
> 
> It wouldn't contain itself as a value.

My mistake, I read the messages hastily and missed the ['a']. It was a more
interesting question that way ;).

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: one line code

2005-04-04 Thread Andrei
Christian Meesters wrote on Mon, 4 Apr 2005 14:49:28 +0200:


> Could it be that a C-like solution with 
> '?' and ':' is more straightforward than a solution with Python or am I 
> just too blind to see a real pythonic solution here?

Pierre did the Python equivalent of the ternary operator in his solution.

> I am aware that putting a solution in one line of code might be against 
> the 'Zen of Python' (... Complex is better than complicated ... 
> Readability counts ...), but since I'm just asking out of curiosity, 
> perhaps I'll get an answer anyway. ;-)

>>> l = ['1','2','3','abc','','4', '9.5', 9]
>>> [(eval(compile('exec """try:t=float("%s")\nexcept:t="%s" """ in 
>>> globals(),locals()'%(s,s),'','exec')),t)[1] for s in l]
[1.0, 2.0, 3.0, 'abc', '', 4.0, 9.5, 9.0]

I would recommend against it though :). Having a special function for this 
purpose is the way to go, a ternary operator doesn't really add anything to 
the quality of the code.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq 
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: building strings of specific length

2005-04-04 Thread Andrei
Vines, John  (Civ, ARL/CISD) wrote on Mon, 4 Apr 2005 10:04:59 -0400:

> Hello. I have a question regarding strings.  How do I format a string to be a 
> specific length?
> For example I need 'string1' to be 72 characters long.

You could do (I'll use 20 instead of 72 to keep it readable):

>>> s = "%20s" % "xyz"
>>> len(s), s
(20, ' xyz')

or:

>>> s = "xyz"
>>> s = s + (20 - len(s)) * ' '
>>> s, len(s)
('xyz ', 20)

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: one line code

2005-04-05 Thread Andrei
Alan Gauld  freenet.co.uk> writes:

> > With other words I'd like to tell Python: Convert into a float if 
> > possible, otherwise append anyway. 
> 
> [ (type(x) == type(5) and float(x) or x) for x in mylist ]

Almost fell for it too, but the original list contains numbers 
stored as strings :).

Andrei


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


[Tutor] Re: Mouseclick

2005-04-06 Thread Andrei
Ãyvind  kapitalisten.no> writes:

> and would like to click the left mousebutton at that position. Is that
> possible? I have just been able to find ways to click the button on
> buttons that I can name such as:
> def findAButtonCalledOK(hwnd, windowText, windowClass): # Define a
> function to find our button
> return windowClass == "Button" and windowText == "OK"
> okButton = findControl(optDialog, findAButtonCalledOK)
> click(okButton)

Looking at the implementation of the click() function on the site you 
got that from:

  http://www.brunningonline.net/simon/blog/archives/000664.html ,

a click is a left button down followed by left button up. The docs:

http://www.6URL.com/FED

state that the last parameter (lParam) is the position. This page shows 
how to construct it:

  http://www.geocities.com/practicalvb/vb/windows/messages.html

There's probably something available with ctypes or win32all to build 
the lParam, but if that's not the case, you can do something like:

lParam = ypos * (2**16) + xpos

(with the positions being relative to the top/left of the control 
the handle of which you use in the SendMessage). If you pass that
parameter in the SendMessage calls, I think the mouse should click
on a certain position (although I haven't tested, as I'm not on 
Windows ATM).

Yours,

Andrei



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


[Tutor] Re: Help with classes

2005-04-07 Thread Andrei
Kevin  gmail.com> writes:

> I am fooling around with classes and I was trying to create a very
> small one player text adventure. I made a class called commands here
> it is:
> class Commands:
> def __init__(self):
> pass
> def quiting(self):
> sys.exit()
 
> I want to beable to type in a command from the list at the prompt and
> have it call one of the functions from the class. I was looking for a
> shorter way to write it but the only way I can think of is with an if
> statment for each command. Is there a better way or shorter way to do
> this?

I don't think you're making proper use of classes. A class is a collection of
data and methods related to that data. The Commands class is merely a collection
of unrelated methods. IMO the natural solution for your problem would be a
dictionary, where a command is mapped to a function. You'd ask the player for a
command, strip + lowercase it and check if you have a key of that name in your
commands dictionary and if that is the case, run the associated function. It's a
shorter solution and easier to maintain than making a class, keeping a list of
commands and inspecting a Commands object to see if something is available.

Possible classes in a text adventure could be a Player class (which could
contain a list of items which the Player carries, life points, etc.), a Room
class (which could contain information and methods related to the room the
player is in plus the connected rooms), an Item class (with subclasses for
different types of items, where different implementations of e.g. PickUp methods
would determine if the player could pick up a pencil or a skyscraper), etc.

Yours,

Andrei

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


[Tutor] Re: Help with classes

2005-04-08 Thread Andrei
Bob Gailer  alum.rpi.edu> writes:

> At 12:22 PM 4/7/2005, Andrei wrote:
> >Kevin  gmail.com> writes:
> >
> > > I am fooling around with classes and I was trying to create a very
> > > small one player text adventure. I made a class called commands here

> >I don't think you're making proper use of classes.
>
> IMHO there is no "proper use of classes".

Perhaps I didn't phrase that quite the way I intended. What I meant is that
there are places where classes are obviously beneficial and there are places
where a different solution is the easier one. Python is fortunately flexible
enough to allow all kinds of approaches.

> In Python a class is whatever one creates using the class statement. In 

As it is in all languages. Which is not to say that any class the language
allows you to make is actually useful or the best way to do the job. Python has
with its tuples, lists, dicts and sets a whole bunch of collection types readily
available, which look like collections and are instantly recognized by any
programmer as collections (unlike a class, which I for one would expect to be
used as more than a collection when reading code).


> Kent's proposal makes IMHO excellent use of the class mechanism. One may 
> also access the class __dict__ directly in lieu of using getattr.

Yep, hence my statement that a class in this use case is just a confusing way of
using a dict :). I read (perhaps misread) Kevin's post as a question from
someone who is new to OOP and wants to learn about it, rather than a request on
info regarding the manipulation of class internals. 

> >The Commands class is merely a collection of unrelated methods.
> 
> But they are related. Each represents a game command; the class is the 
> container for the commands. And it might be that as the program expands 
> that there would be multiple instances representing players or saved games 
> or ??? And class properties would keep track of the player's status.

Guessing at Kevin's intentions is quite difficult by other means than reading
the posted code. A class called "Commands" that only contains methods
implementing actions as results to commands given by the human player, can't
reasonably be interpreted as something that will at some point hold a
character's status.

Yours,

Andrei

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


[Tutor] Re: Help with classes

2005-04-08 Thread Andrei
Kevin  gmail.com> writes:

> Well this OOP stuff is realy hard for me as I have never even
> programmed it took me a while just to understand defs. However I am
> determined to learn how to do it. My biggest problem is with __init__
> I still don't understand how to use it. Though I did try somthing
> different with my code rather then having the dict of commands in the
> main part of the code, I put it in th __init__ of class Comands like
> so:

__init__ is called when a new instance of that class (an object) is created.
It's particularly useful when used with certain arguments in order to initialize
certain properties of an object. Let's say you have a number of enemies and each
enemy has a certain name and strength. You can then define a class like this:

class Enemy:
def __init__(self, name, strength):
self.name = name
self.strength

and create any number of enemies like this:

enemy1 = Enemy('Gargoyle', 10) # calls __init__
enemy2 = Enemy('Soldier', 3)

If you then ask enemy1 about its name, it wall answer:

>>> print enemy1.name
'Gargoyle'

> When a player type is "get sword" it will add a sword to there
> inventory. Wich I'm not sure if I am going about this the right way.

That part about the sword in the inventory sounds right. Let's do a quick dummy
implementation:

class Player:
def __init__(self, name, strength):
self.name = name
self.inventory = [] # player always starts with empty inventory
self.strength = strength
def PickUp(self, item):
# the player can only cary the amount of stuff around
# that is allowed by his strength
if len(self.inventory)==self.strength:
print "You are not strong enough to pick that up!"
else:
self.inventory.append(item)
print "You've picked up a %s" % item.name

class Item:
def __init__(self, name):
self.name = name

conan = Player('Conan the Barbarian', 3)
excalibur = Item('sword')
bottle = Item('bottle of water')
ball = Item('crystal ball')
scroll = Item('ancient scroll')

conan.PickUp(excalibur)
conan.PickUp(ball)
conan.PickUp(scroll)
conan.PickUp(bottle) # will fail

donan = Player('Donan the Civilized', 2) # different player!
donan.PickUp(bottle) # can pick it up, because donan != conan



(The implementation above has some obvious problems, like not being able to drop
anything, a sword demanding just as much strength as a bottle and most
importantly the fact that donan will be able to pick up excalibur even though
conan already has it.) 
You can see that conan and donan are both players (Player objects), but each of
them has his own name, inventory and strength. Even if conan's inventory is
full, donan can still pick up new things.

Yours,

Andrei

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


[Tutor] Re: Class - superclass

2005-04-08 Thread Andrei
Bernard Lebel wrote on Fri, 8 Apr 2005 15:05:13 -0400:

> I'm experimenting with basic inheritance concepts, and something that
> I would assume to work returns an error.
> 
>>>> class A:
> ... def __init__( self ):
> ... self.a = 13
> ...
>>>> class B( A ): # create sub-class of class A
> ... def __init__( self ):
> ... self.b = 14

Call the __init__ of the ancestor explicitly:

>>> class B(A):
... def __init__(self):
... A.__init__(self)
... self.b = 14
>>> b = B()
>>> b.a, b.b
(13, 14)

B inherits everything from A, but by defining B.__init__, the __init__
inherited from A is replaced, so you'll need to call it explicitly. Python
has no way of knowing that you still want to use the original __init__ too
unless you tell it so. To demonstrate the fact that __init__ is indeed
inherited:

>>> class C(A):
...     pass
>>> c = C() # inherited __init__ (A.__init__) is called
>>> c.a
13

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: Help with classes (Joseph Q.)

2005-04-09 Thread Andrei
Joseph Quigley wrote on Fri, 08 Apr 2005 16:46:33 -0600:

> Now what are dictionaries and the __name__ really used for? A byte of 
> python never got that through my thick skull.

Dictionaries associate a value with a certain key, sort of like a real
world dictionary where you can take a word and look up its
meaning/translation (except that real world dictionaries are alphabetically
sorted and only contain words, while Python dictionaries are not sorted and
can contain lots of things, including numbers and tuples). 

It's possible to get by without using them directly (other languages don't
even have something resembling a dictionary and they still manage to work
somehow :)), but you might end up building functionality to emulate their
behaviour with for example lists. Let's say you build an application which
allows the user to attach comments to their pictures: you could use a
dictionary for it, mapping a string to each file name:

comments = {}
while True:
photo = raw_input("Picture name: ")
if photo = '':
break
comment = raw_input("Comment: ")
comments[photo] = comment
print comments

You could also think of an address book (where you use names as keys and
addresses as values), a menu system (where certain user input is mapped to
a certain function), a cache system (where results of certain
time-consuming operations are saved in case the user asks for the same
operation again) and there are many, many other uses.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: import.... (Joseph Q.)

2005-04-09 Thread Andrei
Joseph Quigley wrote on Fri, 08 Apr 2005 16:58:37 -0600:

> import is handy. But my questions are:
> is there a type of unimport or something to unload a module? 

Things which are not used are cleaned up automatically at some point. What
would you like to do do that this mechanism doesn't provide?

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: import.... (Joseph Q.)

2005-04-10 Thread Andrei
Joseph Quigley  gmail.com> writes:

> Well, I'm importing a custom module, and I can't loop back to the module I 
> imported (the modules are different modes of the program. Someone suggested 
> classes, but I have no idea how to use them. 

So you have two modules which implement the same functions in different ways,
depending on the mode of the program? If this is the case, just import the
modules by name and use the dot-notation (see post before mine). There's no need
to unload anything. Whether classes are useful in this case: it's possible, but
without a more detailed description it's hard to determine. I would say it's
perpahs a bit unusual if you do indeed have two modules with the same interface
but different behavior.

Yours,

Andrei

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


[Tutor] Re: Sorting of files based on filesize

2005-04-11 Thread Andrei
Klas Marteleur  telia.com> writes:

> Some of my harddrives are getting full and i would like to burn the files to 
> some cheep DVD's. Filesizes range from lets say 1Mb to 1Gb. 
> 
> Ofcourse i would like to optimize the size of each DVD to be as close to 
> 4.7Gb 
> as possible (to save this cheep media :) ).
> 
> There are plenty of software that are able to index my DVD's so sorting 
> between disks is not a problem. Just size.
> 
> What i would like to do is write a Python program that could sort my files 
> (based on size) into chunks as close to a given storage size (DVD 4.7Gb, CD 
> 650Mb...), and minimize the use of disks. Does anyone know of if something 
> like this is done before in Python, that i could look at?

Depends on how optimal you want things done. The easiest way is probably to sort
them by size, start with the largest and then keep adding smaller ones to the
compilation until it's full. Then start with the largest that's left and repeat
the process until you're left with (part of) a DVD with all kinds of small
files. I have some doubts about how optimal this will turn out to be. 

So instead, I went and implemented a fun 100-line script which uses a simple
genetic algorithm to generate disc layouts. Lacking real files, the script
listed below first generates 500 files with normally distributed sizes with an
average of 200 MB and a standard deviation of 200MB (with some sanity checks to
prevent files with negative size and files larger than 650MB) and tries to cram
those in 650MB CD's. 

Here's the link: http://ww3.6URL.com/FOK

It does this by first shuffling the list of files in a random manner several
times and determining the best fit of those (the solution that fills up the
discs as much as possible). This is the initial parent. Then it randomly
shuffles parts of this parent several times and determines the best fit of those
combinations. Then it uses that best fit to generate new children, etc. 

The siblings variable determines how many shuffles are performed before a best
fit in that group is selected. The generations variable determines how many
times the process of selecting the best is repeated.

The algorithm seems to work reasonably well (I get 190-ish CD's for files which
would cover 180-ish CD's if those CD's could be filled perfectly, even though
initial random file distributions give 240+ discs), but I haven't checked the
results very thoroughly. It might be doing something really stupid. It's also
reasonably fast (1000 generations of 1000 individuals each is feasible for
example, but not necessarily very useful). There's also no guarantee that the
result is the absolute best you can get.

Yours,

Andrei

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


[Tutor] Re: sorting a list of dictionaries

2005-04-12 Thread Andrei
Gooch, John  echostar.com> writes:

>   lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
>   where field is either 'name' or 'size'.
> What is "n:" and what is "lambda m" ? 

You could rewrite that in a more readable manner as follows:


def comparedict(dict1, dict2):
"Compares the values of a certain key in the two dictionaries."
item1 = dict1[field]
item2 = dict2[field]
return cmp(item1, item2)

lst.sort(comparedict)


m and n then correspond to dict1/dict2 (function arguments), lambda is in this
context just a different way of defining a function. The net result is a
comparison function which is called by the sort() method in order to determine
which of two dictionaries is 'smaller' or 'larger'.

Yours,

Andrei


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


[Tutor] Re: Python starting books (fwd)

2005-04-12 Thread Andrei
> From: Alexis  gmail.com>
> Hi people thanks to all of you for the suggestions, I am currently
> reading some programming books but it seems as if i can't findn a
> suitable one to get me started the way i want, i mean not only
> learning the basics but getting prepared for more complex programming,

I would say that learning the basics *is* getting prepared for more complex
programming. Typically you start with defining variables, doing simple
calculations, getting user input, get to know some modules in the standard
library, etc. Then you go on to classes (this is often a difficult topic). What
you do from there depends on your needs. You might want to dive in GUI
programming, web applications, scientific stuff, games, etc. and read up on that
particular topic.

The "How to Think Like a Computer Scientist" tutorial has some implementations
of common (but not necessarily useful to you) algorithms - e.g. trees - which
other books don't offer. You can also read those chapters on their own if you're
interested, but prefer to follow a different tutorial instead. In fact, you can
read texts about topics like that even if they're not Python-specific: if they
convey their ideas clearly, you can implement such things on your own.

Yours,

Andrei

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


[Tutor] Re: when to use properties?

2005-04-12 Thread Andrei
Marcus Goldfish  gmail.com> writes:

> Are there guidelines for when properties should be used vs. instance
> variables?  For example, it often seems more convenient to directly
> use instance variables instead of properties, like MyClass2 listed
> below.  Is one class more pythonic than the other?

In Python I tend to use methods directly, even though I think properties are
clearer and I actively avoid calling getters/setters directly in Delphi. I just
can't be bothered to write the extra line for some reason :). 

On the other hand, I never write getters/setters just for the sake of it. In
your example I would not have a self._value, but a self.value which is accessed
directly, since the getter and setter don't do anything special anyway. Now, if
I had such code and needed to add some processing before accessing the variable,
I might change it into a property and add the appropriate methods, so that the
interface remains the same.

Yours,

Andrei


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


[Tutor] Re: New to programming question

2005-04-13 Thread Andrei
Ben Markwell  gmail.com> writes:


> if prefixes[n] == 'O' or 'Q':

A tip: when working with several boolean (and/or/not) conditions in one test,
it's helpful to use parentheses in order to make sure you get what you expect.
Let me demonstrate.

The example above is equivalent to:

  if (prefixes[n] == 'O') or ('Q')  [1]

but you probably meant to write:

  if prefixes[n] == ('O' or 'Q')[2]


With the parentheses it's easier to follow what is going on. In case [1], first
prefixes[n] == 'O' is evaluated (which might or might not return a True). Then
('Q') is evaluated (which is True in a boolean context), which means that the
expression is sort of equivalent to:
 
  if (either True or False) or (True)

which is obviously always True.


Case [2] can be regarded in a similar manner. First ('O' or 'Q') is evaluated.
Let's see what this means. Both 'O' and 'Q' are True in a boolean context, but
what is the *result* of ('O' or 'Q')? After all, the result of this operation is
what you compare with prefixes[n]. You probably don't know the answer to this
question and that should trigger some alarm bells: it's never a good sign if you
don't understand your own code :).
Fortunately we have the Python interpreter available:

>>> ('O' or 'Q')
'O'

Aha! Well, this means that approach [2] is the same as:

  if prefixes[n] == 'O'

This is obviously not what you wanted to achieve.

Actually, I've jumped a bit too fast to a conclusion here, by assuming that ('O'
or 'Q') always returns 'O', just because that's what happened in my 1 test on 1
machine on 1 version of Python. This is a dangerous assumption: perhaps
elsewhere it could return 'Q' or True or 1 (all of these are equivalent in a
boolean expression)? 
In this case it turns out that it is correct (you can read the docs to find out
about how it works, or play around in the interpreter to get a feeling for it),
but be careful with such assumptions, they can bite you. For example let's thest
the assumption that a dictionary remembers the order the keys are entered in:

>>> d = {4:0, 5:0, 6:0}
>>> d.keys()
[4, 5, 6]

Look, it does! However, a different test reveals this:

>>> d = {4:0, 5:0, 1:0}
>>> d.keys()
[1, 4, 5]

Aha! So it sorts the keys (both tests support this conclusion). Or does it?

>>> d = {4:0, -1:0, 5:0}
>>> d.keys()
[4, 5, -1]

Nope, not sorted, not ordered - exactly as the Python specification states,
dictionaries are unordered.

Yours,

Andrei

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


[Tutor] Re: help (fwd)

2005-04-13 Thread Andrei
> From: Feziwe Mpondo  sanbi.ac.za>
> 
> how to run a programm after you have typed in the commands

Depends on where you type those commands. 

If you type them in the interactive interpreter, they are executed whenever you
press Enter. However, this method does not allow you to run the same program
twice (except by typing it in twice of course).

A better method is to use a text editor (you could use PythonWin, IDLE, SciTE,
Spe  or even Notepad). Type the code and, if you have an editor with good Python
support, locate its Run command in the menus and use it. If you use a plain text
generic editor, save the program and double-click on it in Explorer (if you're
on Windows) or launch it by typing at the command line:

  python myscript.py

Yours,

Andrei

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


[Tutor] Re: when to use properties?

2005-04-13 Thread Andrei
Marcus Goldfish  gmail.com> writes:

> This raised another design issue for me, tho', regarding property
> validation.  In C#/Java, I would typically do validation in all of my
> setter methods, but is this really pythonic?  It seems OO--
> encapsulation-- but also seems to be one of the biggest wastes of
> coding time & typing in those languages.

I wouldn't validate unless there's some subtle (hard to detect) bad
behavior that might catch people off-guard and unless I'm dealing with an
untrustworthy and potentially malicious data provider (in other words, 
the user :)). Even then, it might be better/easier to use catch exceptions 
than to validate in advance.

Let's say we take your example and feed a list to it as a number. It will
crash even without the validation. There's nothing subtle about it, and 
it's good enough "validation" for me. 

If you drop the validation and feed it a number larger than 99 or lower
than 0, it will work just fine, even though it's going beyond its stated
intended use. In fact, the validation makes it *less useful*, because it 
wouldn't permit the user to use the class to its full capabilities. 
Perhaps the user doesn't want to feed your class with numbers, but with 
some objects which mimmick part of the integer behavior 
(http://docs.python.org/ref/numeric-types.html), but not the comparison to an
integer. The validation makes that impossible too. That sounds
a bit useless in this particular fantasy case, but there are plenty of other
cases where it's very useful.

Regarding the integrity of the class: if you prepend _ or __ to internal
attributes/methods, users of your class know that they're not supposed to mess
around with them. They *can*, but from that point on, it's no longer your
responsibility to protect them from themselves. Python works on the assumption
that programmers are responsible adults :).

Yours,

Andrei


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


[Tutor] Re: (no subject)

2005-04-14 Thread Andrei
Jim and Laura Ahl  psci.net> writes:

> How come when I ask it to print i[2:4] from an inputted string it gives me the
letters between two and four
> 
> But when I ask it to print i[-1:-4] it does not print anything.

Because the range is counting forward from -1 (the last element) onward, and
since there's nothing after the last element, it can't print anything. It's the
same as typing range(5,2) for example. If you want it to give you the letters
beteen -1 and -4 backwards, type i[-1:-4:-1] (I'm not sure that works in older
Pythons). If you need the last 4 letters, type i[-4:].

Yours,

Andrei

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


[Tutor] Re: Craps, eternal loop (Joseph Q.)

2005-04-14 Thread Andrei
Joseph Quigley  gmail.com> writes:

> I also can't get the counter to save the added or removed money. every time 
> I play again, I always have $100

Without reading all the code (there might be other issues) I've snipped the
parts of the code away which are not interesting to this question, which
highlights the cause:

def play_again():
crapps()

def crapps():
 while loop:
 total_cash = 100
 if total > total_2:
 total_cash = total_cash + 10
 play_again()
 else:
 total_cash = total_cash - 10
 play_again()


total_cash is a local variable in the crapps function and is reset to 100 at the
start of every loop. Move this initialization to a different place (I'm not sure
when exactly you want to reset it as I don't know your intentions, but perhaps
before the loop, or make it a global variable and only initialize it at the
start of the program).

Yours,

Andrei

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


[Tutor] Re: Recursion....what are the best situations to use it?

2005-04-14 Thread Andrei
  Safe-mail.net> writes:

> If this is too general a question, perhaps you can tell me when NOT to use
recursion(where it would be
> inappropriate or inefficient).

Easy way to kill a Python program:

>>> def a():
... a()

Recursion is dangerous if its depth is unchecked. I've recently seen a recursive
quicksort implementation run wild for example, killing the program without any
error message (not in Python, but the principle is the same regardless the
programming language).

You can use recursion it for a shortest route algorithm, given a group of points
with certain connections between them (if there aren't too many points,
otherwise you'll hit a recursion depth limit or a stack overflow). Or for a menu
navigation system, where a showmenu() routine calls itself to display submenus.

Yours,

Andrei

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


[Tutor] Re: high score lists

2005-04-14 Thread Andrei
Alberto Troiano  hotmail.com> writes:

> I've read somewhere that the appropiate way to make a best score list is with
a dictionarie
> So you'll have something like this:
> best_score={"Peter":100,"Jhon":23} 

I don't see how that is in any way superior to a list of tuples. In fact, it has
distinct disadvantages, in that you'll have to do a 'lot' of work to get the
scores listed from high to low (which is what is usually done with them). The
situation would improve if you'd use the score as key and the player as value.
But even then it's still easier to keep them in a list of tuples, because it's
easier to do manipulations like "remove the lowest score" when you insert a
higher one.

Yours,

Andrei

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


[Tutor] Re: newbie intro to pickle

2005-04-16 Thread Andrei
D. Hartley  gmail.com> writes:

> So the .dump command is, in effect, saving the file, correct? which
> takes the object you're saving (in my case it would be
> high_scorelist), and ("filename",". what is the "w" ?)  Why does
> the temp file you're saving into end in .pik?

Pickling simply converts an object to a string (unpickling does the opposite,
convert a string to an object). The dump() function writes the generated string
directly to a file, but you can use the dumps() function to get the generated
string as such and do something else with it (e.g. put it in a database, send it
by mail, whatever).

>>> mylist = [1, 2, 34, 4.2, 'abc']
>>> s = pickle.dumps(mylist)
>>> s # display the string
"(lp0\nI1\naI2\naI34\naF4.2002\naS'abc'\np1\na."
>>> pickle.loads(s)
[1, 2, 34, 4.2002, 'abc']

Pickling is also very useful when combined with the bsddb module, because you
get a fast database which functions very much like a dictionary, and in which
you can put anything you like, as long as you pickle it first.

>>> import bsddb
>>> mydb = bsddb.btopen('game.db')
>>> mydb['highscores'] = pickle.dumps(mylist)
>>> mydb['highestlevel'] = pickle.dumps(21)
>>> mydb['lastplayer'] = pickle.dumps('John Doe')
>>> mydb.close()
>>> mydb = bsddb.btopen('game.db')
>>> pickle.loads(mydb['lastplayer'])
'John Doe'

This is not useful for small amounts of data like the highscores list, but if
you have more data (e.g. level data, dialog texts) and you need quick access to
it without having to keep everything in memory all the time, bsddb is a
comfortable option.

Yours,

Andrei

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


[Tutor] Re: exceptions

2005-04-16 Thread Andrei
Diana Hawksworth  optusnet.com.au> writes:

> I have been trying to trap a string entry by raising an exception.  The code
follows - but the exception is
> never raised.  What am I doing wrong?

I've snipped the code that is irrelevant to this question.

>  try:
>  self.guess = int(self.num_ent.get())
>  except(ValueError):
>  message = str(self.guess) + " is not a number. Please try again!"

Obviously it's hard to determine what's happening since I don't know that that
get() returns, nor what you do with the message. Now let's play with that a bit
in the interpreter:

>>> try:
... guess = int('abc')
... except (ValueError):
... print 'not a number'
not a number
>>> try:
... guess = int('4')
... except (ValueError):
... print 'not a number'
>>> try:
... guess = int('abc')
... except (ValueError):
... message = 'not a number'
>>> print message
not a number

The first run demonstrates that the code is working. The second run shows that
if your source doesn't return any invalid data, the exception will not be
raised. The third run shows that the exception is triggered, but you will simply
not notice it if you don't do anything with message. 

By the way, the third implementation contains a potential problem: if the
message variable does not exist before the try-except and everything goes well,
you'll get a NameError if you try to print it. Also if it does exist, it will
need to be reset before the try-except, otherwise afterwards you won't know
whether its value comes from the last try-except or from some time in the past.

On a sidenote: recommended Python style is to use 4 spaces per indentation 
level.

Yours,

Andrei

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


[Tutor] Re: newbie intro to pickle

2005-04-16 Thread Andrei
Lee Harr  hotmail.com> writes:

> Now my question is how do you keep people from just loading
> the high score file with whatever scores they want?

I'd say this is impossible particularly with Python, because cheaters could
always look in the source and find out whatever you're doing to the scores and
if they can't get around it, they can certainly feed that routine bogus scores
and get valid (but cheated) score files. Cheating happens even with
closed-source games.

The only reliable way of scoring is to have an application which both runs and
keeps scores on computers you control (i.e. an online in-browser game), without
relying on cookies or any other form of client-side data.

If you just want to keep casual tinkerers from playing with a plain text scores
file, simple safeguards would suffice, like:

- writing a MD5 hash of the scores list along with the scores themselves. If the
scores are modified and the MD5 isn't, the two won't match.

- implementing some trivial obsfucation (as opposed to real encryption)
algorithm which you could apply to the data before writing it. You could for
example use the zlib module for this (compress the result of pickle.dumps and
decompress the string read from file before feeding it to pickle.loads). The
result will look tremendously ugly and scary, plus it will save a few bytes in
storage space if you're lucky :).

- storing the scores in a bsddb (it can be modified by hand, but it looks quite
scary and mistakes might lead to breakage)

It's quite obvious though that no method is good enough if you attach any kind
of value to high scores, by e.g. posting the highest scores on your webpage.

Yours,

Andrei

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


[Tutor] Re: How can I avoid cut'n'paste in this case?

2005-04-16 Thread Andrei
Nigel Rowe  xoxy.net> writes:

> >> I have two modules, both define the same set of classes (with differing
> >> implementations) and a number of utility functions that use those
> >> classes.
> >> The utility functions are identical (the differences I need are
> >> abstracted in the classes), so they are cut'n'pasted into both files.

How about putting all utility functions in a separate module and doing a "from P
import *" or "from C import *" at the top of that module, depending on some
command line parameter or whatever it is that determines which one should be
imported? It's not elegant by any means, but at least you don't have to
copy-paste code around any more and the changes to the existing code are 
minimal.

> >> How can I refactor these modules to avoid the code duplication?

I would say that the fact that there are two parallel implementations of the
same classes with small differences is worrying as well. There should be an
ancestor layer in there implementing common behavior.

> Maybe I'm going too far, trying to eliminate the cut'n'paste, but I've
> always thought it a bad smell.

It does indeed smell of a maintenance nightmare waiting to happen :). The bad
part is that it tends to get progressively worse. Imagine also what would happen
if you'd get even more of those similar modules. 

Yours,

Andrei



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


[Tutor] Re: Installation Routines (Joseph Quigley)

2005-04-18 Thread Andrei
Joseph Quigley  gmail.com> writes:

> I have a friend who recently got a hush-hush contract. He told me that it 
> was for writing an installation program for Windows and that he considered 
> python and Tkinter as an option.
> I know there are installers written in python for Linux. I suppose they are 
> easier to write, than one for Windows?

Python isn't really suitable for installing applications because it requires
itself a quite large installation beforehand (unless you freeze it, in which
case you still end up with quite a large overhead; might be a problem for
internet-based distributions). However, if the installation is purely for
computers which already have Python installed and it's not as much about
installing (IOW, registry modifications, making shortcuts, etc.) as it is about
distributing files, then yes, it's a reasonable option. Otherwise I agree with
the other replies: it's better to go for NSIS, InnoSetup or even a
self-extracting executable as produced by just about any zip tool out there -
you get an environment specifically made for this purpose, with nice GUI/wizard
to produce the code and low overhead.

> Now, I'm still new, and can't do GUI yet, but I was wondering how hard 
> would it be to write a simple installer for windows? None of that fancy INI 
> and registry crapp, just a very simple file copier to, oh lets say, My 
> Documents?

That would be very easy. Using easygui.py (a Tkinter wrapper) it would be even
absolutely trivial (show a standard directory selection dialog, then copy the
stuff - 5 lines of code or so). It would be cross-platform too.

Yours,

Andrei

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


[Tutor] Re: snippets helps

2005-04-18 Thread Andrei
Chris Smith  bigfoot.com> writes:

> I have often wished for some small examples to break into the sometimes 
> dense technical notation. Has the python community ever considered 
> writing the "annotated documentation resource?" It would be nice if the 

I remember someone made some time ago a sort of shell around the Python docs
which allowed adding comments to the official docs. The Python docs are loaded
in a frame, the comments are stored separately by this system. It doesn't seem
to be very widely used, but it's probably still worth a look:
http://pydoc.amk.ca/frame.html

> documentation had more examples that were "VERY SIMPLE" to demonstrate 
> the use of some function or its arguments.

I agree, simple examples are indeed lacking in some parts of the docs. The
cookbook covers the more difficult options/tricks. I'd say Useless Python could
be a candidate for storing such simple examples, but I'm not sure it really has
the infrastructure required to search e.g. for examples using pickle.

> perhaps a link to another page would be better. Would a rating system 
> allow the snippets that people find most useful to rise to the top of 
> the examples?

It would indeed, if someone implemented it :).

> would get used or not.  Perhaps the personal feedback of the tutor list 
> is more effective.

OTOH, finding it yourself is faster than waiting for a reply.

Yours,

Andrei

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


[Tutor] Re: How to obfuscate a database password. (fwd)

2005-04-19 Thread Andrei
> From: David Driver  gmail.com>
> I am not necessarily talking about passwords for users but about the
> password that is used for connecting to the database. In a compiled
> language you would have to look pretty hard in a dll to find where the
> password had been encoded. As you point out there will be users inside
> of the application. Their passwords will be hashed and stored in the
> database. That is relatively easy to execute. But the password that
> the application uses to connect to the database is going to be stored
> somewhere in the code.

Storing passwords in the exe/dll/pyc doesn't sound like a particularly secure
option whichever way you look at it. If you don't value the password of the DB
very much, you can always obsfucate it (zipping or converting to a list of
integers comes to mind, or you can be creative and devise something else -
though more obsfucation != more security). The effect this will have in stopping
a determined person will be pretty much zero, but at least it's not out there in
the open and a simple text search won't cause it to just show up.

Yours,

Andrei

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


[Tutor] Re: Installation Routines (Joseph Quigley) (Jay Loden)

2005-04-22 Thread Andrei
Joseph Quigley wrote on Fri, 22 Apr 2005 13:45:05 -0600:

> Interesting. So several distros use rpms? I though only red hat used 'em.

Yeah, including some major ones like Mandrake and Suse.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


[Tutor] Re: CLS? (Joseph Quigley)

2005-04-22 Thread Andrei
Joseph Quigley wrote on Thu, 21 Apr 2005 18:15:51 -0600:
> In QBASIC there was the command "CLS"
> this wiped the screen and "started printing letters to the screen at the 
> top " of the console window.

With a quick Google, it does indeed appear to be in the cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65257
(look under >>> Platform Testing <<<).

For Windows this is:

import os
os.system('cls')

It's actually just sending the cls command to the dos box it's running on,
it's not built-in (hence the need for platform-specific code in the recipe
above).

> Is there any such command in Python? Would a Python cook book have this (I 
> have pay-by-the-minute dial-up Internet so I can't go online for long)?

I'm tempted to say that if you need cls, you've got the wrong interface for
your application :). Command line apps which wipe out the command line
history are bad. You might prefer making a GUI or a web application
instead.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] tokenize row numbering

2005-05-02 Thread Andrei
Chris Smith  bigfoot.com> writes:

> ###
> # line 1 according to tokenize tuple
> # line 2
> a=b #line 3
> ###
> 
> Does anyone have an idea of *why* the rows/physical lines of code 
> beginning their count at 1 instead of 0? In order to process the code I 

The snippet above shows that numbering begins at 0, with the fourth line having
number 3. So either I misunderstand the question, or the snippet is confusing.
That being said, I can imagine counting lines from 1 because programming editors
also tend to count from 1 instead of 0 and this way it's consistent. 

Yours,

Andrei

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


Re: [Tutor] Psyco (Joseph Quigley)

2005-05-04 Thread Andrei
Max Noel wrote on Wed, 4 May 2005 17:30:48 +0100:

> On May 4, 2005, at 16:35, Joseph Quigley wrote:
>> For those who use Psyco:
>> Is it any good? I'm searching for instructions on how to use  
>> it, should I
>> stop?

Depends on the application. If you have a performance problem in the code
(this is an important aspect: don't waste your time on optimizing if there
is no problem), profile it to identify the source and try psyco-ing it. It
might help, but it might also not help. It's hard to predict its effects
without profiling beforehand, the speed increase factor may be anywhere
from say 100x (in extremely lucky situations) to 0, with code of average
optimizability probably being in the 2-5 range.

Note that in some cases algorithm improvements can give tremendous speed
boosts without any external help (e.g. I've seen in several cases factor 20
speed gains just by swithing from 'normal' algorithms to fancier features
in Python, using the built-in libraries wisely or implementation of simple
caching systems).

>  I hear it's quite good at what it does. Note, however, that it  
> only works on x86 computers (i.e. IBM PC compatibles).
>  Also, if speed is what your program needs, you should go all the  
> way and rewrite the critical parts in pure C. It's not very difficult  
> to do -- the tutorial on www.python.org explains how to do it.

I disagree there. Psyco can deliver significant speed improvements on
certain types of code at virtually no cost (something along the lines of 2
lines of Python code) and to make things even better, your code will still
run on computers without Psyco (only slower). That could be worth doing
even if you only shave a couple of seconds off something that runs
repeatedly. Coding in C might give better speed improvements, but at a
significantly larger investment of time *and* your code won't work unless
your custom module is present on the target machine.

>> For those who don't know about Psyco:
>> It is supposed to be a Python Compiler. The programs are said  
>> to run
>> faster than normal Python and they almost run as fast as C.
> 
>  It's not a compiler. It's a JIT (Just-In-Time) compiler, a  
> little bit like HotSpot for Java.
>  Also, while it is faster than regular Python, it is still much  
> slower than C.

Except in some amusing cases:
http://mail.python.org/pipermail/python-list/2004-April/215272.html

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] dicts&lists vs objects

2005-05-12 Thread Andrei
Chris Somerlot  gmail.com> writes:

> is a premutation of another, and I'm having trouble following the code
> I've written.
> Is there a golden rule to knowing when to use objects instead of dictionaries
and lists?

It all depends on the programmer, the project, etc. I'd say that the fact that
you're having trouble following your code is an indication that it might be time
to drop the procedural/inline approach for something more structured. Not that
it's impossible to write unmaintainable OOP code by the way, far from it :).
E.g. imagine having one huge big Application object with everything that was a
function having become a method of this monolithic object. Not an improvement at
all.

Depending on what/how you write, I'd say that for code over 50 lines (say 1h of
work) an OO approach at least deserves consideration and will often turn out to
have some benefits (it's possible to mix OO and procedural code). If a project
runs into thousands of lines of code, it virtually always makes sense to bring
OO into the picture.

Yours,

Andrei

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


Re: [Tutor] Python Resources

2005-05-13 Thread Andrei
Greg Lindstrom wrote on Fri, 13 May 2005 07:52:54 -0500:

> would like to list some resources.  I have the Python home page, "Dive 
> Into Python", the Python Gems" page, but would like to ask what 
> resources would any of you suggest?  I'd like  between 5 and 10, with a 
> short description of each.

Not sure what the Python Gems is. I'd suggest the ActiveState Python
Cookbook as a valuable resource (though it's not exactly intro material).
The Daily Python Url is nice because it collects interesting posts in
Python-related blogs.

> subscribe to this mailing list and ask questions (though I do caution 
> them not to submit their homework simply to get a solution).

I think people reading a magazine called "IT Pro" should be aware of such
basic etiquette :).

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] YATENJoe

2005-05-17 Thread Andrei
Joseph Quigley  gmail.com> writes:

> I want to make a text editor. I know that there are hundreds out there,
> but practice makes perfect, and I need the practice. My problem is
> that I have no idea how to make one. I've tried a little already by
> defining line functions:def line1():l1 =
> raw_input("")

If you intend to make a text editor (something which allows the user to browse
through the text and manipulate it at will) using just raw_input and print, I
think you've set yourself an impossible task. For a console editor you should
probably look at curses (http://www.amk.ca/python/howto/curses/) - which don't
work on Windows, so you'll probably need this:
http://adamv.com/dev/python/curses/ (but according to the site it's 
incomplete). 

It's probably better to select a GUI toolkit which has an editor widget and
build your editor on that. Tkinter and wxPython both offer this, with wxPython
including a wrapper of the excellent Scintilla control (it has syntax
highlighting, word wrapping, support for non-monospaced fonts, etc.). You could
even write a webbased editor using the text entry widget provided by browsers
(crappy as it may be), even that would be better than hand-coding your own
editor widget.

> line2()Of course, this only allows for 2 lines. What's the trick to an
> infinite number of lines?

lines = []
while True:
lines.append(raw_input(''))

(But that offers no way to e.g. save and continue.)

> YATENJoe"? I'm still a newbie to python (actually OOP programming in
> general!) so I can't have a lot of complicated stuff thrown in my
> face.

Text editors are IMO not applications suitable for learning vanilla Python, or
OOP for that matter. Text editors are used as example applications in the RAD
IDE world (VB, Delphi and such) because in those environments a text editor is
literally three clicks away (click on memo component, click on form, click on
run). Vanilla Python has no GUI, so no memo component - hence my recommendation
for Tkinter or wxPython. PythonCard and Boa provide an experience somewhat
similar to commercial RAD IDE's if that's what you're looking for.

> I thought of a function that would define a function for me. Is this
> possible? If it is how would I do it? If it possible, here's my

Having one function for each line is a bad idea whether you code it by hand or
automatically (yes, it would be possible, but not something you should want to
do). A line of text is a piece of *data* similar to the line before it and the
line after it. 
A function implements certain behavior. Having the same behavior (raw_input)
implemented separately for each line is an extremely wasteful way of
programming. Use data containers (like lists) for storing data and use a single
function for manipulating any item (line) in such a data structure. E.g. let's
say you have 5 lines of text and you want to uppercase them all. Your way would
be to create 5 separate functions (or 1000 if there are more lines) for each
of the lines and call each of those. A better way would be to have a single
function and call that repeatedly telling it on which line to operate.

I would suggest that you learn a bit more about Python's facilities before
embarking on an ambitious project :) - you won't get very far without knowing
how to use lists and dictionaries.

Yours,

Andrei

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


Re: [Tutor] Opinions about this GIS script

2005-05-17 Thread Andrei
Ron Phillips  engineer.co.summit.oh.us> writes:

> The script produces expected results, but if anyone is so inclined, I'd
appreciate review/evaluation/critique of the 'pythonism' of the script. 

I haven't read it from A to Z, but it looks OK. Some minor things:

- string formatting, e.g.:
out+= 'Attribute: '+field+" => "+str(self.fileAttributes[field])+'\n'
I'd prefer seeing a format string. "Attribute: %s => %d\n" % (field,
self.fileAttributes[field]) - I'm guessing at types here, with file as string
and attrib as integer.

- lists of strings and ''.join instead of +, e.g.:
I'd favor making 'out' a list of strings and building the result at the end,
using "\n".join(out).

- long functions/loops: there are two parse functions which don't fit on my
screen. Perhaps they can be split in smaller parts. There's some duplicate code
in the two large (and also the third smaller) parse functions, indicating that
splitting in smaller pieces should be possible and would also remove the
duplicate code.

- There's a lot of "struct.unpack('>i',indexfile.read(4))[0]" and similar lines.
A file class which would wrap this stuff and offer a nice interface with methods
like ReadInt, ReadDouble would clear it up a bit.

- "Private function" in the comment of __newdemo. I'd remove it, since the
double underscore already documents this. 

Yours,

Andrei

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


Re: [Tutor] I know you will hate this but...

2005-05-17 Thread Andrei
Smith, Jeff  medplus.com> writes:   
> merge...that doesn't really matter.  It seems problematic to me to try   
> to enforce tool standards on people (IDE and editor settings) which may   
> or may not take.   
   
It seems problematic to me to NOT enforce standard *settings* (e.g. 4 spaces   
per indentation level, no tabs). Any IDE can be used as long as the proper   
settings are configured. Inconsistent indentation styles are very annoying in   
other languages, but a fatal problem in Python.   
   
> My solution has been to require (as a coding standard) ending comments   
> on control blocks longer than one line.  At least this is something that   
> could be caught at submit time with an automated review tool.   
   
Weird. Looks to me like the wrong solution (it would IMO be better to find out 
who committed the broken code and work from there to find the cause), but 
whatever works for you.   
   
> I'd be interested in how anyone else has solved this problem...provided   
> you've seen it.   
   
I haven't, but I use Subversion and haven't done team development in Python. 
But I don't think any half-decent VCS should go around modifying code on its 
own in *any* way, even if it's spaces. Although, now that I think about it, a 
VCS might have an option of ignoring leading/trailing whitespace when doing 
diffs, such an option could bite when merging Python code. 
 
Yours, 
 
Andrei 

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


Re: [Tutor] YATENJoe

2005-05-17 Thread Andrei
Joseph Quigley  gmail.com> writes:

> Is there a way of telling Python to make a new line after you press Enter
(return)?

Return automatically ends the current input line (and therefore starts a new
one) when you use raw_input.

>> I would suggest that you learn a bit more about Python's facilities before
>> embarking on an ambitious project :) - you won't get very far without knowing
>> how to use lists and dictionaries.

> So that's one of the ways Dicts, and lists are used for? I never could fully
grasp their use.

Perhaps you should have a look at "How to think like a computer scientist in
Python" (http://www.ibiblio.org/obp/thinkCSpy/). Chapters 8 and 10 discuss Lists
and Dictionaries
  http://www.ibiblio.org/obp/thinkCSpy/chap08.htm
  http://www.ibiblio.org/obp/thinkCSpy/chap10.htm ,

but I'd recommend you read all of it (or another Python tutorial).

Yours,

Andrei

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


Re: [Tutor] I know you will hate this but...

2005-05-18 Thread Andrei
Smith, Jeff  medplus.com> writes:

> But there is no way to enforce standard settings.  When new versions are
> installed or someone just makes a mistake the settings might change and
> you won't know until it's too late...possibly weeks later.

Programs when updated tend to keep their settings, as they're usually written
either in the registry or in the home folder. Perhaps PythonWin is different? I
think of it as basic programmer's responsibility, but it's also possible to
write an application to check the indentation settings and modify them, while
leaving the rest alone, regardless of where they're stored.

> >But I don't think any half-decent VCS should go around modifying code
> on its 
> >own in *any* way, even if it's spaces. Although, now that I think about

> Every CMS I've used modified code in some way.  CVS, RCS, VSS, Perforce,
> and Subversion support the use of keywords.  All of these tools, as well

Yes, but by using keywords (and at least for SVN telling it explicitly not to
ignore them) you instruct it to modify the code, it doesn't do so on its own. 

> back together again when a specific revision is requested.  Sure you
> hope it's the same as it was in the beginning but there's always a
> chance for error.

Yep. But the fact that only the indentation changed, sounds fishy. I'd rather
expect editor settings to be at fault than the VCS. If you do find out the
cause, don't hesitate to drop another message to the list, I'm curious :).

Yours,

Andrei

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


Re: [Tutor] Password

2005-05-18 Thread Andrei
Øyvind wrote on Wed, 18 May 2005 14:46:43 +0200 (CEST):

> The user enters a password first. These lines will create a string:
> '12c0faae657b3d068c0f19b71f5b43bc' This string will be stored in the file
> settings.txt

That's a very good way of preventing the user's password from being
reconstructed. If that's all the safety you're looking for, then it's OK.
If the password is intended to safeguard some really important data, it's
not safe to store the password or the hash - you'll have to encrypt the
data in such a way that it can't be decrypted without the password, even if
the source code is available.

-- 
Yours,

Andrei

=
Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] While loop exercise

2005-05-22 Thread Andrei
. ,  hotmail.com> writes:

> I just finished the chapter which includes while loop, if-else-elif 
> structure and randrange().
> 
> Can anyone suggest me 3 exercises to remind of the chapter?

The standard exercise which includes all three would be a number guessing game
where the computer picks a number and the user guesses it (the opposite is also
possible, but then randrange is not useful). A while loop is standard in *any*
program that can be executed more than once. E.g. asking someone for a string is
a single line of code, but asking for an unlimited number of strings directly
requires a while loop.

> Looking forward to writing some programs!

At this stage there aren't many really useful application you can make, but you
should use your fantasy. Pick a subject you know something about and make a
simple application for it. I think there are lots of suitable subjects in maths,
physics and children's games, but you can find suitable subjects in lots of
other fields too.

Other possible small programs using while and if (randrange is a bit exotic and
not that useful):
- let the user input names and dates of birth. Calculate membership fee to a
club based on whether the person is a child, an adult or a senior citizen.
- a quadradic formula solver (would have to check whether the determinant < 0)
- a hangman game
- a free fall calculator (given an object that is dropped from a certain height,
calculate a table with its position as a function of time)
- a quiz program about some topic you like (could even use randrange in this one
to pick questions)
- a program which combines some of the programs above - e.g. allow the user to
play either number guessing or hangman.
- a hotel booking application which allows making reservations for one or
2-person rooms and applies a discount if the reservation is on a day between
monday and thursday. 

Yours,

Andrei

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


Re: [Tutor] Expression order problem

2005-05-26 Thread Andrei
William O'Higgins  utoronto.ca> writes:

> This is a problem if you are used to Perl, where the whole script is
> parsed first (Perl also auto-vivifies variables, but that's a different
> problem for a different day).  Here is a test script:

The Python compiler parses the whole script too, can't compile otherwise. Of
course a variable must exist if its value is requested. I don't know what
vivifying a variable means, but surely Perl doesn't pull a non-existing variable
out of its sleeves? 

> class test:
> variable = "is this a variable" + other_argument
> 
> if sys.argv[1:]:
> other_argument = sys.argv[2]
> instance = test()
> print instance.variable
> else:
> sys.exit()
> I am only beginning to get my head around OO programming, so please bear
> with me.  In Perl, I would define all of my subs (functions or classes)
> at the end of the program, because the Perl parser will read the whole
> program, and then execute it.  So I'm having trouble from the start

That's what Python does too. But the variable assignment above is not in a
function, so it's executed immediately like any other statement.

> because I can't do that - the interpreter whines about undefined calls
> when things are defined further down the page.

It whines if they're used before they're defined. It's perfectly fine to have
them, undefined and all, as long as they aren't used.

> In my example though - I
> want to use variables from one code block in another, but whichever one
> is first, something is undefined.  I'm not necessarily looking for a
> fix, but pointers as to technique to avoid this would be appreciated.
> Thanks.

I can think of several possibilities:

1. assign a value to your variable before using it in the class definition. You
can do this by putting the assignment code above the class definition or putting
the assignment code in a separate module and importing it at the top of the
module which defines the class.

2. assign the attribute to the class only once its value is known:

>>> class tst:
... var = None
...
>>> myvar = 5
>>> tst.var = myvar
>>> inst = tst()
>>> inst.var
5

3. Make it an attribute of the instance rather than of the class:

>>> class tst2:
... def __init__(self):
... self.var = newvar
... print 'tst2.__init__ executed'
...
>>> tst2()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in __init__
NameError: global name 'newvar' is not defined
>>> newvar = 57
>>> tst2().var
tst2.__init__ executed
57

It would be better to pass the extra argument as function parameter to __init__,
but anyway.

4. Generate the class after the value of the variable is known:

>>> def generateclass():
... class test4:
... var = newervar
... return test4
...
>>> test = generateclass()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in generateclass
  File "", line 3, in test4
NameError: name 'newervar' is not defined
>>> newervar = 100
>>> test = generateclass()
>>> instance = test()
>>> instance.var
100

5. Use a class method instead of an attribute:

>>> class test5:
... @classmethod
... def var(cls):
... return dummy
...
>>> test5.var()
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 4, in var
NameError: global name 'dummy' is not defined
>>> dummy = 234
>>> test5.var()
234
>>> test5().var()
234

Which soultion is right, depends on your needs. I'm tempted to say (3) is the
best one, unless you really need that to be a class attribute. 

Tip: http://zephyrfalcon.org/labs/python_pitfalls.html

Yours,

Andrei


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


Re: [Tutor] python problem

2005-05-26 Thread Andrei
Feziwe Mpondo  sanbi.ac.za> writes:

> i'm trying to write a code that handle errors help

I think the indentation was screwed up.

> while menu_choice != 5:
> menu_choice = input("Type in a number (1-5):")

I'd avoid using input. Use raw_input instead.

> break

break stops a loop. So you display the menu once and stop immediately after the
user has selected an action. That can't be right.

> except(TypeError,NameError):

Exceptions are caught in a try except block, where the code that might
malfunction comes after try, and the code to handle the malfunctioning comes
after except. It therefore looks something like this:

  userinput = raw_input('Choice: ')
  try: # userinput may or may not be valid
  choice = int(userinput) # might fail if userinput is random text
  except (ValueError): # what to do if couldn't convert to integer
  print 'Not a number'
  choice = 5

Yours,

Andrei


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


Re: [Tutor] Planning a program with algorithm?

2005-05-30 Thread Andrei
. ,  hotmail.com> writes:

> But, I don't know how to plan a prog. with algorithm.

For small programs there's little value in planning - in fact, you'll probably
end up wasting time. As far as individual algorithms go, it's usually best to go
with whatever seems the easiest to understand and only do more advanced things
once you know that you need more speed or something like that.

> If algorithm of a part of a prog. is like..

That's a pseudocode implementation of an algorithm. You can describe an
algorithm in human language, in pseudocode or in a programming language.

> 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

That's actually *longer* than just writing the algorithm in Python directly,
which is why we say that Python is executable pseudocode :). Pseudo-code design
has IMO little value in Python and should stop at a higher level if it's used at
all. In this example I'd have said this before going to Python code:

  randomize letters in word

By going into too much detail, you've actually overlooked the fact that you're
recreating functionality from the Python standard library: random.shuffle.

> 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.")
>
--
> 

The pseudocode could be something like this:

  list all games
  show nr. of games
  get the name of a new game
  add the new game
  list all games
  exit

If you go into more detail, you'll end up writing a long version of the Python
code, which kind of defeats the purpose of pseudocode.

> Any useful advice for algorithm would be appreciated.

It's more important (at least for larger progams) to think about good design in
terms of modules, classes and functions than in terms of individual lines of
code. Always stop designing when designing becomes as low-level as just writing
the code.

Yours,

Andrei

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


Re: [Tutor] Planning a program with algorithm?

2005-05-30 Thread Andrei
> I'm learning python by reading 'Python Programming for the Absolute  
> Beginner' by Michael Dawson. 
> In the book it says it's recommended to plan a prog.  
> with pseudocode. 
>  
> Can i just ignore it? 
 
I don't think it's a bad technique, but there's different ways of writing 
pseudocode. The benefit of pseudocode is that you can write and inspect an 
algorithm quickly (quicker than in the programming language). Having 1 line of 
code for 1 line of pseudocode is in that regard a pointless use of pseudocode. 
 
Code:pseudocode ratios of 3:1, 5:1 or so are more reasonable in my opinion.  
By the way, this is roughly equivalent to the ratio of code required to do 
something in a lower-level language compared to doing the same thing in 
Python, which is why Python is comparable to pseudocode from the POV of 
low-level languages. 
 
One approach you could consider is to write pseudocode, turn it into comments 
and write the real code in between those. That way you get the benefits of 
pseudocode (being able to spot algorithm errors at a higher level) as well as 
properly commented code. Difficult portions then automatically get more 
comments, while easier portions get fewer comments - just as it should be. 
 
Yours, 
 
Andrei 
 

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


Re: [Tutor] Planning a program with algorithm?

2005-05-30 Thread Andrei
. ,  hotmail.com> writes:  
  
> And I'm doing chapter4. In the book it says it's recommended to plan a prog.  
>  
> with pseudocode.  
>   
> Can i just ignore it?  
  
Let me expand a bit on my previous post. You can use pseudocode iteratively,  
starting at a very high level and dropping lower until you start recognizing 
your programming language. Let's go back to your shuffling example and assume 
that code is part of a weak password generation tool. You could start with 
this (either in your editor, or in your mind):  
  
  get source of letters  
  process letters to generate password  
  show password  
  
Then you can start expanding. What is that processing? Could be this:  
  
  ask user for the desired password length  
  randomize source of letters   
  return piece of desired length  
  
At this point you probably already recognize Python code directly in there: a  
raw_input with validity checking (password can't be longer than the source), a  
random.shuffle and a list slice combined with a join(). There's no point in  
going even deeper, because you'd end up writing this:  
  
  while desired length larger than source or smaller than 1  
get desired length  
  convert source to list  
  shuffle source  
  take slice of desired length 
  return joined slice 
 
That's just a clumsy way of writing Python and therefore a waste of time. If 
on the other hand you were programming in ObjectPascal, C++ or something 
similar, this code would still not be quite high level, because shuffling the 
source, taking a slice and such are not built into those languages. In fact, 
in those languages you'd most likely choose a different approach at this 
level. 
 
Yours, 
 
Andrei 

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


Re: [Tutor] Planning a program with algorithm?

2005-05-31 Thread Andrei
Danny Yoo  hkn.eecs.berkeley.edu> writes:
> Some design advocates say that program design should be a part of every
> program.  At least, at minimum, we may want to think about:
>
>1.  What is the program supposed to do?  What's the input, and what's
>the output?
> 
>2.  What would a typical program run look like?
> 
>3.  What can we test it with to know that the program's doing the right
>thing?

It's hard to disagree with that :). 
My only gripe with such a generous definition is that it's pretty much
impossible to make a program without 'designing' it, because you'd end up with a
bunch of random statements. I find 'design' useful only if it means that some
effort has gone into making sure the application is well structured, easy to
maintain, easy to extend/modify (especially in the directions which could be
foreseen beforehand). Going from design-in-head straight to production code
doesn't (at least for me) lead to the best of results in those respects, even
though the code may work.

Yours,

Andrei

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


Re: [Tutor] samples

2005-06-23 Thread Andrei
D. Hartley  gmail.com> writes:

> code, but it's made up of 46 different .py files, none of which seem
> to be the "main" game (lots of little modules, like an input box, a
> high score list, etc).  It's a lot harder for someone new to
> programming to read. 

Identify the main file (the one that you launch) and go from there. A search for
'main' might turn up something. Having all code in one big file makes it more
difficult to read for advanced users, but also for beginners. Make sure you use
a good editor with code outline support (outline of classes/methods), it makes
it easier to explore the code.

> Also, the reason that I would like to see several examples is that I
> would like to see how different people approach things like keeping
> track of the columns' being filled or not, how they approach timing
> questions, whether or not they give hints, that kind of thing.  I did
> game.  I have donwloaded tetris clones as well, and have made one
> myself (getting toward the falling objects idea, anyway), but they
> havent been on a static board which is filled at all times with
> objects. Nor have I ever, actually, done anything with mouse clicks
> (!!).

Except for tetris, you could also look at othello/reversi, five in a row,
checkers and chess. They deal with sequences of pieces, clicking on pieces to
move them and (depending on the implementation and target audience) hints. It
might be even more instructive to look at differences between the games than to
look at differences within a game.

> at my disposal, and what's more, I want to figure it out on my own.

I'd say you shouldn't be shy about borrowing ideas (and even code, if the
licence allows it) from other people. Usually the best way to learn is not by
starting with the development of the wheel.

> Does anyone have any little "gamelets" like these, or know of

I remember not too long ago there was a discussion on the pygame list about
developing a partygame-like system, with a framework capable of loading all
kinds of simple minigames. I don't know how far it is by now, but if you look in
the pygame mailing list archives you should be able to find it.

Yours,

Andrei


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


Re: [Tutor] My first recursive function...

2005-07-28 Thread Andrei
Liam Clarke  gmail.com> writes:

> Are there any other pitfalls with recursion I need to watch for? 

Not just infinite recursion, but recursion that exceeds the maximum recursion
depth (1000 on my system). You can add a counter parameter to your recursive
function and stop recursing if the function finds it has called itself too many
times - helps against infinite recursion too.

>>> def a(i):
... i += 1
... if i < 500:
... a(i)
>>> a(0)

If you try the function above without the if condition, it will generate a
RuntimeError.  

Yours,

Andrei

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


Re: [Tutor] Custom metaclass?

2007-04-19 Thread Andrei
Michael Hannon  physics.ucdavis.edu> writes:

> The approach, in essence, is a fairly standard one: redefine the 
> __setattr__ method to add some logic to enforce whatever restrictions 
> you choose, but the details are a bit convoluted.  Copyright law 
> probably prohibits me from posting the entire recipe, but here's the 


Well, here's a dummy that simply ignores requests to add attributes, instead
printing a message about the attempt to the console, so we have a concrete
example to look at:

def no_new_attributes(*args, **kwargs):
print 'called ', args, kwargs
return no_new_attributes

class NoNewAttrs(object):
__setattr__ = no_new_attributes(object.__setattr__)
class __metaclass__(type):
__setattr__ = no_new_attributes(type.__setattr__)

nna = NoNewAttrs()
#NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
try:
print 'object nna.x =' + str(nna.x)
except:
print 'object nna.x doesn\'t exist'

NoNewAttrs.x = 5
try:
print 'class nna.x =', nna.x
except:
print 'class nna.x doesn\'t exist'

> Finally, my question: can somebody enlighten me as to how and why the 
> "custom metaclass",
> 
>  class __metaclass__(type):
> 
> does something useful?

A metaclass is to a class like a class is to an object. The way a class
customizes the behavior of an object, a metaclass customizes the behavior of a
class. It's all a bit mind-bending and I don't think I'm an expert on the
subject, but let's see how far we get.

Try running the example above with the  __metaclass__ code and without: you'll
see that if you leave it out, you can still add attributes to the class itself
(even though not to the object), so your console will say:

  object nna.x doesn't exist
  class nna.x = 5

If however you put the metaclass in, you'll get:

  object nna.x doesn't exist
  called  (, 'x', 5) {}
  class nna.x = class nna.x doesn't exist

Without the metaclass code, it would be trivial to work around the __setattr__
limitation. Just try uncommenting the line "NoNewAttrs.__setattr__ =
object.__setattr__". If you disabled the metaclass, you'll see that nna.x will
be set. If the metaclass is enabled, it will not be set.

This being Python, you can still work around all this metaclass safety by adding
using this code:

NoNewAttrs.__metaclass__.__setattr__ = type.__setattr__
NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
print 'After reset: nna.x =', nna.x

Run this and you'll see it will have restored the attribute-setting
functionality even if it's theoretically blocked. I'm not sure there is a way to
absolutely completely stop users from adding attributes.


Yours,

Andrei

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


Re: [Tutor] Calculator research

2007-06-02 Thread Andrei
Hi Adam,

> Ok, this is my research for a better calculator.  I want to make a
> calculator that is much less lame than the one that comes standard
> with windows.  If anyone has any ideas for how to start or some things

A very simple option would be to just call eval() - you get the full 
power of Python at basically no cost. The downside is that you get the 
full power of Python, meaning your calculator could be used for 
'dangerous' things. Depending on your target audience, that may or may 
not be an issue.

> Also, I'd like to know how to make my program have visual qualities,
> like the standard calculator.  I assume that this is either impossible
> or very advanced/difficult, considering I have not previously heard

You mean a GUI, right? It's more difficult than plain CLI, but it's not 
really difficult. Google for wxPython and wxGlade - you can design your 
interface in a point-and-click manner. You will need to learn a bit 
about wxPython in the process, but don't have to become an expert.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Searching Sorted Lists

2005-08-20 Thread Andrei
[EMAIL PROTECTED] wrote:
> Hi, Can someone tell me if there is a bulit in Binary search function for
> python lists ?
> 
> I am currently building lists and sorting them with a comparison function.
> The only list search function I know is List.Index(X), which is pretty
> inefficient I reckon, especially hen the lists are likely to contain 100's
> or 100's of members.

Hundreds or thousands of entries are pretty much nothing in computer 
terms. Unless you have measured that it's a bottleneck in your 
application, I wouldn't bother finding an alternative to index().

 > Is there a search function that uses a compariosn function / binary 
chop ?
 > or will I have to implement my own ?

It's quite easy to code it yourself if necessary. The Wikipedia has a 
nice article on it, including sample code which looks very much like 
Python: http://en.wikipedia.org/wiki/Binary_search

Yours,

Andrei

=
Mail address in header catches spam. Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] Strange "snippets" in Learning Python, 2nd ed.

2005-08-20 Thread Andrei
Dick Moores wrote:
> I have the first printing. The snippets are on pp. 159 and 160, and are 
> there to illustrate the loop "else" clause.

> while x: # exit when x empty
>  if match(x[0]):
>  print 'Ni'
>  break# exit, go around else
>  x = x[1:]

> "match()" seems to come out of the blue, and also "Ni". Or have I 
> misunderstood something?

I can't tell you where match() comes from - perhaps it's just a dummy 
name of a function the purpose of which is left to the imagination of 
the user. I don't think it's important actually, the point would be that 
it returns True if some criterium is met and False otherwise.

"Ni" comes from a Monty Python movie. The name of the Python language 
comes from Monty Python, hence the reference to the movie. For more 
info, google for "knights who say ni". It's quite traditional in the 
Python world to include Monty Python references in code or even program 
names. References to idle, eric, spam, dead parrots, shrubberies, 
cleese, grails, the Spanish inquisition, swallows and just about 
anything else that seems weird can usually be tracked down to that same 
source.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] Python DB

2005-09-22 Thread Andrei
> The problem (I have) with SQL-type DB is that I cannot be sure ahead of
> time of the exact data structure. The DB will be about patients, who
> have diseases, and also have treatments.Clearly, I can't specify now
> the exact structure of the table. The advantage of SQL is that you can
> (in general) do things like constrain types for fields, and give
> enumerated options, which makes the data more consistent.

My experience:
- keeping in-memory: fast and easy as long as the amounts of data are 
*very* limited.
- kirby: I looked at it almost two years ago and it's nice, easy to use, 
but needs speedups for large amounts of data. At the time I tweaked some 
of the code and got very nice improvements (some of them are now in 
there I think).
- bsddb: very comfortable (just treat it like a dictionary), fast 
lookup, but searching in the values is slow. If you have thousands of 
records, you'll most likely need to employ some tricks to get fast 
responses when searching.
- sql (my experience is with SQLite): harder to work with (had some 
issues getting SQLObject to work with it, so I did it the very hard way 
by writing SQL statements), but insanely fast searches.

> The thing I liked about KirbyBase was that it used text files. This is a
> real advantage, as it means that I can access the data from other
> application easily, and also makes it easier to back-up (can just copy a
> few files). The same would seem to be true of the XML-based options. The

bsddb and sqlite also have single-file databases.

> The final thing is that I needs to have a simple GUI frontend. The nice
> thing about ZODB is that I could just map the eventhandlers to functions
> on objects..

sqlite has some viewers available (in my experience not quite reliable, 
but YMMV). bsddb can be inspected and manipulated easily in an 
interactive python session.

> If people have more comments in the light of the bigger spec. above, I'd
> still love to hear them...

I'd give bsddb a try if the application mainly involves looking up 
treatments/illnesses for a given patient (with the patient being the key 
in the database) or if the number of patients is quite low (hundreds). 
If however an important use is to do other types of searches too (e.g. 
find all patients with an age above X who use a drug Y) and you have a 
large database, some SQL DB would be better.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] Remaking Vim in Python (was Python Editors)

2005-09-23 Thread Andrei
Ed Singleton wrote:
> My instinct was to try and write a small program similar to vim, but
> in Python.  The very basics should be quite easy.  If I start a system
> that is very easily expandable then as and when I need further
> functionality I can add it in.

I'd say it's better to either adapt an existing editor or write a new 
editor from scratch, but using an existing editor component. Under 
wxPython you could use the Scintilla control. This approach is much less 
time consuming than writing your own text editor control which will most 
likely end up either being less powerful than what you'd get for free if 
building on existing functionality. Text editors are more fiddly than 
you might expect, because they offer a lot of functionality people don't 
even notice is there until they come across one which lacks it. E.g. I 
avoid IDLE and Leo simply because I don't like their editing components.

You might even be interested in customizing Vim itself. I don't know 
what your goals are, but you could e.g. look at Cream 
(http://cream.sf.net) for a more user-friendly Vim.

> I know it would be ambitious to try and do this, but is it stupidly ambitious?

It's not stupidly ambitious, but odds are (simply based on the amount of 
editors out there and the features they have) that you'll end up with 
not much more than a slightly fancy notepad. This can of course still be 
a useful learning exercise, but if you want to have an editor in which 
to be productive, it's probably better to invest some time in learning 
to use one of the existing options. Whether it's Spe, Scite, Komodo, 
Vim, Emacs or whatever else suits you, is not very relevant.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] Error checking - very basic question

2005-09-25 Thread Andrei
Garry Rowberry wrote:
> def ask_dau_version():
> """Determine the product issue of the DAU."""
> dau_version = None
> while dau_version not in ("2.8", "2.1"):
> dau_version = raw_input("\n\tIs the DAU a version 2.1 or 2.8, please
> enter only 2.1 or 2.8 ")
> print"\n\t\aError! - please enter only 2.1 or 2.8."
> else:
> print""
> return dau_version
> 
> I can see why it isn't working, the error message is in the wrong place, but
> I can't see a simple way around it (wood for the trees)

How about using a "while True" loop that you break out of only when a 
correct value has been identified:

 while True:
 dau_version = raw_input('blabla')
 if dau_version in ("2.8", "2.1"):
 break
 else:
 print "Error"


-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info (decode with rot13):
[EMAIL PROTECTED] Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V 
ernq gur yvfg, fb gurer'f ab arrq gb PP.

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


Re: [Tutor] creating strings

2005-09-25 Thread Andrei
[EMAIL PROTECTED] wrote:
> 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

There's no point in importing 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()

You could chain a bunch of if-statements.
   if g is between X1 and Y1: result is Z1
   else if g is between X2 and Y2: result is Z2
   else if ...

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Exception handling - syntaxerror?!

2005-09-25 Thread Andrei
> Think the mail system screwed up the formatting! But am fairly sure
> that I have indented it correctly in the console. Try and Except are
> in the column. Any other hints?

Yes :). Compare:

 >>> try:
...   os.system('cls')
... except:
...   print "Foo"
...
Foo
 >>> print "Bar"
Bar

With (what you had):

 >>> try:
...   os.system('cls')
... except:
...   print "Foo"
... print "Bar"
   File "", line 5
 print "Bar"
 ^
SyntaxError: invalid syntax

Subtle, but important difference. You should terminate the try-except 
block (confirm with extra ENTER) before doing more stuff.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Exception handling - syntaxerror?!

2005-09-26 Thread Andrei
Krishna wrote:
> When I have this piece of code in a function, it works fine. So is
> this some limitation of directly working out off the console?

It is indeed valid Python (you don't have to have empty lines after 
try-except in a real Python program).

> Seems the console supports complete code constructs only  I.e., I can
> have one complete try...except block, a if block etc., but not a bunch
> of constructs? Is my assumption correct?

That seems to cover it, one compound statement per >>>. (You can chain 
several statements in one line by using ';', e.g. ">>> print 6; print 5" 
will work just fine.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Tutor Digest, Vol 19, Issue 82

2005-09-27 Thread Andrei
sanjay sinha wrote:
> I am sanju sinha just started python from the last one month . I have 
> gone through all basic programming of with python and also use Tkinter 
> for window . I want to know from you all experience person in python 
> that weather i move to wx or tkinter is sufficient for GUI programming.

Tkinter is usable for GUI development and it's the default GUI toolkit 
in Python. wx is also usable. wx offers IMO better tools (visual GUI 
builders) and better looks, but your users will have to download both Py 
and wxPy to use it - unless you use Py2exe. Whether you should switch 
depends on whether you like Tkinter or not. I for one really dislike it 
and avoid programs written in it, but others seem to prefer Tkinter - 
it's very much a matter of taste.

In the future please don't include a full tutor digest in your message 
and mind the warning at the top of the digest:

'When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."'

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Installing ActiveState Python vs2003

2005-09-29 Thread Andrei
Mohammad Moghimi  gmail.com> writes:

> When I tried  to install activestate python(.net implementation of python) to
my visual studio 2003.
> It gives me this error message:
>
> The Visual Python Installer found an installation of Python 2.4, 
> but it also requires the win32 extensions.
>
> what's  the problem? -- Mohammaddo you Python?!!

It seems you need to install win32all
(http://starship.python.net/crew/mhammond/win32/). The ActiveState Python distro
(ActivePython) includes this as well. Note that ActivePython is not the same
thing as ActiveState Visual Python, which seems to be what you got - one is a
Python distro, the other is an extension of the VisualStudio IDE. Neither is a
.Net implementation of Python, IronPython is (http://www.ironpython.com/).

Yours,

Andrei

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


Re: [Tutor] Global var problem

2005-10-28 Thread Andrei
Hi Nick,

> messing about with classes I've come across something basic that I don't 
> understand.

Your issue is not so much with classes as it is with namespaces. You'll 
hit the exact same problem with simple functions.

> Take this class
> 
> class T:
> def p(self):
> print x

In this case, the Python reference states that if a name (x) is not 
found in a block (i.e. inside the p method), it will look in its 
surrounding scope for it. That would be the global namespace. Given the 
fact that you defined x as a global variable, it finds it there and it 
works as expected.

> Now this
> class T:
> def p(self):
> x += 1
> print x
> This outputs
> UnboundLocalError: local variable 'x' referenced before assignment

Here is what the Python docs have to say about assignment:

   If the target is an identifier (name):
 If the name does not occur in a global statement in the current code
 block: the name is bound to the object in the current local
 namespace.

In other words, when trying to assign a new value to x, it:
1. looks if x was defined as global *inside the current function/class*
2. sees that it was not defined as global -> therefore it must be local
3. tries to get the value of that local x
4. finds there is no local x -> raises exception

> So I tried this
> 
> class T:
> def p(self):
> x += 1
> print x
> 
> if __name__ == '__main__':
> global x
> x = 1
> t = T()
> t.p()
> but that gives me the same UnboundLocalError exception.

This second attempt is almost but not quite right: the global statement 
is in the wrong place. x is by definition global if defined outside a 
class or function, so adding "global" in front of it won't make a 
difference. The point is that if you try to assign a value to a global 
variable inside a function or class definition, you must tell Python *in 
that block* that you want to assign to a global variable, not a local one.

 >>> def p():
... global x
... x += 1
 >>> x = 5
 >>> p()
 >>> x
6

Similar problems can occur when defining a function inside another function:

 >>> def a():
... aa = 2
... def b():
... print aa # aa in surrounding namespace, not local to b()
... b()
 >>> a()
2
 >>> def a():
... aa = 2
... def b():
... aa += 1 # in surrounding namespace, not local to b()
... print aa
... b()
 >>> a()
UnboundLocalError: local variable 'aa' referenced before assignment


> No doubt the answer is staring me in the face ... but I still can't see it.

I would recommend against using global variables this way (modifying 
them inside functions). It's better to use method parameters for input 
and the return statement to output any necessary modifications, e.g.:

def p(inp):
 output = inp + 1
 print output
 return output

if __name__ == '__main__':
 x = 5
 x = p(x)

It would be even better with a decent function name of course :). More 
info available in paragraph 4.1 of the Python reference manual.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Recursion and List Comprehensions

2005-10-28 Thread Andrei
Carroll, Barry wrote:
> Greetings:
> I'm trying to improve my programming and Python skills.  To that end I 
> have implemented a word jumble program as a recursive function:  given a 
> string of arbitrary length, return a list of all permutations of the 
> string each character exactly once.  In other words:
> 
> permute('t') = ['t'],
> permute('te') = ['te', 'et'],
> permute('tes') = ['tes', 'tse', 'ets', 'est', 'ste', 'set'],
> etc. 

> I'm told that I can collapse the logic further by using a list 
> comprehension, something like:
>> >>>def permute3 (word):
>> >>>retList=[]
>> >>>if len(word) == 1:
>> >>># There is only one possible permutation
>> >>>retList.append(word)
>> >>>else:
>> >>># Return a list of all permutations using all characters
>> >>>retlist = [a list comprehension that calls permute3]
>> >>>return retList
> Unfortunately, I don't understand how list comprehensions work and how 
> to implement them.  Can someone point me in the right direction, please.

There's nothing magic about writing a list comprehension - they're just 
an inside-out way of writing a for-loop :).

   newlist = []
   for item in mylist:
   newlist.append(item * 2)

becomes (imagine this as an animation with bits of code from above 
floating down to fill in the blanks :)):

   newlist = [   ]
   newlist = [ for item in mylist]
   newlist = [item * 2 for item in mylist]


In your case, you could start with your permute2 implementation and turn 
it inside out to get a list comprehension:

   for item in permuteList:
   retList.append(word[pos] + item)

would become according to the example above:

   retList = [word[pos] + item for item in permuteList]

Testing this shows that it tends to cut off a bunch of combinations, 
because retList is overwritten in every iteration of "for pos in range". 
Let's fix that by extending the list instead:

   retList.extend([word[pos] + item for item in permuteList])

That works. Now we replace 'permuteList' with its definition a few lines 
above:

   retList.extend([word[pos] + item
 for item in permute2(word[0:pos]+word[pos+1:len(word)])])

Getting ugly now. Let's see what's missing: word is an argument, item 
comes from the "for item in ...", but pos still needs to be defined. We 
get that by wrapping the "for pos in range" loop around this list 
comprehension:

   for pos in range(len(word)):
   dosomething(pos)

becomes:

   [dosomething(pos) for pos in range(len(word))]

Where dosomething(pos) is our earlier list comprehension. Let's fill it in:

   [ retList.extend(
   [ word[pos] + item
 for item in permute2(word[0:pos]+word[pos+1:len(word)]) ] )
 for pos in range(len(word))]

The net result:

   def permute3(word):
   retList=[]
   if len(word) == 1:
   # There is only one possible permutation
   retList.append(word)
   else:
   # Return a list of all permutations using all characters
   [ retList.extend(
 [ word[pos] + item
 for item in permute3(word[0:pos]+word[pos+1:len(word)]) ] )
 for pos in range(len(word))]
   return retList

4 lines of perfectly readable code have become 4 lines of perfectly 
unreadable list comprehension. Any reader interested in understanding 
this will have to perform the exact opposite set of operations to go 
back to the original code.



-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Circular approach to a dictionary structure

2005-10-28 Thread Andrei
Tim Johnson wrote:
> Hello:
> 
> # I have the following dictionary:
> next_phases = {"open":"review","review":"write","write":"open"}
> 
> # a 'phase is extracted by
> next_phase = next_phases[self.phase
> 
> Note that the value for each of the first keys is the key for
> the next item, and that the value for the last key is the *first* key.

I too would be tempted to use a list for this. Something along the lines of:

   phases = ['open', 'review', 'write']

   nextphase = phases[((1 + phases.index(phase)) % len(phases)]

This is not as friendly as the dictionary option, but I'd wrap that in a 
function call (or object interface). It has some advantages:
   - there's a single instance of every string
   - it's obvious that it's a sequence
   - it's one of the standard ways of doing circular structures
   - there's no chance of introducing a dead branch, breaking the circle
   - it's easier to add/remove things.
 E.g. if you'd add and an "approve" step between review and write,
 the list approach requires a single update, while the dictionary
 requires one new key-value pair and modifications in another two
 places in order to get it working correctly.

-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] Who called me?

2005-11-08 Thread Andrei
Bill Campbell wrote:
> Is there a way in python for a method to determine its parent?
 > In particular, I'm working with SimpleXMLRPCServer, and would
 > like to be able to find the client_address in the routine that
 > has been dispatched.  I know that client_address is an attribute
 > of the handler class instance, but don't know how to get to that.

I'm not sure what you mean by its parent (also never worked with 
SimpleXMLRPCServer). Something like this?

 >>> class A(object):
... pass
 >>> class B(object):
... pass
 >>> def func(self):
... print self.__class__
 >>> A.f = func
 >>> B.f = func
 >>> a, b = A(), B()
 >>> a.f(), b.f()



-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] First program -- would like comments and criticisms

2006-02-18 Thread Andrei
[EMAIL PROTECTED] wrote:
> Here is my first stab at putting together a working program. It is a 
> glossary that you can add words and definitions to, or look up words and 
> their definitions.  There are a couple of problems here and there, but 
> it basically does what I set out for it to do. All comments and 
> criticisms are welcome. I attached the data file that goes with the 
> script in case anybody wanted to actually run it, so they wouldn't have 
> to make their own dictionary file to access.

I haven't executed it, but it seems quite good, certainly for a first 
working program. For small programs there's no point in overengineering, 
but here are some simple improvements you could look into:

- place a "if __name__=="__main__":" condition at the bottom and put 
your program code in there (or better yet, extract it in a function and 
call that function after the if __name__ stuff). This way the module can 
also be imported.

- make the location of the dictionary a 'constant' (which in Python 
means a variable with all-uppercase name :)). Having magic strings in 
code is bad practice.

- the menu system could be redesigned to make it more 
maintenance-friendly. At this point if you want to add/modify a choice, 
you'd have to modify a procedure and the main code. You could instead 
make a dictionary mapping each possible choice (keys) to tuples 
containing a description and a function name. Loop over the keys and 
print them with the description. Once the user makes a choice, you could 
look up the function in the dictionary and execute it. This way adding 
new functionality items only means you need to add an entry to that one 
dictionary.

- you could replace the "while num != '3':" condition with a "while 
True:" - the loop is interrupted anyway if '3' is selected, because of 
the 'break'. This way you can also remove the initialization of num.

- you could extract the actual logic (the glossary) to a class with 
methods like "load", "save", "lookup" and separate it completely from 
all the user interaction. The glossary class shouldn't print/ask for 
user input. It's overkill for such a small program, but you could then 
theoretically reuse the glossary in a different application (e.g. put a 
webbased interface onto it, or subclass it and make a glossary which can 
also do multiple language translations, or use a different storage 
backend, etc.).



-- 
Yours,

Andrei

=
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

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


Re: [Tutor] i have a question

2006-03-12 Thread Andrei
Tom Bachik  gmail.com> writes:

> ok say u want python to ask the user to type a username then password for a
game account thats easy but how do u get the information they typed back to you?

Depends on the environment you're asking it in. If it's command-line, you're
probably using the raw_input function in order to get the name. This function
simply returns a string that you can use, so you could write something like:

  username = raw_input("Name: ")
  password = raw_input("Password: ")
  if CheckPassword(username, password):
  print "Hello %s" % username
  else:
  print "Incorrect name or password!"

Other environments (e.g. wxPython, PyGame or web interfaces) offer different
ways of achieving the same results, but I presume you're really new to Python
and not yet messing around with those.

Yours,

Andrei

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


Re: [Tutor] Some questions about my yen-USD.py

2006-09-07 Thread Andrei
;Amount: ').lower().strip()
  if useramount in 'qx':
  return useramount
  try:
   amount = float(useramount)
  except ValueError:
   continue # we want to skip the code below
  if amount <= 0:
  print "Amount must be more than 0."
  else:
  return amount

Using multiple returns in a single function is sometimes frowned upon; but then
again, so are break and continue :).

Yours,

Andrei



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


Re: [Tutor] python & mysql question

2006-09-07 Thread Andrei
Patricia  gmail.com> writes:

> I have to store and retrieve text files from a database table and 
> the size of each file is about 500k. Can someone give me an idea 
> on how to do this? 

You might want to have a look at this:

http://sourceforge.net/projects/mysql-python

Yours,

Andrei

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


Re: [Tutor] Some questions about my yen-USD.py

2006-09-07 Thread Andrei
Pawel Kraszewski  kraszewscy.net> writes:

> > > get me into trouble with the flakiness of float(n)? In testing I
> > > didn't find any problems, but ..
> >
> > Nah. Float accuracy is only a problem if you need around lots of
> > significant digits (16 or so).
> 
> I wouldn't bet. Such a simple thing as 0.1 can't be represented correctly on 
> Float... That's what 'decimal' is for.
> 
> See that:
> 
> >>> 0.1 + 0.1 + 0.1 - 0.3
> 5.5511151231257827e-17

For the intents and purposes of this script, this difference is of no
consequence (that value is close enough to zero):

>>> "%.2f" % (.1+.1+.1-.3)
'0.00'

Andrei


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


Re: [Tutor] Some questions about my yen-USD.py

2006-09-07 Thread Andrei
Dick Moores  rcblue.com> writes:

> So now that I know better, I'm trying to write the beginnings of a 
> general setPrecision() function using format strings. However, it 
> appears that a variable cannot be used instead of the ".2" in
> 
> "%.2f" % 2.234234

> How to do this?

You could use simple string concatenation:

>>> "%." + str(2) + 'f'
'%.2f'
>>> "%." + str(4) + 'f'
'%.4f'

Or use format strings to create other format strings, by escaping the '%' with
'%%'. E.g.:

>>> "%%.%df" % 2 # the '%%' will be changed to '%' in the result
'%.2f'
>>> "%%.%df" % 4
'%.4f'
>>> s1 = "%%.%df" % 2
>>> print s1, s1 % 3.41234
'%.2f', '3.41'
>>> s2 = "%%.%df" % 4
>>> print s2, s2 % 3.41234
'%.4f', '3.4123'
>>> ("%%.%df" % 2) % 3.23423 
'3.23'

Yours,

Andrei

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


Re: [Tutor] Some questions about my yen-USD.py

2006-09-08 Thread Andrei
Dick Moores  rcblue.com> writes:

> Version 3 is now at http://www.rcblue.com/Python/yen-USD-v3.txt . Am 
> I done? Or will a v4 be necessary/advisable?

The original program worked fine from the user's POV and the code had lots of
good features (functions instead of monolithic code, docstrings). IMO the most
important problem of the code was the "if again" thing in the loop, which, as
you point out, is not a problem for the user (who won't hit the recursion
limit), but it is a very big conceptual issue that's prone to bite you every
time you write a function.

Beyond that, any program above 10 lines (and even many smaller ones) offers
infinite opportunities at fiddling - at some point opinions will start to differ
about the 'perfect' approach and further micro-optimizations. It's best to let
programs that are "good enough" alone and focus on new things that will give new
learning opportunities: you could write something different, or choose to extend
the program in radical new ways (e.g. automatic downloading of conversion rates,
a GUI/web interface).

> >4) Function names are important and should be chosen in such a way 
> >that they are
> >not confusing. Most of them are OK, but commas() is non-descripting
> 
> I've renamed commas() to numberCommas(). Is that descriptive enough? 
> I'm reluctant to go with even a longer name. I'll be using it a lot elsewhere.

A guideline for function names is that they should contain a (well chosen) verb
and an object. As always it ends up being a matter of personal taste. I for
example might call that function insertSeparators or formatNumber, but other
people might prefer longer names like insertSeparatorsInNumber or
prettyPrintNumber or something completely different.

Yours,

Andrei

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


Re: [Tutor] python for web developing

2006-09-14 Thread Andrei
federico ramirez wrote:
> Hello! I have heard that python is very good for web development, but 
> you need frameworks, like django or turbogears.

There are also more lightweight frameworks, like web.py (http://webpy.org).

> Im a php programmer, and i want to make another dinamic site with sql, 
> in python, but i need sql object or other sql...
> And i cant get a host with it, a free host just to test it.

If you want to test, I think your own PC can do the job just fine. I 
don't know of any free generic Python hosts. Webfaction (run by the 
author of CherryPy, which is part of TurboGears) seems to have decent 
support for all kinds of Python things, but it's paid - if they allow a 
1-month account, you could try it out for very little money over there.

Yours,

Andrei

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


Re: [Tutor] Limitation of range() function in Walking problem

2006-09-16 Thread Andrei
Srinivas Iyyer wrote:

> Coordinates of a variable G1:
> a1 : 3-8
> b2 : 10-25
> c3 : 7-18
> d4 : 10-13
> Now, I have variables G1Gn.  Each variable may
> have individual pieces a1(n),b2(n),c3(n).z(n).
> 
> my kind of solution, which is very crappy (i assume):
> 
> Sort the list:
> [3,8] [3,8]
> [10,25] sort  [7,18]
> [7,18] >  [10,13]
> [10,13]   [10,25]
> 

> The question to the forum is, I am using range()
> function to solve this. Since the numbers in the
> example are small, it worked. in the real world
> example , it did not work, because computer slowed
> down and eventually crashed.  The range(81393417) is
> really big. 

I'm not sure I fully understand the question - do you NEED to loop over 
the possible locations, or do you only need to determine the extremes of 
the 4 ranges? If you need a loop, xrange is probably the way to go, as 
Luke mentions.
If you just need the extremes, you don't need a range(), because it can 
be done using zip:

 >>> a,b,c,d = [3,8], [10,25], [7,18], [10,13]
 >>> candidates = zip(a,b,c,d) # 'merges' the elements of the lists
 >>> print candidates # first item contains potential minimums
[(3, 10, 7, 10), (8, 25, 18, 13)] # second item potential maxes
 >>> maxrange = [ min(candidates[0]), max(candidates[1]) ]
 >>> print maxrange
[3, 25]

Now if you have a non-continuous range, this will still give you the 
overlapping area. E.g. if you'd drop c3, it would not affect the result. 
If that's a problem, you could loop over the lists directly:

def getMaxRange(locs):
 locs.sort() # sorts 'naturally'
 #print "sorted locs:", locs
 maxrange = locs[0][:] # guaranteed to start with min
 for loc in locs[1:]: # loop over rest of locs
 if loc[0] <= maxrange[1]:
 maxrange[1] = loc[1]
 else:
 print "   discontinuity found for", loc
 return None
 return maxrange

It's similar to your solution, but without the range - they're superfluous.

Yours,

Andrei

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


Re: [Tutor] Lists in lists

2006-09-16 Thread Andrei
Morten Juhl Johansen wrote:
> # Newbie warning
> I am making a timeline program. It is fairly simple.
> I base it on appending lists to a list.
> Ex.
> [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]]
> 
> This seemed like a brilliant idea when I did it. It is easy to sort.
> Now, if I want to OUTPUT it, how do I indicate that I want to extract
> first entry in a list in a list? How do I print the separate entries?

Just append the position indicators, e.g. "print MyList[0][1]" will take 
item #0 in MyList and request its item #1. It's equivalent to saying

   MySubList = MyList[0]
   print MySubList[1]

In an interactive session:

 >>> li = [[1,2], [3,4]]
 >>> li[0]
[1, 2]
 >>> li[0][0]
1
 >>> li[0][1]
2
 >>> li[1][1]
4


Yours,

Andrei

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


Re: [Tutor] Question about startswith() and endswith() in 2.5

2006-09-25 Thread Andrei
Dick Moores  rcblue.com> writes:

> endswith( suffix[, start[, end]])
> Return True if the string ends with the specified suffix, otherwise 
> return False. suffix can also be a tuple of suffixes to look for. 

>  >>> s.startswith("er","q","ty")
> 
> Traceback (most recent call last):
>File "", line 1, in 
>  s.startswith("er","q","ty")
> TypeError: slice indices must be integers or None or have an __index__ method

> def is_image_file (filename):
>  return filename.endswith(('.gif', '.jpg', '.tiff'))

> function is_image_file() will return filenames ending in '.gif', but 
> what do '.jpg' (as start) and '.tiff' (as end) do? What kind of 
> data(?) would this function be applied to? A Python list of filenames?

Note that endswith(('.gif', '.jpg', '.tiff')) is a function call with ONE
parameter: the tuple ('.gif', '.jpg', '.tiff') - hence the double parentheses.
This parameter is the suffix. The optional start and end parameters are not
specified. You could read it like "if the filename ends with .gif or .jpg or
.tiff". In older Python versions, you could implement the same functionality as:

if s.endswith('.gif') or s.endswith('.jpg') or s.endswith('.tiff')

This is in contrast with the example you give above, where
startswith("er","q","ty") is a function call with three separate parameters, all
of them strings. Since start ("q") and end ("ty") must be integers, this call
crashes.

Yours,

Andrei

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


Re: [Tutor] Efficient programming questions. Tuples vs Li sts; Custom Objects vs Lists.

2006-09-25 Thread Andrei
 why is 
> it not possible to have a program that reads in the whole python script, 
> translates it to C and compiles it? Is it simply that the C functions are 

Because the script as you see it might not be what is executed. Python programs
can be modified dynamically at runtime, e.g. I might add a method to an object
based on user input, or add complete new classes, etc. Or I might call a method
on a certain object, without knowing what that object is - it needs to examine
the object at runtime to determine if the method is available. The potential
compiler would have to handle all of these cases, meaning you'd end up with...
well, CPython. Typical compiler efforts in the past have limited the flexibility
of the language. 

Yours,

Andrei


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


Re: [Tutor] e-learning Python

2006-09-26 Thread Andrei
PA  sapo.pt> writes:

> Is there any site offering e-learning about Python?
> 
> If not, the PSF should do it!

If you mean if there are any online tutorials: lots of them. Here's a very large
list: http://www.awaretek.com/tutorials.html

Yours,

Andrei

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


Re: [Tutor] e-learning Python

2006-09-28 Thread Andrei
Paulino  sapo.pt> writes:

> Yes I'm looking for something more interactive, but didn't find
> anything yet.
> Lerning by one's self has it's limitations...

I don't know of any such course. Probably the closest thing to it is picking a
tutorial, work through it on your own and ask on this list when you get
stuck/confused - there are many fine tutorials for different knowledge levels,
so self-study should get you quite far. People also regularly post small scripts
they do while learning and ask for feedback, which is a lot like getting your
homework reviewed by a teacher in a more classical approach.

Yours,

Andrei

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


Re: [Tutor] Workaround for limitation in xrange()?

2006-10-10 Thread Andrei
Dick Moores  rcblue.com> writes:

 
> I can think of 2 workarounds for this 2**31 limitation in xrange(). 
> Use a while loop instead. Or use 2 or more for loops, keeping the 
> number of cycles in each under 2**31.
> 
> Are there others?

Write your own iterator:

>>> def hugerange(minval, maxval):
... val = minval
... while val < maxval:
... yield val
... val += 1
...
>>> for i in hugerange(2**31, 2**31 + 2):
... print i
...
2147483648
2147483649

It might be slower than Python's xrange implementation (haven't tested), but it
will take anything you throw at it as long as Python itself can handle it.

Yours,

Andrei

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


Re: [Tutor] Evaluate my script?

2006-10-24 Thread Andrei
usable in other chemistry/physics-related applications if they were contained
as normal functions inside the module. The float() stuff will disappear if you
modify parseInput as described above.

The output() function seems a bit pointless in the current implementation - I'd
just use "print" directly in main.

Now onto the Python idiom I mentioned at the beginning: for reuse it's better to
not always run the main() function. If I import your module because I want to
reuse calcVol, I'd end up running the complete code. In order to avoid this,
write at the bottom of the module:

if __name__=='__main__':
main()

This way main is only called if the script is running on its own, not by being
imported in some other application.

Some generic remarks:
1. I can think of an potentially useful use case for specifying all 4 input
values with no unknowns: check whether the combination is valid while doing
homework, without getting the correct answer. This is a bit tricky because you
can't assume pV is *exactly* equal to nRT when floats are used, so you'd have to
build in a bit of tolerance.

2. Functions can be assigned as variables, like this:

  >>> def myfunc(a, b):
  ... print a + b
  ...
  >>> f = myfunc # note the absence of parentheses - myfunc is not called!
  >>> f(3, 4) # calls myfunc
  7

To make things even better, you can convert lists to function arguments like 
this:

  >>> args = [3,4]
  >>> f(*args) # the * 'unpacks' the list
  7

Using these two techniques makes it possible to get rid of "unknown_variable":
parseInput could return a function and a list of arguments to be supplied to it.
There is an argument to be made both in favor and against this approach, but
it's interesting anyway.

3. Mirror user input: the highly tolerant unit parsing is potentially dangerous.
Say I accidentally specify p=2atn. The program will calculate with 2 kPa, but I
wouldn't know that. If instead it displayed its interpretation of my input by
writing "p = 2 kPa" to the screen, I'd have a better chance of noticing.
Alternatively, you could provide a warning like "unknown pressure unit: atn.
Assuming kPa.".


That's a lot of comments for such a small program, so keep in mind you don't
have to do everything I (or others :)) write. Some of the advice is generic in
nature: e.g. you might not care about reuse in this particular case, but it's
still good to know what you should pay attention to in the cases where you DO 
care.

Yours,

Andrei

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


Re: [Tutor] OOP and Python.. a gentle remark

2006-10-25 Thread Andrei
Asrarahmed Kadri  googlemail.com> writes:

> the use of 'self' keyword really confuses me. 

I see how it can annoy you, but not how it can *confuse* you - if anything,
"self" removes any confusion about whether you're looking at a local variable or
an object property. By the way, the use of special identifiers is not uncommon
in dynamic languages. Ruby for example uses the prefixes @, @@ and $ to define
variable scope (which are not particularly self-explanatory - I think they're
class, instance and global vars) and keywords (private, protected, public) to
define method visibility. 

> and to make matter worse the variables can be accessed from outside teh 
> class. 
> Isnt it a violation of the OOP principle of ENCAPSULATION)

Python has conventions for this: prepend _ for protected and __ for private
(private names get mangled). In an interactive session:

  >>> class a(object):
  ... def _protected(s): # don't *have* to use "self" :)
  ... print s
  ... def __private(s):
  ... print "private"
  >>> A = a()
  >>> A._protected()
  <__main__.a object at 0x00AF2E10>
  >>> A.__private()
  Traceback (most recent call last):
File "", line 1, in ?
  AttributeError: 'a' object has no attribute '__private'

Lets's examine what's happened:

  >>> dir(A) 
  [, '_a__private', '_protected']

See, __private was mangled to _a__private. We can still access it of course:

  >>> A._a__private()
  private

Python approaches the programmer as a responsible person: if I see a method name
is mangled (or marked with _), I know I'm not supposed to use it - but can use
it if I really need to (and suffer the consequences if the next version of the
class breaks my code). 
Other languages choose the opposite approach: private is private, don't trust
the programmer, tough luck if you really really need access to that private.
Unfortunately you will invariably encounter cases when you need to access
privates and these are major PITA's. Usually you can get your hands on the
secret stuff, it's just very annoying and silly (e.g. by creating shadow classes
or other workarounds).

In the end it comes down to a choice between making some unavoidable cases very
cumbersome to deal with, or trusting the programmer to do the right thing -
thereby making it easier to stick his grubby little fingers in places where he
shouldn't. Some people prefer the former, some the latter.

Yours,

Andrei

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


Re: [Tutor] Of integers, relations and trees

2006-12-09 Thread Andrei
Tor Hildrum wrote:
> I have this problem which I thought would be trivial, but I can't
> seem to figure out a decent way to do it.
> 
> Say I have the following file:
> 10
> -100

> -108
> --1080

> 12

> 20
> 
> In lack of a better explanation, here is how it works:
> A level in the tree follows the following:
> x * 10^level
> 
> x * 10^1 belongs to level 1 in the three
> x * 10^2 belongs to level 2 in the three.
> etc.

Here's a different way to look at it: the level in the tree is 
determined by the length of the string representation of the node. 2 
long -> level 1. 3 long -> level 2. etc.

> I decided to make this pretty straightforward so I wrote a Node class
> and a Tree class.

Are you sure you need a Tree class? The Node class itself may have all 
the facilities needed to manage an entire tree. The tree is then 
represented by a 'root' node. You'd then have:

- root
   - 10
 - 103
 - 105
   - 12
etc.

> A Node has a key which is an integer, as well as some additional
> information that isn't relevant to the structure. It also has a link
> to it's sibling, which is the next node on the same level. And a link
> to it's first child.

A different way to implement this is for each node to have a (sorted) 
list of children and potentially a link to its parent. The story then 
looks like this:

- root with the following children
   - 10 (with parent = root) with the following children:
 - 100
 - 108
   - 12 (with parent = root)
etc.

You then do not insert siblings, you add children (not tested, but the 
intention is what counts):

class Node(object):
 def __init__(self, name):
 self.Name = name
 self.Parent = None
 self.Children = []
 def addChild(self, newname):
 """Tries to add the node as a newNode. Returns True
 if successful, False otherwise."""
 # check if the node is a (sub)child
 if newname[:len(self.Name)] <> self.Name:
 return False
 # check if it is a direct descendant
 if len(newname) == len(self.Name) + 1:
 newnode = Node(newname)
 newnode.Parent = self
 self.Children.append(newnode)
 self.Children.sort()
 return True
 else: # not a direct descendant -> add to one of the children
 for child in self.Children:
 if child.addChild(newname):
 return True
 # if we arrive here, it means that there's a missing level in 
the hierarchy -> add it
 self.addChild(newname[:len(newname)-1])
 return self.addChild(newname)
 def show(self, indentation=0):
 print ' ' * indentation, '-', self.Name
 for child in self.Children:
 child.show(indentation + 2)
 def __cmp__(self, othernode):
 """Get sort() to work properly."""
 return cmp(self.Name, othernode.Name)
 def hasChildren(self):
 return len(self.Children) > 0
 def hasSiblings(self):
 return (self.Parent <> None) and (len(self.Parent.Children) > 1)

root = Node('')
root.addChild('10')
root.addChild('12')
root.addChild('0')
root.addChild('20')
root.addChild('108')
root.addChild('5')
root.addChild('678')

root.show()

This implementation will not handle the dot-style leaves properly, 
you'll need some extra logic for that. It will however 'fill in the 
blanks', so you can add node '678' without adding nodes '6' and '67' 
first and auto-sort the nodes.

> How do I know if I have a sibling or a child?
> Simple, I just check the length:
 > -
 > if( len(str(node1[key])) == len(str(node2[key])) ):
 > -
 >
 > If the length, amount of integers, is the same, they are siblings.

With the alternative representation presented, it's more comfortable:
- has child: len(self.Children) > 0
- has sibling: (self.Parent <> None) and (len(self.Parent.Children) > 1)

> How do I determine that 2080 is not a child of 10. Or how do i determine
> that 536798 is not a child of 536780? And how do I determine that it is a 
> child?

See my code: just manipulate them as strings and it's suddenly very 
easy. Same length and the first (length - 1) characters are the same -> 
siblings. Different length: take the shortest node name; if the other 
node name starts with that string, it's a child, otherwise they're 
unrelated.

> I can't seem to rack my brains around a solution for this. Maybe it's
> my tree-structure that is making this more complex than it should be?

Hierarchies are easier if you look at them as families: it's easier to 
ask a parent how many children it has, than it is to ask one of the 
siblings if there is any sibling younger than it, then ask that younger 
sibling if it has any younger siblings, etc.

Yours,

Andrei



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


Re: [Tutor] class methods as argument

2007-02-10 Thread Andrei
Hi Thomas,


thomas coopman wrote:

> I want to execute the class method given as argument,
> but this obvious doesn't work, but I don't know how to
> get it work,

Pass the method reference of the class as argument, like this:

 >>> class A(object):
... def __init__(self, x): self.x = x
... def dostuff(self, arg):
... print self.x
... print arg
...
 >>> def dostuff(obj, method):
... method(obj, 'blabla')
...
 >>> a = A(5)
 >>> dostuff(a, A.dostuff)
5 # this demonstates method has been called for instance a
blabla




Yours,

Andrei

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


  1   2   >