Re: [Tutor] designing a class

2006-01-27 Thread Alan Gauld
> Write a class called Mylist that shadows ("wraps") a
> Python list: it should overload most list operators
> ...
> When I read this, I feel like a deer caught in the
> headlights.  Where should I begin?  How do I go about
> designing a new class?

Well, to quote an old joke, I wouldn't start from here

Defining a new type based on a builtin type and overloading 
all the operators is a relatively hard thing to do (correctly). 
Personally I'd advise defining something easier and less useful.
Something that doesn't require operators at all initially just 
plain methods.

Once you've defined a few of those you will find the exercise
above more straightforward. Try wrioting a program that you 
are interested in that uses objects - like say a DVD database, 
or a menu management system. Think about how you might 
build DVD or menu classes. What kind of things would you 
do to these objects if you had them(their methods). What kind 
of information would those methods need to work?

Build the objects method by method and test them.

Just some ideas.

The one advantage of starting with a builtin type is that most of 
your code just calls the existing class's methods but I still think 
the advantage of that is outweighed by the added complexity
of jumping straight into overloading operators!

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] Is this overkill?

2006-01-27 Thread Alan Gauld
Catherine

> I've spend some time going throught the many available turorials, but find
> it hard to get good exercises to try out what you learn.

Most tutorials do have a few suggested exercises but the best way is to
take the examples they give and modify them to see what happens. The
reason for that is you are starting with a working outline which is much
easier than starting with nothing.

However one source of small project ideas is "Useless Python". Have
you seen that web site? It includes all sorts of little programs that people
have written plus lots of projects that have been suggested, some very
small others quite ambitious.

So far as I know Useless Python is a unique concept in programming
languages, but I think its great for beginners! (And don't forget to visit
the 'old site' because it has more content than the new - but less well
organised!)

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



On 1/21/06, Bradly McConnell <[EMAIL PROTECTED]> wrote:
>
> Greetings all:
>
> I'm new to Python, and have come across and exercise that basically
> counts to 100.  The idea is to accept user input for an initial
> number, and then let the user add additional numbers.  I wanted to
> give feedback if a number selected would bring the total above 100, so
> the user would select a lower number.  It looks like I have it
> working, but it doesn't seem very efficient.  I would like any hints,
> help, or comments that you can provide.  Below is what I have so far.
>
> number = input("Please enter a number: ")
> while number != 100:
>additional_number = input("Please enter an additional number: ")
>if additional_number + number > 100:
>lower_number = input("please enter a lower number: ")
>if lower_number + number > 100:
>lower_number = input("Lower!")
>else:
>number = lower_number + number
>elif additional_number + number < 100:
>number = additional_number + number
>else:
>continue
>
> print "Done", number
>
>
> Brad
> ___
> 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] AttributeError - ChatServer

2006-01-27 Thread Alan Gauld
> AttributeError: ChatServer instance has no attribute 'decriptors'

Read the error carefully - a typo maybe?

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


Re: [Tutor] First steps with Tkinter

2006-01-27 Thread Etrade Griffiths


Catherine
I'm a Python newbie too but have done some programming with C++ Builder
so have a little knowledge of GUIs etc
Best regards
Alun

At 22:41 26/01/2006, catherine curley wrote:
Alan
 
As a matter of interest, did you have much knowledge of Python before you
tried TKinter?  I'm only a python beginner at present.
 
Catherine
 
On 1/26/06,
[EMAIL PROTECTED]
<[EMAIL PROTECTED] > wrote: 


Hi!

Just started trying to get to grips with Python and Tkinter.  Have Frederick

Lundh's tutorial and am on program hello2.py which looks like this

# File: hello2.py

from Tkinter import *

class App:

   def __init__(self, master):

   frame = Frame(master)

   frame.pack()

   self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)

   self.button.pack(side=LEFT)

   self.hi_there = Button(frame, text="Hello", command=self.say_hi)

   self.hi_there.pack (side=LEFT)

   def say_hi(self):

   print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()

I am running from inside Pythonwin 2.4 IDE under XP Pro and every time I run 

hello2.py it freezes when I press "QUIT".  The only way to kill it is through

Alt-Ctrl-Del but this crashes Pythonwin.  Any workaround for this so that I

can use Tkinter from inside the IDE?  BTW the same thing happend with IDLE 

Thanks in advance

Alun Griffiths

___

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] Controling my loops and redundant code?!?

2006-01-27 Thread Jon Moore
PaulThe book is called 'Python Programming for the absolute beginner'. It is written by Michael Dawson and published by Premier Press.I have to say that as someone that has no experience in programming what so ever, I am hooked! I need to learn Python for a job I am starting next month and to say I felt a little worried at the idea is an understatement. Since going through the first few chapters of this book (and having the support of this group) I can not wait to learn more!
JonOn 26/01/06, Paul Kraus <[EMAIL PROTECTED]> wrote:
What book are you working through? That is a pretty interesting exercise.PaulOn Thursday 26 January 2006 12:52 pm, Bob Gailer wrote:> At 08:44 AM 1/25/2006, Jon Moore wrote:>> Hi,>
> I have written the program below as an exercise from a book I am working my> way through.>> Objective from book:> Write a character creator program for a role-playing-game. The player> should be given a pool of 30 points to spend on four attributes: strength,
> health, wisdom and dexterity. The player should be able to spend points> from the pool on any attribute and should be also be able to take points> from an attribute and put them back in the pool.
>> Although the program meets the aim of the exercise set out in the book ,> there are a couple of things I am not happy with!>> 1. I am sure I have written far more code than required. Where could I have
> made some shorcuts?>> 2. Should the user enter a value greater than what is available, the> program kicks the user all the way back to the main menu. How could I tidy> this up to just loop round to ask the user to try a new value?
>> choice = None>> # Set max number of available points> POINTS_POOL = 30>> # store attribute values> attributes = [["Strength", 0], ["Health", 0], ["Wisdom", 0], ["Dexterity",
> 0]]>>> Some ideas to chew on as you develop skills and understanding of> programming.> Separate the "essential data" from the code. The essential data are> attributes, associated points and max_points. So
>> attributes = ["Strength", "Health", "Wisdom", "Dexterity"]> points = [0, 0, 0, 0]> MAX_POINTS = 30>> In this model the relationship between attributes and points is by
> position. Later you will study and use classes; then the points list will> be replaced by a list of class instances, one per attribute.>> Develop code that operates on these lists to accomplish the various
> objectives. The code itself will never refer to any attribute by name!>> For example - to list the attributes with their points:>> for x in range(len(attributes)):>   print "\t",attributes[x], points[x]
>> To assign values. Note I separated getting input from converting it to> integer so we can see if the user's entry is convertible.:>> available_points = MAX_POINTS - sum(points)> print "You have " + available_points + " available."
> for x in range(len(attributes)):>  cvalue = raw_input("How much would you like to assign to " + attributes[x]> + " ?: "))>   if cvalue.isdigit():> value = int(cvalue)
>   else:> print "Number expected">> [snip]> --> Bob Gailer> 510-978-4454--Paul Kraus=-=-=-=-=-=-=-=-=-=-=PEL Supply CompanyNetwork Administrator
216.267.5775 Voice216.267.6176 Faxwww.pelsupply.com=-=-=-=-=-=-=-=-=-=-=___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- Best RegardsJon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Alan Gauld
Hi Ben,

> I want to enter the words and definitions from the  text file into the 
> dict.
> The way the text file is set up is that one  line is the word and the
> next line is the definition.

>  I tried using a for loop like this
>
>  f = open('glossary.txt','r')
>  gloss = {}
>
>  for line in f:
>  gloss[line] = line

The problem that you have is that you really need to read two lines at a 
time.
(Assuming that the definitions are all on one line which may not be true!)
A while loop may be easier in this case.

A for loop will read each line individually. You then need to set a 
definition
flag to tell the loop body whether you are reading a definition or a key.

Either type of loop is possible. Since you started with a for loop lets 
stick with it...

definition = False
currentKey = None

for line in f:
if isDefinition:
   gloss[currentKey] = line
   currentKey = None
   isDefinition = False
else:
   currentKey = line
   isDefinition = True

If the definitions take up more than one line each then you will need to 
think
about how to identify the end of a definition - a blank line maybe? You will
need to append the lines to the glossary entry (rather than just assign 
them)
until the end of the definition. And you will need to update the 
isDefinition
flag at the appropriate times.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] why can't I find a function that givesme the sign of aninteger?

2006-01-27 Thread Alan Gauld
Orri,

> Eh you mean to say that in next Python versions someone could decide
> to change cmp(x,0) to another meaning? I bet my countryman (I'm from
> Holland too ;-) ) will veto that! Or else I'll pay him a visit :D

Its not another meaning, its the current meaning.
Kent is just pointing out that while the default cmp currently 
returns -1,0,1
there is nothing to stop a user defined cmp fom returning any negative or
positive number instead of -1,1. And cmp() calls any user defined cmp
under the hood.

In theory the standard cmp could be changed in future although its 
unlikely..
So while it is a nice trick it cannot be relied upon since it depends on a
detail of implementation. In practice I suspect you are fairly safe :-)

Alan G

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


Re: [Tutor] why can't I find a function that givesme the sign of aninteger?

2006-01-27 Thread Rinzwind
On 1/27/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
> Orri,
>
> > Eh you mean to say that in next Python versions someone could decide
> > to change cmp(x,0) to another meaning? I bet my countryman (I'm from
> > Holland too ;-) ) will veto that! Or else I'll pay him a visit :D
>
> Its not another meaning, its the current meaning.
> Kent is just pointing out that while the default cmp currently
> returns -1,0,1
> there is nothing to stop a user defined cmp fom returning any negative or
> positive number instead of -1,1. And cmp() calls any user defined cmp
> under the hood.
>
> In theory the standard cmp could be changed in future although its
> unlikely..
> So while it is a nice trick it cannot be relied upon since it depends on a
> detail of implementation. In practice I suspect you are fairly safe :-)
>
> Alan G
>
>

Ok.

Well I needed it to reflect -, 0 or + anyways so I should be safe. I
needed it to find out the direction of a chessmove so pawns could not
walk back and with that and the MIN and the MAX function I could do
with 1 for+while loops per direction (hor, vert or diag).

Oh, I am now on 32 hours of coding and started with 0 knowledge of
Python, PIL and/or Pygame and the 1st release should be out soon :-)
Just need to fix castling, promotion and en passant and I'm done! I
LOVE PYTHON.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] socket and lost data

2006-01-27 Thread le dahut
Hi,
I try to send some data across a network (between 400KB and 10MB) like 
this :
def envoyer(conn, mysize):
 print mysize,' KB sent'
 data = '1'*1024
 data_end = data[:-5]+'#'
 data = data*(mysize-1)
 begining = time.time()
 conn.send(data)
 conn.send(data_end)
 passed = time.time() - begining
 return passed, size

and receive it like this :

def recevoir(conn):
 data=''
 while 1:
 tmpdata = conn.recv(8192)
 data += tmpdata
 if '#' in data:
 print 'END OF DATA'
 break
 print len(data)/1024, ' KB received'
 return passed, int(data[-15:-5])/1024

But I don't receive as much data that I sent ... does someone know why ?
If I want to send the same data back to the client, do I have to destroy 
and recreate the socket ?

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


Re: [Tutor] why can't I find a function that givesme the sign of aninteger?

2006-01-27 Thread Kent Johnson
Alan Gauld wrote:
> Orri,
> 
> 
>>Eh you mean to say that in next Python versions someone could decide
>>to change cmp(x,0) to another meaning? I bet my countryman (I'm from
>>Holland too ;-) ) will veto that! Or else I'll pay him a visit :D
> 
> 
> Its not another meaning, its the current meaning.
> Kent is just pointing out that while the default cmp currently 
> returns -1,0,1
> there is nothing to stop a user defined cmp fom returning any negative or
> positive number instead of -1,1. And cmp() calls any user defined cmp
> under the hood.
> 
> In theory the standard cmp could be changed in future although its 
> unlikely..
> So while it is a nice trick it cannot be relied upon since it depends on a
> detail of implementation. In practice I suspect you are fairly safe :-)

The test suite does specifically test for -1, 0 and 1 as the result of 
cmp(int, int):
 self.assertEqual(cmp(-1, 1), -1)
 self.assertEqual(cmp(1, -1), 1)
 self.assertEqual(cmp(1, 1), 0)
so this behaviour will probably be consistent in different Python 
versions. Jython for example tries to pass the standard tests and I 
imagine IronPython does as well, and of course (C)Python.

Kent


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


Re: [Tutor] socket and lost data

2006-01-27 Thread Kent Johnson
le dahut wrote:
> Hi,
> I try to send some data across a network (between 400KB and 10MB) like 
> this :
> def envoyer(conn, mysize):
>  print mysize,' KB sent'
>  data = '1'*1024
>  data_end = data[:-5]+'#'
>  data = data*(mysize-1)
>  begining = time.time()
>  conn.send(data)
>  conn.send(data_end)
>  passed = time.time() - begining
>  return passed, size
> 

socket.send() may not send all the data - it returns a count telling you 
what it actually did. Use socket.sendall() or put your call to send() in 
a loop.

> and receive it like this :
> 
> def recevoir(conn):
>  data=''
>  while 1:
>  tmpdata = conn.recv(8192)
>  data += tmpdata
>  if '#' in data:
>  print 'END OF DATA'
>  break
>  print len(data)/1024, ' KB received'
>  return passed, int(data[-15:-5])/1024

socket.recv() will return an empty string when there is no more data - I 
would look for that instead of your marker, it is more general. Instead of
   if '#' in data:
you can say
   if data == '':
or just
   if not data:

> 
> But I don't receive as much data that I sent ... does someone know why ?
> If I want to send the same data back to the client, do I have to destroy 
> and recreate the socket ?

If this doesn't fix it, maybe an example of the lost data would help.

Kent

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


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-27 Thread Wolfram Kraus
Rinzwind wrote:
> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> I searched on  the web for a bit but sgn and sign give me way too many 
> discussions about Decimals. python.org  with 
> numbers/digits doesn't tell about a function.
> 
> Maybe Python uses a different name for it so I am not looking for the 
> correct wording :( Sucks not knowing syntax from my memory and having to 
> look them up alot).
> 
> Wim
> 
> 
If you can accept False,0,True instead of -1,0,1 you can use:
x and x == abs(x)

HTH,
Wolfram

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


Re: [Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

2006-01-27 Thread Wolfram Kraus
Rinzwind wrote:
> In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> I searched on  the web for a bit but sgn and sign give me way too many 
> discussions about Decimals. python.org  with 
> numbers/digits doesn't tell about a function.
> 
> Maybe Python uses a different name for it so I am not looking for the 
> correct wording :( Sucks not knowing syntax from my memory and having to 
> look them up alot).
> 
> Wim
> 
> 
> 
D'Oh!

It works with -1/0/1, too:
x and x/abs(x)

 >>> x = -2
 >>> x and x/abs(x)
-1
 >>> x = 2
 >>> x and x/abs(x)
1
 >>> x = 0
 >>> x and x/abs(x)
0

HTH,
Wolfram

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


Re: [Tutor] why can't I find a function that gives me the sign of an integer?

2006-01-27 Thread Rinzwind
On 1/27/06, Wolfram Kraus <[EMAIL PROTECTED]> wrote:
> Rinzwind wrote:
> > In basic I can use SGN to get back -1, 0,  +1 if a number is <0, 0, >0.
> > I searched on  the web for a bit but sgn and sign give me way too many
> > discussions about Decimals. python.org  with
> > numbers/digits doesn't tell about a function.
> >
> > Maybe Python uses a different name for it so I am not looking for the
> > correct wording :( Sucks not knowing syntax from my memory and having to
> > look them up alot).
> >
> > Wim
> >
> >
> >
> D'Oh!
>
> It works with -1/0/1, too:
> x and x/abs(x)
>
>  >>> x = -2
>  >>> x and x/abs(x)
> -1
>  >>> x = 2
>  >>> x and x/abs(x)
> 1
>  >>> x = 0
>  >>> x and x/abs(x)
> 0
>
> HTH,
> Wolfram


No, I needed the -1 0 and 1 :-)
That way whatever you move (like Qd2-d6 or Qd6-d2) I could find the
places in between the 2. Same goes for Rd1-Rd8 or Rd8-Rd1). I needed
it to multiply with -1, 0, 1 according to what move it was :-)

Oh and I allready got it working so I'm all :-) :-) :-) about it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-27 Thread Michael Janssen
On 1/26/06, John Fouhy <[EMAIL PROTECTED]> wrote:

> >>> for name in pairs:
> ...  print '%*s --> %*s' % (maxKey, name, maxValue, pairs[name])

thanks for pointing out the '*' syntax. Ignorant as I am I have had to
write things like

   print '%%%ss --> %%%ss' % (maxKey, maxValue) % (name, pairs[name])

for years. Thanks :-)
Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries

2006-01-27 Thread Kent Johnson
Jon Moore wrote:
> Hi
> 
> Is there anyway to print informtation from dictionaries better than this?:
>  
>  >>> pairs = {"Jon Moore": "Tony Moore",
>  "Simon Nightingale": "John Nightingale",
>  "David Willett": "Bernard Willet",
>  "John Jackson": "Stuart Jackson",
>  "James Southey": "Richard Southey",
>  "William Forsythe": "Shaun Forsythe"}
>  >>> print pairs.keys()
> ['David Willett', 'Jon Moore', 'John Jackson', 'Simon Nightingale', 
> 'James Southey', 'William Forsythe']
>  >>>

There is a very nice table formatting recipe here:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662

Kent

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


Re: [Tutor] socket and lost data

2006-01-27 Thread Alan Gauld
I'm a wee bit confused.

> def envoyer(conn, mysize):
> print mysize,' KB sent

This doesn't seem to be true from the code.

> data = '1'*1024
> data_end = data[:-5]+'#'
> data = data*(mysize-1)

So data is mysize-1 KB, but you printed mysize KB?

> begining = time.time()
> conn.send(data)
> conn.send(data_end)
> passed = time.time() - begining

it migfht be more useful to print the siuze here and work out what you 
really sent:

print 'sent: ',len(data) + len(data_end), 'bytes'

> return passed, size

where is size defined?

> and receive it like this :
>
> def recevoir(conn):
> data=''
> while 1:
> tmpdata = conn.recv(8192)
> data += tmpdata
> if '#' in data:
> print 'END OF DATA'
> break
> print len(data)/1024, ' KB received'
> return passed, int(data[-15:-5])/1024
>
> But I don't receive as much data that I sent ... does someone know why ?

if you are going by your print statements they will not match.

> If I want to send the same data back to the client, do I have to destroy 
> and recreate the socket ?

There is nothing to stop you having two sockets, one in each direction.

Alan G

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


[Tutor] templates

2006-01-27 Thread Mike Hansen
For some of the web programming I've done in Python, I've used htmltmpl. I had 
some experience with it in Perl, and found a Python version.

http://htmltmpl.sourceforge.net/

I like that there's nearly a complete separation between the presentation and 
the code. This is great when one person is designing the pages and another is 
writing the code to drive those pages. However, that's usually not the case for 
me. I'm usually doing both, and I'm thinking there's got to be something 
possibly better out there. I'm curious about other templating systems. I 
wouldn't be opposed to a little bit of code in the template. I just don't want 
to go the other extreme of something like PHP or ASP. i.e. all code in the 
template.

What web templating systems do you use and why?

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


Re: [Tutor] designing a class

2006-01-27 Thread Christopher Spears

> class MyList:
>def __init__(self, aList=None):
>  if aList is None:
>self._list = []
>  else:
>self._list = aList[:]
> 

This code certainly looks like it will do the trick. 
I'm just not sure what the _ in front of list (i.e.
_list) denotes.



"I'm the last person to pretend that I'm a radio.  I'd rather go out and be a 
color television set."
-David Bowie

"Who dares wins"
-British military motto

"I generally know what I'm doing."
-Buster Keaton
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] designing a class

2006-01-27 Thread Kent Johnson
Christopher Spears wrote:
>>class MyList:
>>   def __init__(self, aList=None):
>> if aList is None:
>>   self._list = []
>> else:
>>   self._list = aList[:]
>>
> 
> 
> This code certainly looks like it will do the trick. 
> I'm just not sure what the _ in front of list (i.e.
> _list) denotes.

It's a convention that indicates a private attribute. Think of it as 
telling clients, "This is for my private use, it may change at any time."

In this case it was also a way to avoid using 'list' as the name of the 
attribute. 'list' is the name of a built-in - it shouldn't be used as a 
variable name because it will shadow the built-in. In the case of an 
attribute it doesn't really matter but I have a strong habit of not 
using 'list' as a name.

Kent

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


[Tutor] the chicken and the egg

2006-01-27 Thread Christopher Spears
Thanks to all of the tutors on this mailing list!  I'm
finally making some headway!  I originally decided to
tackle my problem one operator at a time:

class MyList:
def __init__(self, aList=None):
if aList is None:
self.mylist = []
else:
self.mylist = aList[:]
def __getitem__(self, index):
return self.mylist[index]

However, I got the following error:

>>> from MyList import *
>>> x = MyList([1,2,3])
>>> x[0]
Traceback (most recent call last):
  File "", line 1, in ?
  File "MyList.py", line 8, in __getitem__
self.mylist[index]
AttributeError: MyList instance has no attribute
'__setitem__'
>>> x.mylist[0]
1

I did the obvious and created __setitem__.

class MyList:
def __init__(self, aList=None):
if aList is None:
self.mylist = []
else:
self.mylist = aList[:]
def __getitem__(self, index):
return self.mylist[index]
def __setitem__(self, index, value):
self.mylist[index] = value

Why does __getitem require __setitem__?  Don't they do
different things?


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


Re: [Tutor] Dictionaries

2006-01-27 Thread Victor Bouffier
Hi Alan and Ken,

I think know the difference between using items() vs. iteritems() and
their equivalent for keys and values. I notice Ken suggests iteritems(),
while Alan suggests items() only.

Does one approach have an advantage over the other?
Should we use only one of them favorably?

Thanks.
Victor

On Thu, 2006-01-26 at 13:43 +, Alan Gauld wrote:
> > How would I modify this to just print either the values or keys?
> 
> Just ask for the values or the keys!
> 
> for value in pairs.values()
>  print value
> 
> for key in pairs.keys()
>  print key
> 
> for key,value in pairs.items()
> print key
> print value
> 


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


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Bob Gailer
Alan Gauld wrote:
> Hi Ben,
>
>   
>> I want to enter the words and definitions from the  text file into the 
>> dict.
>> The way the text file is set up is that one  line is the word and the
>> next line is the definition.
>> 
>
>   
>>  I tried using a for loop like this
>>
>>  f = open('glossary.txt','r')
>>  gloss = {}
>>
>>  for line in f:
>>  gloss[line] = line
>> 
>
> The problem that you have is that you really need to read two lines at a 
> time.
> (Assuming that the definitions are all on one line which may not be true!)
> A while loop may be easier in this case.
>
> A for loop will read each line individually. You then need to set a 
> definition
> flag to tell the loop body whether you are reading a definition or a key.
>
> Either type of loop is possible. Since you started with a for loop lets 
> stick with it...
>
> definition = False
> currentKey = None
>
> for line in f:
> if isDefinition:
>gloss[currentKey] = line
>currentKey = None
>isDefinition = False
> else:
>currentKey = line
>isDefinition = True
>   
Or you can use next():

for line in f:
gloss[line] = f.next()

> If the definitions take up more than one line each then you will need to 
> think
> about how to identify the end of a definition - a blank line maybe? You will
> need to append the lines to the glossary entry (rather than just assign 
> them)
> until the end of the definition. And you will need to update the 
> isDefinition
> flag at the appropriate times.
>
> HTH,
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> ___
> 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] Dictionaries

2006-01-27 Thread Alan Gauld
> ...  print '%*s --> %*s' % (maxKey, name, maxValue, pairs[name])
> 
> thanks for pointing out the '*' syntax. Ignorant as I am I have 
> had to write things like
>
>   print '%%%ss --> %%%ss' % (maxKey, maxValue) % (name, pairs[name])

I didn't even try that, I've always done it on two lines

fmt = "%%%ds --> %%%ds' % (width1,width2)
print fmt % (value1,value2)

'%*s' is a neat trick, albeit a tad obscure in the readability stakes.
But is %%%ds any better?!

Alan G.

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


Re: [Tutor] the chicken and the egg

2006-01-27 Thread Kent Johnson
Christopher Spears wrote:
> Thanks to all of the tutors on this mailing list!  I'm
> finally making some headway!  I originally decided to
> tackle my problem one operator at a time:
> 
> class MyList:
>   def __init__(self, aList=None):
>   if aList is None:
>   self.mylist = []
>   else:
>   self.mylist = aList[:]
>   def __getitem__(self, index):
>   return self.mylist[index]
> 
> However, I got the following error:
> 
> 
from MyList import *
x = MyList([1,2,3])
x[0]
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "MyList.py", line 8, in __getitem__
> self.mylist[index]
> AttributeError: MyList instance has no attribute
> '__setitem__'

Strange. It works for me. Are you sure there is nothing else in MyList.py?

D:\>type MyList.py
class MyList:
 def __init__(self, aList=None):
 if aList is None:
 self.mylist = []
 else:
 self.mylist = aList[:]
 def __getitem__(self, index):
 return self.mylist[index]


D:\>python
Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
  >>> from MyList import *
  >>> m=MyList([0,1,2])
  >>> m[0]
0
  >>> m[1]
1

Kent

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


Re: [Tutor] Dictionaries

2006-01-27 Thread Kent Johnson
Victor Bouffier wrote:
> Hi Alan and Ken,
> 
> I think know the difference between using items() vs. iteritems() and
> their equivalent for keys and values. I notice Ken suggests iteritems(),
> while Alan suggests items() only.
> 
> Does one approach have an advantage over the other?
> Should we use only one of them favorably?

It doesn't make much difference for small dictionaries. keys(), values() 
and items() create new lists with the specified elements. iterkeys(), 
itervalues() and iteritems() create iterators that return the specified 
elements in sequence. So for the common case of iterating over dict 
elements with a for loop, the 'iter' variants conserve memory and may be 
faster (but always check!) because of the cost of creating the list.

The iter variants are relatively new (since Python 2.2). I used to use 
the older variants in examples here so I wouldn't have to explain the 
difference :-) but ISTM that modern usage is heading to prefer the iter 
versions and I am starting to use them myself.

But I guess you will not notice any difference in performance until you 
have dicts with many thousands of elements.

Kent

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


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Bob Gailer
Bob Gailer wrote:
> Alan Gauld wrote:
>   
>> Hi Ben,
>>
>>   
>> 
>>> I want to enter the words and definitions from the  text file into the 
>>> dict.
>>> The way the text file is set up is that one  line is the word and the
>>> next line is the definition.
>>> 
>>>   
>>   
>> 
>>>  I tried using a for loop like this
>>>
>>>  f = open('glossary.txt','r')
>>>  gloss = {}
>>>
>>>  for line in f:
>>>  gloss[line] = line
>>> 
>>>   
>> The problem that you have is that you really need to read two lines at a 
>> time.
>> (Assuming that the definitions are all on one line which may not be true!)
>> A while loop may be easier in this case.
>>
>> A for loop will read each line individually. You then need to set a 
>> definition
>> flag to tell the loop body whether you are reading a definition or a key.
>>
>> Either type of loop is possible. Since you started with a for loop lets 
>> stick with it...
>>
>> definition = False
>> currentKey = None
>>
>> for line in f:
>> if isDefinition:
>>gloss[currentKey] = line
>>currentKey = None
>>isDefinition = False
>> else:
>>currentKey = line
>>isDefinition = True
>>   
>> 
> Or you can use next():
>
> for line in f:
> gloss[line] = f.next()
>   
Or even:
[gloss.setdefault(l,f.next()) for l in f]
>> If the definitions take up more than one line each then you will need to 
>> think
>> about how to identify the end of a definition - a blank line maybe? You will
>> need to append the lines to the glossary entry (rather than just assign 
>> them)
>> until the end of the definition. And you will need to update the 
>> isDefinition
>> flag at the appropriate times.
>>
>> HTH,
>>
>> Alan G
>> Author of the learn to program web tutor
>> http://www.freenetpages.co.uk/hp/alan.gauld
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>>   
>> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>   

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


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Alan Gauld
>> for line in f:
>> if isDefinition:
>>gloss[currentKey] = line
>>currentKey = None
>>isDefinition = False
>> else:
>>currentKey = line
>>isDefinition = True
>>   
> Or you can use next():
> 
> for line in f:
>gloss[line] = f.next()

Ah! Indeed you can. I'd forgotten about that neat feature of iterators. 
No longer are for loops broken when you mess around with the 
iterated item.

Good catch Bob.

Alan G.



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


[Tutor] Fwd: Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
Hello Danny

Thanks for replying to my post.
>   I tried :>>   for line in f:Thanks for your reply to my post. 


>   gloss[line] = f.readline()>
This should have worked, but there's one problem.  Whenever we're doingsomething like:for line in f:...there can be some interference between the iteration and any readline()
in the body of the loop.  For efficiency reasons, the iterator's allowedto march through the file ahead several lines at with an internal buffer.This means our position in the file might be further along than we might
realize, and that means that readline() will give nonsensical results.So we're getting caught by a low-level detail.  We should try to avoidusing both the for loop and readline() on the same file. Here's one way we
can avoid the problem:
while True:word = f.readline()defn = f.readline()if not word or not defn:   break...Does this make sense?
 It does mostly...I don't see why you need the:

 if not word or not defn:





   break











If this is so that when python iterates to the end of the file, it
knows to stop, and if that is so, then why doesn't python know it has
gotten to the end of the file without it being told?
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Fwd: Trying to enter text from a file to a Dictionary

2006-01-27 Thread Danny Yoo
> Here's one way we can avoid the problem:
>
> while True:
> word = f.readline()
> defn = f.readline()
> if not word or not defn:
>break
> ...
>
> Does this make sense?
>
>  It does mostly...I don't see why you need the:
>
>  if not word or not defn:
>break
>
> If this is so that when python iterates to the end of the file, it knows
> to stop, and if that is so, then why doesn't python know it has gotten
> to the end of the file without it being told?


Hi Ben,

Yes, that's the point: Python doesn't know when to stop.  *grin*

The way we've rewritten the loop:

while True:
...

is an "infinite" loop that doesn't stop unless something in the loop's
body does something extraordinary, like "breaking" out of the loop.
Python is much dumber than we might expect.


In more detail: Python's readline() method doesn't fail when we reach the
end of a file:  we actually start hitting the empty string.  For example:

##
>>> import StringIO
>>> sampleTextFile = StringIO.StringIO("""This is
... a sample
... text file
... """)
>>> sampleTextFile.readline()
'This is\n'
>>> sampleTextFile.readline()
'a sample\n'
>>> sampleTextFile.readline()
'text file\n'
>>> sampleTextFile.readline()
''
>>> sampleTextFile.readline()
''
##

Notice that when we hit the end of the file, readline() still continues to
run and give us empty string values.  That's why the loop above needs to
make sure it breaks out in this particular situation.


Does this make sense?  Please feel free to ask questions about this.

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


Re: [Tutor] Dictionaries

2006-01-27 Thread Alan Gauld
> their equivalent for keys and values. I notice Ken suggests iteritems(),
> while Alan suggests items() only.

I'm old fashioned and rarely use new language features until I really have
to. Kent uses the more modern idioms. I think iteritems is the preferred 
usage nowadays, but its longer to type and for most jobs has no real 
advantage.

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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


Re: [Tutor] Fwd: Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
Hi Ben,Yes, that's the point: Python doesn't know when to stop.  *grin*
The way we've rewritten the loop:while True:...is an "infinite" loop that doesn't stop unless something in the loop'sbody does something extraordinary, like "breaking" out of the loop.
Python is much dumber than we might expect.In more detail: Python's readline() method doesn't fail when we reach theend of a file:  we actually start hitting the empty string.  For example:##
>>> import StringIO>>> sampleTextFile = StringIO.StringIO("""This is... a sample... text file... """)>>> sampleTextFile.readline()'This is\n'
>>> sampleTextFile.readline()'a sample\n'>>> sampleTextFile.readline()'text file\n'>>> sampleTextFile.readline()''>>> sampleTextFile.readline()''##
Notice that when we hit the end of the file, readline() still continues torun and give us empty string values.  That's why the loop above needs tomake sure it breaks out in this particular situation.
Does this make sense?  Please feel free to ask questions about this.
Yes The  -- while true loop
--  needs something to be false or it needs to be told when to
stop. If that is correct, then it makes sense. 

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


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
On 1/27/06, Bob Gailer <[EMAIL PROTECTED]> wrote:
Bob Gailer wrote:> Alan Gauld wrote:>>> Hi Ben,> I want to enter the words and definitions from the  text file into the>>> dict.>>> The way the text file is set up is that one  line is the word and the
>>> next line is the definition.>  I tried using a for loop like this>>  f = open('glossary.txt','r')>>>  gloss = {}
>>  for line in f:>>>  gloss[line] = line The problem that you have is that you really need to read two lines at a>> time.
>> (Assuming that the definitions are all on one line which may not be true!)>> A while loop may be easier in this case. A for loop will read each line individually. You then need to set a
>> definition>> flag to tell the loop body whether you are reading a definition or a key. Either type of loop is possible. Since you started with a for loop lets>> stick with it...
 definition = False>> currentKey = None for line in f:>> if isDefinition:>>gloss[currentKey] = line>>currentKey = None
>>isDefinition = False>> else:>>currentKey = line>>isDefinition = True> Or you can use next():>> for line in f:
> gloss[line] = f.next()>Or even:[gloss.setdefault(l,f.next()) for l in f]
Hello Bob

I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] is beyond me at this point.
Thanks for your input.

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


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Bob Gailer
Ben Markwell wrote:
>
>
> On 1/27/06, *Bob Gailer* <[EMAIL PROTECTED] 
> > wrote:
>
> Bob Gailer wrote:
> > Alan Gauld wrote:
> >
> >> Hi Ben,
> >>
> >>
> >>
> >>> I want to enter the words and definitions from the  text file
> into the
> >>> dict.
> >>> The way the text file is set up is that one  line is the word
> and the
> >>> next line is the definition.
> >>>
> >>>
> >>
> >>
> >>>  I tried using a for loop like this
> >>>
> >>>  f = open('glossary.txt','r')
> >>>  gloss = {}
> >>>
> >>>  for line in f:
> >>>  gloss[line] = line
> >>>
> >>>
> >> The problem that you have is that you really need to read two
> lines at a
> >> time.
> >> (Assuming that the definitions are all on one line which may
> not be true!)
> >> A while loop may be easier in this case.
> >>
> >> A for loop will read each line individually. You then need to
> set a
> >> definition
> >> flag to tell the loop body whether you are reading a definition
> or a key.
> >>
> >> Either type of loop is possible. Since you started with a for
> loop lets
> >> stick with it...
> >>
> >> definition = False
> >> currentKey = None
> >>
> >> for line in f:
> >> if isDefinition:
> >>gloss[currentKey] = line
> >>currentKey = None
> >>isDefinition = False
> >> else:
> >>currentKey = line
> >>isDefinition = True
> >>
> >>
> > Or you can use next():
> >
> > for line in f:
> > gloss[line] = f.next()
> >
> Or even:
> [gloss.setdefault(l,f.next()) for l in f]
>
>
> Hello Bob
>
> I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] 
> is beyond me at this point.
[expr for l in f] is a "list comprehension". expr is an expression that 
may involve l.

result = [expr for l in f] # is equivalent to:

result = []
for l in f:
result.append(expr)

"list comprehension" (once understood) is often easier to read and more 
efficient than the for loop.

result = xxx.setdefault(key, newvalue) is a dictionary method that tries 
to get an item from the dictionary xxx using key. If the key is not in 
the dictionary it adds the item assigning it newvalue. Equivalent to:

if key not in xxx:
xxx[key] = newvalue
result = xxx[key]

Note that list comprehension and setdefault both return something. In my 
code the returned values are ignored. The outcome (populating a 
dictionary via a loop) is a "side effect".
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
> I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f]> is beyond me at this point.
[expr for l in f] is a "list comprehension". expr is an _expression_ thatmay involve l.result = [expr for l in f] # is equivalent to:result = []for l in f:result.append(expr)
"list comprehension" (once understood) is often easier to read and moreefficient than the for loop.result = xxx.setdefault(key, newvalue) is a dictionary method that triesto get an item from the dictionary xxx using key. If the key is not in
the dictionary it adds the item assigning it newvalue. Equivalent to:if key not in xxx:xxx[key] = newvalueresult = xxx[key]Note that list comprehension and setdefault both return something. In my
code the returned values are ignored. The outcome (populating adictionary via a loop) is a "side effect".
Thank you Bob.  This is much to think about.  I very much appreciate your concise explanation.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor