Re: [Tutor] Whats so good about OOP ?

2005-03-12 Thread Bill Kranec
Hi Mark,

In my brief experience with OOP, I would say that the main advantage is
organization of code.  All functions and attributes that you need to work
with an object are wrapped up nicely inside the object.  Also, object
inheritance provides a great framework for easy customization.

For example, to write some code to model a car, you might use an object:

class car:
   def __init__( self, name ):
  self.name = name
  self.numberOfDoors = 4
  self.milesPerGallon = 25
   def drive( self, time ):
  print self.name+' drove for '+str(time)+' hours, and used '\
  +str(self.milesPerGallon*time)+' gallons of gas.'

In this example, the drive function will only be accessible to things that
we have defined as cars.  You can also have specialized versions of the
car class (for example, to model a Porsche) which have different
attributes ( self.milesPerGallon = 15 ), but have the same methods (you
still want the drive() method).

Note that this task isn't necessarily easier to do with OOP, (you could
just as easily define a function which takes all of the attributes as
inputs), but I believe the structure is clearer, and you get the added
bonus of expandability.

I hope my example has been helpful, and that someone here will correct me
if I've said something wrong.  Good luck using OOP!

Bill

On Sat, 12 Mar 2005, Mark Kels wrote:

 Hi list !
 I want to know whats so great in OOP...
 I have learned some of it, but I don't understand why everybody like
 it so much...
 Can anyone give me an example for a task that could be done only with
 OOP or will be much simpler to do with it ?

 Thanks in advance.

 --
 1. The day Microsoft makes something that doesn't suck is probably the
 day they start making vacuum cleaners.
 2. Unix is user friendly - it's just picky about it's friends.
 3. Documentation is like sex: when it is good, it is very, very good.
 And when it is bad, it is better than nothing. - Dick Brandon
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Criticism / Suggestions

2005-03-01 Thread Bill Kranec
Hi Kent,
First off, thank you so much for the suggestions!  They have helped 
clarify some of the concepts I've been struggling with lately ( mostly 
object - related ones ).  I have been teaching myself Python in my spare 
time for the last few months, and have no previous programming 
experience, so any feedback I get really helps me improve as a programmer.

I have implemented some of the changes you talked about, and posted an 
updated version of my program here:

http://rafb.net/paste/results/SicsjJ23.html
I hope this new version is a bit better, and that my answers to your 
questions help you understand what I'm doing.

do you mean, 'each  player is teammates with each other player exactly 
once', or, 'each  player is teammates with each other player at most 
once'? Is there a certain number of rounds that must be played?
Each player is teammates with each other player exactly once.
- Why do you have the initialization code in a comment? Wouldn't it be 
helpful to put that in a function or maybe Tournament.__init__()?
The initialization code is commented because I don't run it every time 
the script runs ( it takes awhile to run ).  I usually load the list 
from a file, this is reflected in my updated code.

- I have a hard time figuring out how this is supposed to work. Maybe 
some comments about the algorithm you are using would help? I have no 
idea what self.key is doing.
My algorithm works something like this:
Fact: roundlist partitions into 11 slices of length 113400, and self.key 
keeps track of which round in each of those slices I am currently using.

Starting with the first tournament ( Tournament(0) ), I do the following:
   1. Construct the tournament.
   2. Test to see if two players are on the same team twice ( 
checkTeammates )
   3. Test to see if two players match up against each other too often 
(checkOpponents )
   4a. If everything is ok, I'll append another round from the next slice.
   4b. If not, I'll try the next round in the most recent slice.  If 
none of the rounds in the slice work, I'll move back and try the 
next round in the previous slice, etc.
   5. Whenever I manage to build an 11 round tournament, I'm done.

It's an attempt at a recursive algorithm, and I'm not sure how well it 
is implemented.

- What is the argument to Tournament.__init__() for?
The argument lets you specify a starting tournament, to avoid having to 
start the search from the beginning, you can instead pick up from some 
point where you last left off.

Example:  Tournament(0,113460) gives a two round tournament using 
elements 0, 113460 from roundlist.

- The above code depends on roundlist which is not even defined 
anywhere in the module (just shown in the comment). This suggests 
again that the init code from the comment should be part of 
Tournament, and roundlist should be an attribute of Tournament. For a 
class to depend on some external variable is bad design and will break 
if the client code is in a different module from the class code 
(roundlist will be in a different namespace than Tournament).
I have always been uneasy about this, but I wanted to be able to define 
multiple tournament objects off of the same roundlist, to avoid 
generating the list every time a new object is created.  I think what I 
really want to do is have a separate Round class, from which Tournament 
inherits the list of rounds.  I have started to implement something like 
this in my most recent version, but haven't finished it yet.  ( I need 
to understand class inheritance better. )

- Tournament.next() doesn't return a value, it prints it directly. It 
should return self.key or str( self.key )
Does the next() call in an iterator object need to return a value, and 
if so, why? ( My reasoning was that next() only needs to increment the 
iterator. )

Thanks again for any additional suggestions!
Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Criticism / Suggestions

2005-02-28 Thread Bill Kranec
Hello,
So I think that I've 'completed' my first real Python program, and I 
would appreciate any constructive criticism you all could offer.  The 
program deals with a question that my Dad asked me awhile ago, which was 
If twelve people want to divide into teams of two and play (golf) 
against each other, can a series of rounds be constructed such that each 
player is teammates with each other player only once, and play against 
each other as opponents no more then 3 times ( that last bit might or 
might not be 'optimal'.

My program:
1. Defines a round as a list, for example [1,2,3,4,5,6,7,8,9,10,11,12], 
meaning player 1  player 2 vs. player 3  player 4, etc.  I have 
generated all such possible rounds ( I think ).
2. Defines a tournament iterator object, which uses two functions, 
checkTeammates and checkOpponents, to build a tournament satisfying the 
above criteria.

Like I mentioned before, this is my first fairly complex program, and is 
also my first real use of things like exceptions, objects, and list 
comprehensions.  Basically I would like to know weather or not I used 
these structures properly, weather or not my syntax is good, and if 
there are any places with potential for improvement.  ( This version is 
somewhat slow, but is much faster than previous versions that I have 
written. )  I've tried to have as many comments as possible to help 
readability.

Code aside, my algorithm may or may not be the best.  Feel free to 
suggest improvements.

The code is located at http://rafb.net/paste/results/lrd5DG32.html.
Thanks for any thoughts!
Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Method/subclass

2005-02-23 Thread Bill Kranec
This article might also be helpful, as it is a little more concrete: 
http://www.devx.com/dbzone/Article/22093.  I found it by Googling for 
'python database access object'.  Is this the kind of thing that you are 
referring to, Kent?

HTH,
Bill
Liam Clarke wrote:
Kia ora, 

 

I'm not really sure what you are trying to do, the code is pretty sketchy. It looks like you want to
have a bunch of queries on your dataset, and the result of each query is displayed in a window. Is
that right? Assuming it is, I'll continue...
   


What I'm doing here is very sketchy, both in my mind and code. So
yeah, my apologies, I probably should have put more effort into the
question. ESR would flame me for sure.
 

First, DO NOT put any references to your GUI classes into your data access classes!! NEVER ever do that!
   

Point noted. That was me trying to grasp the concept of returning
objects, and then I thought I could be clever
 

I would probably have
- a data access class (DAO)
- probably some data container classes (domain objects). Your data access class 
methods will take domain objects as parameters and return them as results. The 
different parts of the app will communicate by passing domain objects around. If the 
domain data is very simple you might just use
Python lists and dictionaries.
- a class for the main window
- classes for the display windows - a separate class for each kind of display. If all 
the displays are similar you might reuse a single class; if they are very different 
they will have their own classes. If there is shared behaviour you might have a 
common base class, otherwise inherit directly from the GUI classes.
- possibly one or more controller classes - the classes that provide the glue between 
the gui and the data. Some of this logic will be in the main window, some you 
might want to put in its own class.
A sample data flow might be
- user enters a query into the main window and clicks a 'search' button
- the search button handler is invoked. This might be a method of the main window class, or it might delegate to a helper class.
- in either case, the handler class must have a reference to the data access class. It forwards the request to the DAO, gets the results back, and creates the new window to display the results. (The result object might be passed directly to the window class in its constructor or by a helper method.)
   


Thank you for that Kent, your shouting has been heeded, and it makes
perfect sense not to return GUI objects. Of course, hindsight is great
like that, the answer to the cryptic crossword clue is obvious once
you know the answer.
I'm not sure I understand your response fully, so I've described how
I would do this in accordance with my understandinf of the method
described above. Any feedback/corrections are gratefully welcomed.
But first, a wee bit of explanation. As I said, this is very sketchy.
I've run into the issue of not knowing where to start. This is my
first database type project, so I want
to go about this the right way from the get go, which means my
progress is quite hesitant/non-existent. Ultimately I want to follow
good methods of coding as much as I can, as I dream of actually being
able to make a living out of this at some stage.
So, as I don't actually know how to do this, on account of never
having done similar, I need to layout in my mind what I'm going to do,
before I do it. I had a look at UML, but it doesn't look helpful .
Perhaps it's a way of thinking that I need to learn that'll make UML
useful.
So, looking at your dataflow above Kent, I'm planning - 

my main GUI runs, and upon initialisation creates self.DAO a data access object.
The handlers in the main and each child window, submit requests by
calling an appropriate method of self.DAO (or self.parent.DAO) as the
case may be, passing any needed data as a dictionary/list, as it's not
going to be overly complicated.
The DAO then creates an SQL request as necessary, and creates a
dictionary/list out of any retrieved data, and returns it to the
handler. (Or an acknowledgement if data was entered, or similar.)
If a new window needs to be opened (in response to a query or
requested table) then the handler then instantiates a new child window
using the dictionary after it's been appropriately twiddled. (As a lot
of handlers are going to be doing this, perhaps a function of  my
parent window can hold a method for the twiddling.)
Is this going to violate any best practise type methodologies? Sheesh,
I get so confused.
I've spent all this time trying to keep 'logic and gui' separate, with
the result that I stuck my gui related logic in daft places.
I dunno, I was thinking perhaps do this one in Java, so I'm forced to
learn how to use objects (particularly passing them around) properly.
The temptation to use many, many, functions is there. I've never
(consciously) used objects as arguments and returned values,
aside from what 3rd party packages have required. To put it a better
way, I've 

[Tutor] carriage return on windows

2005-01-29 Thread Bill Kranec
Hello,
I'm trying to have a loop in a program print a message so I know it's 
status.  Right now I'm using

print Percent completed: + str(percent) + \r
Which should send me back to the beginning of the line and overwrite it 
with a new line.  But instead I get:

Percent completed: 50
Percent completed: 51
Percent completed: 52
Percent completed: 53
and so on.  Am I using this wrong, and if so, what is the right way to 
implement something like this?

Thanks for any help!
Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advise...

2005-01-26 Thread Bill Kranec
There has been alot of talk on this list about using list comprehensions 
lately, and this could be one of those useful places.  While I don't 
have time to experiment with real code, I would suggest changing your 
function to look like:

steps = [ min_x + i*delta_x for i in range(steps) ]
totalarea = sum([ eval(func_x)*delta_x for x in steps ])
Since list comprehensions are significantly faster than while loops, 
this could be a big speed boost.

There may be a mistake or two in the above code, but hopefully the idea 
will be helpful.

Bill
TJ wrote:
What is the function? 3*x*x
What is the minimum? 2
What is the maximum? 5
117.000435
Which, considering that it is supposed to be exactly 117, It's darn 
good. Unfortunately, it also takes about
10 seconds to do all that.
Any suggestions? Any advice? TIA
Jacob Schmidt

Jacob,
You can get better accuracy with orders of magnitude fewer steps by 
evaluating the function at the midpoint of each step rather than the 
low value.  This has the added benefit of yielding the same result 
when stepping x up (2 to 5) or down (5 to 2).

Here's some modified code (I don't have psyco):

from __future__ import division
import time
   def reimannSum(func_x, min_x, max_x, steps):
start = time.time()
totalArea = 0
#precalculate step size
delta_x = 1 / steps
#set x to midpoint of first step
x = min_x + delta_x / 2
while min_x = x = max_x:
totalArea += eval(func_x) * delta_x
x += delta_x
return totalArea, steps, time.time() - start
stepsList = [10, 1, 1000, 500, 200, 100]
fmt = 'Area: %f  Steps: %d   Time: %f'
for steps in stepsList:
print fmt % reimannSum('3 * x * x', 2, 5, steps)

The results on my machine are:
Area: 117.00  Steps: 10   Time: 44.727405
Area: 117.00  Steps: 1   Time: 4.472391
Area: 116.99  Steps: 1000   Time: 0.454841
Area: 116.97  Steps: 500   Time: 0.223208
Area: 116.81  Steps: 200   Time: 0.089651
Area: 116.25  Steps: 100   Time: 0.044431
TJ
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] flattening a list

2005-01-11 Thread Bill Kranec
Hello,
I have a list of lists, for example [ [1,2] , [3,4] ], and I would like 
to pass all the elements of that list as arguments to a function (for 
example the intersection of all list elements).  Is there a command in 
regular Python to do this?  I would like to avoid the hassle and speed 
hit of a loop to extract all the list elements.

In the past, I believe I have used something like flatten(list), which 
was part of Numarray (I think).  Am I missing an obvious or clever 
solution in regular Python?

Thanks for your help!
Bill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] simple list query

2005-01-02 Thread Bill Kranec
You might want to try:
x in list
this will return true if, for example,  list = [x,y,z,w], false if list 
= [y,y,y,y]

Bill
Dave S wrote:
OK simple query,
I have a list consisting of about 250 items, I need to know if a 
particular item is in the list. I know this is better suited to  a 
dictionary but thats not the way it ended up ;-)

I could do a for loop to scan the list  compare each one, but I have 
a suspission that there is a better way ?

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