Re: [Tutor] system()? popen2()? How to execute a command save its output?

2010-09-30 Thread Chris Fuller

You might also consider pexpect.
http://pexpect.sourceforge.net/

It's designed for interactive console applications like ftp.

For popen() style access, the recommended approach is the subprocess module.  
You should be able to find an example in the docs to fit your application.
http://docs.python.org/library/subprocess.html

Cheers


On Wednesday 29 September 2010, James Hartley wrote:
 I'm needing to transfer the following shell construct to Python, plus save
 the output of execution:
 
 FTP_SITE='ftp.somesite.com'
 ftp -a  $FTP_SITE EOF
 binary
 prompt off
 cd /some_dir
 dir
 bye
 EOF
 
 Here, the FTP client accepts commands from STDIN, so all commands are saved
 in a temporary file which is redirected to the client application.
 
 I also need to save whatever output is generated.  How can this be done in
 Python?
 
 Thanks.
 
 Jim

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function error

2010-09-30 Thread roberto
On Wed, Sep 29, 2010 at 11:13 PM, Alan Gauld alan.ga...@btinternet.com wrote:

 OK, Thats a non standard error trace so presumably you are running it inside
 an IDE of some kind? It may be the IDE is masking the true error.
 What happens if you just execute the code from a shell prompt in a console
 window?  Can you send the error trace from that?


yes, the IDE is ipython2.5 for debian;
the call to the function is:
 randomMove2(10,30,15,90)

but i don't know how to call it from the bash prompt correctly, can
you point me to that ?

-- 
roberto
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system()? popen2()? How to execute a command save itsoutput?

2010-09-30 Thread Alan Gauld


James Hartley jjhart...@gmail.com wrote

I'm needing to transfer the following shell construct to Python, 
plus save

the output of execution:


Are you sure? It looks like you would be better writing a python 
program

using the ftp module. Shells are intended to execute external programs
but Python provides the tools to do the job directly from Python, with
no need to start external programs in most cases.


FTP_SITE='ftp.somesite.com'
ftp -a  $FTP_SITE EOF
binary
prompt off
cd /some_dir
dir
bye
EOF


If you really really need to use an external process use the 
subprocess module.

But first check that you can't do it from within Python.

HTH

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __import__()

2010-09-30 Thread Jojo Mwebaze
On Thu, Sep 23, 2010 at 5:26 PM, Pete pkoe...@xs4all.nl wrote:

 Hiya,

 still working on my plugin architecture. I figured out how to import
 modules of which I don't know the name yet at compile time,
 by using __import__() instead of import.

 So that works fine when I want to have the equivalent of

 import spam

 ... by using

 __import__('spam')

 Question:

 what is the equivalent of

 from spam import *


may be

function = getattr(spam, function_name)

J.


 ?

 thanks,

 Pete
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system()? popen2()? How to execute a command save its output?

2010-09-30 Thread r...@schoenian-online.de
Hi,
 
I've once written a script to sync my website with a local directory. I guess
that you will find anything you need in the FTPHelper class. Have a look at:
http://home.arcor.de/ralf_schoenian/websync/index.html At the bottom of the page
you can view and download the script.
Any questions are welcome.
Ralf



James Hartley jjhart...@gmail.com hat am 30. September 2010 um 06:29
geschrieben:


 I'm needing to transfer the following shell construct to Python, plus save the
 output of execution:
 
 FTP_SITE='ftp.somesite.com [http://ftp.somesite.com] '
 ftp -a  $FTP_SITE EOF
 binary
 prompt off
 cd /some_dir
 dir
 bye
 EOF
 
 Here, the FTP client accepts commands from STDIN, so all commands are saved in
 a temporary file which is redirected to the client application.
 
 I also need to save whatever output is generated.  How can this be done in
 Python?
 
 Thanks.
 
 Jim
 

 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] generating independent random numbers

2010-09-30 Thread Steven D'Aprano
On Thu, 30 Sep 2010 02:38:31 pm Dave Angel wrote:

[snip nearly 300 lines of quoted text and 7 lines of new content]

Dave, and Carter, are the delete and backspace keys on your keyboards 
broken?

There's no need to quote the ENTIRE thread every time you reply, and 
then quote it in full AGAIN a handful of minutes later.

Please trim your quoting to only show the relevant parts of the email 
that you are actually replying to, or to show context. Nobody wants to 
have to scroll past pages upon pages of quoted text that we've already 
read four or five times to get to your reply.


Thank you.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function error

2010-09-30 Thread ALAN GAULD
Copy the code into a text file with a name ending in .py - lets call it 
myfile.py for now
(if you have not already done so)

From a bash prompt type

$ python myfile.py

Then cut n paste any error messages into an email to the list

 
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/




- Original Message 
 From: roberto robert...@gmail.com
 To: Alan Gauld alan.ga...@btinternet.com
 Cc: tutor@python.org
 Sent: Thursday, 30 September, 2010 10:02:51
 Subject: Re: [Tutor] function error
 
 On Wed, Sep 29, 2010 at 11:13 PM, Alan Gauld alan.ga...@btinternet.com  
wrote:
 
  OK, Thats a non standard error trace so presumably you  are running it 
inside
  an IDE of some kind? It may be the IDE is masking  the true error.
  What happens if you just execute the code from a shell  prompt in a console
  window?  Can you send the error trace from  that?
 
 
 yes, the IDE is ipython2.5 for debian;
 the call to the  function is:
  randomMove2(10,30,15,90)
 
 but i don't know how to  call it from the bash prompt correctly, can
 you point me to that ?
 
 -- 
 roberto
 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Printing prime numbers

2010-09-30 Thread delegbede
Hi all,
I am trying to write a function that prints out which number is prime in range 
(1,500)
The function would check thru and the print out something like
1 is prime
2 is prime
3 is prime
4 is not
5 is prime

Please help me.
Thank you.
Sent from my BlackBerry wireless device from MTN
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing prime numbers

2010-09-30 Thread Shashwat Anand
On Thu, Sep 30, 2010 at 5:27 PM, delegb...@dudupay.com wrote:

 Hi all,
 I am trying to write a function that prints out which number is prime in
 range (1,500)
 The function would check thru and the print out something like
 1 is prime
 2 is prime
 3 is prime
 4 is not
 5 is prime

 Please help me.
 Thank you.


Can you show us your attempts.
We may try to help where you did wrong.



 Sent from my BlackBerry wireless device from MTN
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
~l0nwlf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing prime numbers

2010-09-30 Thread delegbede
Ok. I will do that as soon As I get back to my workstation.
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: Shashwat Anand anand.shash...@gmail.com
Date: Thu, 30 Sep 2010 19:11:33 
To: delegb...@dudupay.com
Cc: tutor@python.org
Subject: Re: [Tutor] Printing prime numbers

On Thu, Sep 30, 2010 at 5:27 PM, delegb...@dudupay.com wrote:

 Hi all,
 I am trying to write a function that prints out which number is prime in
 range (1,500)
 The function would check thru and the print out something like
 1 is prime
 2 is prime
 3 is prime
 4 is not
 5 is prime

 Please help me.
 Thank you.


Can you show us your attempts.
We may try to help where you did wrong.



 Sent from my BlackBerry wireless device from MTN
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
~l0nwlf

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing prime numbers

2010-09-30 Thread Emmanuel Ruellan
On Thu, Sep 30, 2010 at 1:57 PM, delegb...@dudupay.com wrote:


 1 is prime


One is /not/ prime. /pedant
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system()? popen2()? How to execute a command save itsoutput?

2010-09-30 Thread R. Alan Monroe

 I'm needing to transfer the following shell construct to Python, 
 plus save
 the output of execution:

 FTP_SITE='ftp.somesite.com'
 ftp -a  $FTP_SITE EOF
 binary
 prompt off
 cd /some_dir
 dir
 bye
 EOF

 Are you sure? It looks like you would be better writing a python
 program
 using the ftp module. Shells are intended to execute external programs
 but Python provides the tools to do the job directly from Python, with
 no need to start external programs in most cases.

NB: If you use the ftp module (which works great), be sure to open all
files in Binary mode. Voice of experience here.

Alan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Doubly linked list

2010-09-30 Thread T MURPHY
I was having trouble, where on the python site can i find steps on classes and 
making a doubly linked list, is there a help option for linked lists.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] system()? popen2()? How to execute a command save itsoutput?

2010-09-30 Thread James Hartley
On Thu, Sep 30, 2010 at 7:27 AM, R. Alan Monroe amon...@columbus.rr.comwrote:


  I'm needing to transfer the following shell construct to Python,
  plus save
  the output of execution:

  FTP_SITE='ftp.somesite.com'
  ftp -a  $FTP_SITE EOF
  binary
  prompt off
  cd /some_dir
  dir
  bye
  EOF

 NB: If you use the ftp module (which works great), be sure to open all
 files in Binary mode. Voice of experience here.


Thanks all, for the responses thus far.  I was not aware of the ftplib
module.  This looks like it will take care of most of my needs.

However, output from these FTP commands are sent to stdout.  Is there a way
to redirect/capture stdout, as I need to parse the directory listings?

Thanks, again.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Runnig a windows.exe from python

2010-09-30 Thread Susana Iraiis Delgado Rodriguez
Hello !

I apoligize for the format of my last message, I didn't realize that putting
my text in bold format will show those asterisks.
By the way you're Alan, for the pythom module I first had to read my
arguments and passed them to the os.system(), it worked. Now when I execute
this command, in my normal DOS Windows, I must change to another path before
I run the .exe, I don't know how to tell this to my python module. This is
my code:

from dbf import *
from osgeo import ogr
import os
import sys
def call():
  os.chdir('C:\Python26')
  arg1 = R1G-GEODESIA2.shp
  arg2 = LAYER = 'R1G-GEODESIA'
  arg4 = tapalpa_05_plani_point.shp
  os.system('C:/Archivos de programa/FWTools2.4.7/setfw')
  os.system('C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe'+ 
+arg1 + + -where + + arg3 +  +arg4)
call()

If I run it, it shows me the following error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import fw
Ingresa el nombre para el nuevo mapa
R1G-GEODESIA2.shp
Ingresa la condicion
LAYER = 'R1G-GEODESIA'
Ingresa el nombre del mapa original
tapalpa_05_plani_point.shp
FAILURE:
Unable to open datasource `arg3' with the following drivers.
  - ESRI Shapefile
  - MapInfo File
  - UK .NTF
  - SDTS
  - TIGER
  - S57
  - DGN
  - VRT
  - REC
  - Memory
  - BNA
  - CSV
  - NAS
  - GML
  - GPX
  - KML
  - GeoJSON
  - Interlis 1
  - Interlis 2
  - GMT
  - SQLite
  - ODBC
  - PGeo
  - OGDI
  - PostgreSQL
  - MySQL
  - XPlane
  - AVCBin
  - AVCE00
  - DXF
  - Geoconcept
  - GeoRSS
  - GPSTrackMaker
  - VFK

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] inheritance problem

2010-09-30 Thread Roelof Wobben

hello, 

Im following this page : 
http://openbookproject.net/thinkcs/python/english2e/ch17.html

So i have this programm now : 
class Card:
suits = [Clubs, Diamonds, Hearts, Spades]
ranks = [narf, Ace, 2, 3, 4, 5, 6, 7,
 8, 9, 10, Jack, Queen, King]
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
def __str__(self):
return (self.ranks[self.rank] +  of  + self.suits[self.suit])
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))

def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty(): break   # break if out of cards
card = self.pop()   # take the top card
hand = hands[i % num_hands] # whose turn is next?
hand.add(card)  # add the card to the hand

def shuffle(self):
import random
num_cards = len(self.cards)
for i in range(num_cards):
j = random.randrange(i, num_cards)
self.cards[i], self.cards[j] = self.cards[j], self.cards[i]

def remove(self, card):
if card in self.cards:
self.cards.remove(card)
return True
else:
return False
def is_empty(self):
return (len(self.cards) == 0)
class Hand(Deck):
def __init__(self, name=):
   self.cards = []
   self.name = name
def add(self,card):
self.cards.append(card)
def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty(): break   # break if out of cards
card = self.pop()   # take the top card
hand = hands[i % num_hands] # whose turn is next?
hand.add(card)  # add the card to the hand
class CardGame:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()

class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print Hand %s: %s matches %s % (self.name, card, match)
count = count + 1
return count
class OldMaidGame(CardGame):
def play(self, names):
# remove Queen of Clubs
self.deck.remove(Card(0,12))
# make a hand for each player
self.hands = []
for name in names:
self.hands.append(OldMaidHand(name))
# deal the cards
self.deck.deal(self.hands)
print -- Cards have been dealt
self.printHands()
# remove initial matches
matches = self.removeAllMatches()
print -- Matches discarded, play begins
self.printHands()
# play until all 50 cards are matched
turn = 0
numHands = len(self.hands)
while matches  25:
matches = matches + self.playOneTurn(turn)
turn = (turn + 1) % numHands
print -- Game is Over
self.printHands()
def remove_all_matches(self):
count = 0
for hand in self.hands:
count = count + hand.remove_matches()
return count
def find_neighbor(self, i):
numHands = len(self.hands)
for next in range(1,numHands):
neighbor = (i + next) % numHands
if not self.hands[neighbor].is_empty():
return neighbor

game = CardGame()
hand = OldMaidHand(frank)
deck = Deck()
game.deck.deal([hand], 13)
OldMaidHand.print_hands() 
 
But now Im getting this error message:
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126, in module
game.deck.deal([hand], 13)
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24, in deal
card = self.pop()   # take the top card
AttributeError: Deck instance has no attribute 'pop'

 
What went wrong here.
 
Roelof
 
 
 
 

 
 

 

 



 
 
 



  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-09-30 Thread Evert Rol
  Hi Roelof,

 Im following this page : 
 http://openbookproject.net/thinkcs/python/english2e/ch17.html

I just checked this, and it appears you've copied this example fine.

snip /

 class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))
 
def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty(): break   # break if out of cards
card = self.pop()   # take the top card
hand = hands[i % num_hands] # whose turn is next?
hand.add(card)  # add the card to the hand

snip /

 game = CardGame()
 hand = OldMaidHand(frank)
 deck = Deck()
 game.deck.deal([hand], 13)
 OldMaidHand.print_hands() 
 
 But now Im getting this error message:
 
 Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126, in 
 module
game.deck.deal([hand], 13)
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24, in deal
card = self.pop()   # take the top card
 AttributeError: Deck instance has no attribute 'pop'
 
 What went wrong here.

The error message tells you exactly what is wrong: there is no 'pop' attribute. 
Or in this case, rather there is no pop() method for the class Deck.
You're calling it as self.pop() within Deck, hence Deck should provide a pop 
method (the self refers to any instance of Deck that you're currently using). 
But pop() is nowhere defined...

Now, the commentary in the exercise says a card is removed from the deck using 
the list method pop, which would suggest self is of type(list). Since self is 
also of type(Deck), Deck should inherit from list: class Deck(list).
Thus, in my view, the example is broken, and simply not well tested. Hence I 
said you copied it fine, and nothing went wrong there.

Seen the rest of the example, I actually suspect that inheriting from standard 
Python types is not yet discussed here, and will be done later. So inheriting 
from list is one option, but may not be right in the context of this exercise. 
Writing your own pop() method for Deck is another option.

And, since this is an openbookproject, I would expect that means you can edit 
it yourself. That doesn't appear to be directly the case, but you could at 
least notify the authors (bottom of page) and let them know that you think this 
example is broken (feel free to refer them to this thread in the mailing list). 
Unless of course, there was some example done before this chapter that provided 
a pop() method.

  Evert

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-09-30 Thread Bob Gailer
Sorry I hit the send button instead of the save button

On Thu, Sep 30, 2010 at 2:58 PM, Bob Gailer bgai...@gmail.com wrote:
 On Thu, Sep 30, 2010 at 2:38 PM, Roelof Wobben rwob...@hotmail.com wrote:

 hello,

 Im following this page : 
 http://openbookproject.net/thinkcs/python/english2e/ch17.html

 [snip]

 What went wrong here.

 IMHO you are tackling a very large program while still not getting
Python basics and still not walking through the program

I once again am weary of holding your hand.

I suggest (again) that you walk through the program BY HAND step by
step, analyzing and understanding what happens at each step.

There are so many problems in your code even if I told you exactly
what's wrong you will just get the next error-or-unexpected result
then the next, and so on.

I will start you:

game = CardGame()
# leads to
class CardGame:
   def __init__(self):
   self.deck = Deck()
#leads to
class Deck:
   def __init__(self):
   self.cards = [] # an empty list is bound to the instance
attribute cards
   for suit in range(4):
   for rank in range(1, 14):
   self.cards.append(Card(suit, rank)) # one-by-one Card
instances are appended to self.cards
#leads to
 class Card:
   suits = [Clubs, Diamonds, Hearts, Spades] # a list of suit
names is bound to class attribute suits
   ranks = [narf, Ace, 2, 3, 4, 5, 6, 7,
8, 9, 10, Jack, Queen, King] # a list of rank
names is bound to class attribute ranks
   def __init__(self, suit=0, rank=0):
   self.suit = suit # the suit number passed as an argument is
bound to the Card instance suit
   self.rank = rank # the rank number passed as an argument is
bound to the Card instance rank
   # the result is a Card instance with two attributes, suit and rank.

And so forth. Laborious? Time consuming? Lots of detail? Yes. Most of
us have gone thru the same thing in our education.

Regarding the error:

AttributeError: Deck instance has no attribute 'pop'

You should be able by now to know what that means and why it is happening.

A lot of us on this list are spending a lot of time helping you. I
for one again am imploring you to spend more time gaining
understanding and asking us for less help of this nature.

Others may disagree - that is my opinion.

-- 
Bob Gailer
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubly linked list

2010-09-30 Thread Emile van Sebille

On 9/30/2010 6:24 AM T MURPHY said...

I was having trouble, where on the python site can i find steps on classes and 
making a doubly linked list, is there a help option for linked lists.


Python itself doesn't provide a doubly linked list so I wouldn't expect 
to find support ifo on the python site therefore, but google yields 
multiple hits some of which appear to provide working classes providing 
doubly linked lists.  See for example 
http://bytes.com/topic/python/answers/523772-how-implement-linked-list-python 
but if you're new to python but not to programming you'll find a lot of 
useful info working the tutorial.


HTH,

Emile





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (de)serialization questions

2010-09-30 Thread Albert-Jan Roskam
Hi,

I have data about zip codes, street and city names (and perhaps later also of 
street numbers). I made a dictionary of the form {zipcode: (street, city)}
I dumped the dictionary into a marshal file. I have two questions:

The first question is a very basic one: if I deserialize the dictionary it is 
placed into memory. This is fast, but can cause problems for very large 
objects. 
Are there forms of object permanence that do not read all data into memory? 
Does 
the shelve module work this way?

Second, does anybody know of a speed comparison test (e.g., web source) of 
various de/serialization methods? I don't mind if the dumping is somewhat slow. 
Fast loading speed is more important for my purpose.

Btw, I am aware of the portability problems of marshal files. I found that, 
compared to a shelve object, dumping is *much* faster,  loading is slightly 
faster,  look-ups are scarily fast, and file size is about half. 


 
I am using Python 2.5 and installing non-standard modules is a problem for the 
IT droids in my office.

Cheers!!
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the 
Romans ever done for us?
~~



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-09-30 Thread Albert-Jan Roskam

 And so forth. Laborious? Time consuming? Lots of detail? Yes. Most of
 us have gone thru the same thing in our education.

 
--- You forgot: 'Lots of frowning', 'lots of sixpacks' and 'lots of FUN' ;-)))


Cheers!!
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have 
the 
Romans ever done for us?
~~





From: Bob Gailer bgai...@gmail.com
To: Roelof Wobben rwob...@hotmail.com; tutor@python.org
Sent: Thu, September 30, 2010 9:12:48 PM
Subject: Re: [Tutor] inheritance problem

Sorry I hit the send button instead of the save button

On Thu, Sep 30, 2010 at 2:58 PM, Bob Gailer bgai...@gmail.com wrote:
 On Thu, Sep 30, 2010 at 2:38 PM, Roelof Wobben rwob...@hotmail.com wrote:

 hello,

 Im following this page : 
http://openbookproject.net/thinkcs/python/english2e/ch17.html

 [snip]

 What went wrong here.

IMHO you are tackling a very large program while still not getting
Python basics and still not walking through the program

I once again am weary of holding your hand.

I suggest (again) that you walk through the program BY HAND step by
step, analyzing and understanding what happens at each step.

There are so many problems in your code even if I told you exactly
what's wrong you will just get the next error-or-unexpected result
then the next, and so on.

I will start you:

game = CardGame()
# leads to
class CardGame:
   def __init__(self):
   self.deck = Deck()
#leads to
class Deck:
   def __init__(self):
   self.cards = [] # an empty list is bound to the instance
attribute cards
   for suit in range(4):
   for rank in range(1, 14):
   self.cards.append(Card(suit, rank)) # one-by-one Card
instances are appended to self.cards
#leads to
class Card:
   suits = [Clubs, Diamonds, Hearts, Spades] # a list of suit
names is bound to class attribute suits
   ranks = [narf, Ace, 2, 3, 4, 5, 6, 7,
8, 9, 10, Jack, Queen, King] # a list of rank
names is bound to class attribute ranks
   def __init__(self, suit=0, rank=0):
   self.suit = suit # the suit number passed as an argument is
bound to the Card instance suit
   self.rank = rank # the rank number passed as an argument is
bound to the Card instance rank
   # the result is a Card instance with two attributes, suit and rank.

And so forth. Laborious? Time consuming? Lots of detail? Yes. Most of
us have gone thru the same thing in our education.

Regarding the error:

AttributeError: Deck instance has no attribute 'pop'

You should be able by now to know what that means and why it is happening.

A lot of us on this list are spending a lot of time helping you. I
for one again am imploring you to spend more time gaining
understanding and asking us for less help of this nature.

Others may disagree - that is my opinion.

-- 
Bob Gailer
919-636-4239
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-09-30 Thread Joel Goldstick
I looked at the chapter before, and found this in particular:

class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))

I think the error in the book has to do with self.pop() instead should
be self.cards.pop()

Since cards are the items in the deck that get moved around, and since
you are dealing at that
line in your code that fails.




 --
 Bob Gailer
 919-636-4239
 ___
 Tutor maillist  -  tu...@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubly linked list

2010-09-30 Thread Alan Gauld


T MURPHY t...@hotmail.com wrote 

I was having trouble, where on the python site can i find steps 
on classes and making a doubly linked list, is there a help 
option for linked lists.


Thee are several sites that discuss list structures in Python, 
but mostly these are of academic interest only.


Do you have a specific need for a doubly linked lists? They 
are very rarely required in Python because the standard list 
is sufficiently versatile for most purposes.


HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
Hi all,
I have a parser class which is supposed to take a text file and parse
it. I will then do more with the resulting data. The file is in a
particular format, specified by my professor, though this is not
homework (it will be used to do homework later). The file is in the
format:
l
vx vy z
vx vy z

where l is either D or U and x, y, and z are numbers. Anyway, I have
the following lines:
  f=open(self.file, r)
  self.original=f.read() #I thought self.original would now be a
string of all the data in self.file
  txt=str(self.original).split(r\n+) #create an array where elements
are lines in file
  print txt

I fully expected to see txt be an array of strings since I figured
self.original would have been split on one or more new lines. It turns
out, though, that I get this instead:
['l\nvx vy z\nvx vy z']

How is it that txt is not an array of the lines in the file, but
instead still holds \n characters? I thought the manual said read()
returns a string:

To read a file's contents, call  f.read(size), which reads some
quantity of data and returns it as a string. size is an optional
numeric argument. When size is omitted or negative, the entire
contents of the file will be read and returned; it's your problem if
the file is twice as large as your machine's memory. Otherwise, at
most size bytes are read and returned. If the end of the file has been
reached, f.read()
 will return an empty string ( ). 

I know I can use f.readline(), and I was doing that before and it all
worked fine. However, I saw that I was reading the file twice and, in
the interest of good practice if I ever have this sort of project with
a huge file, I thought I would try to be more efficient and read it
once. I will use self.original later again, so I need it either way,
and I figured I could use it since I had already read the file to get
it. TIA.



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] python Task

2010-09-30 Thread Dipo Elegbede
Kindly help me with the following tasks.
You may want to start with explanations for me and then pseudo-codes,
I should be able to take it from there.
They are exercises from deitel how to program for Python.
I have done a lot of thinking and its almost discouraging me. Please help.
Thanks.


4.4 An integer greater than 1 is said to be prime if it is divisible
by only 1 and itself. For example,
2, 3, 5 and 7 are prime numbers, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a program that determines and prints all the
prime numbers between 2 and 1,000.
c) Initially, you might think that n/2 is the upper limit for which
you must test to see whether a number is prime, but you need go only
as high as the square root of n. Rewrite the program and run it both
ways to show that you get the same result.

4.5 An integer number is said to be a perfect number if the sum of its
factors, including 1 (but not the number itself), is equal to the
number. For example, 6 is a perfect number, because 6 = 1 + 2
+ 3. Write a function perfect that determines whether parameter number
is a perfect number. Use this function in a program that determines
and prints all the perfect numbers between 1 and 1000.
Print the factors of each perfect number to confirm that the number is
indeed perfect. Challenge the power of your computer by testing
numbers much larger than 1000.

4.7 Write a program that plays the game of “guess the number” as
follows: Your program chooses the number to be guessed by selecting an
integer at random in the range 1 to 1000. The program then displays
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess.
The player then types a first guess. The program responds with one of
the following:
1. Excellent! You guessed the number!
Would you like to play again (y or n)?
2. Too low. Try again.
3. Too high. Try again.
If the player's guess is incorrect, your program should loop until the
player finally gets the number right. Your program should keep telling
the player Too high or Too low to help the player “zero in” on the
correct answer. After a game ends, the program should prompt the user
to enter y to play again or n to exit the game.

4.8 (Towers of Hanoi) Every budding computer scientist must grapple
with certain classic problems.
The Towers of Hanoi (see Fig. 4.23) is one of the most famous of
these. Legend has it that, in a temple in the Far East, priests are
attempting to move a stack of disks from one peg to another. The
initial stack had 64 disks threaded onto one peg and arranged from
bottom to top by decreasing size.
The priests are attempting to move the stack from this peg to a second
peg, under the constraints that exactly one disk is moved at a time
and that at no time may a larger disk be placed above a smaller disk.
A third peg is available for holding disks temporarily. Supposedly,
the world will end when the priests complete their task, so there is
little incentive for us to facilitate their efforts.
Let us assume that the priests are attempting to move the disks from
peg 1 to peg 3. We wish to develop an algorithm that will print the
precise sequence of peg-to-peg disk transfers.
If we were to approach this problem with conventional methods, we
would rapidly find ourselves hopelessly knotted up in managing the
disks. Instead, if we attack the problem with recursion in mind, it
immediately becomes tractable. Moving n disks can be viewed in terms
of moving only n - 1 disks (hence, the recursion), as follows:
a) Move n - 1 disks from peg 1 to peg 2, using peg 3 as a temporary
holding area.
b) Move the last disk (the largest) from peg 1 to peg 3.
c) Move the n - 1 disks from peg 2 to peg 3, using peg 1 as a
temporary holding area.
The process ends when the last task involves moving n = 1 disk, i.e.,
the base case. This is accomplished trivially by moving the disk
without the need for a temporary holding area.
Write a program to solve the Towers of Hanoi problem. Use a recursive
function with four
parameters:
a) The number of disks to be moved
b) The peg on which these disks are initially threaded
c) The peg to which this stack of disks is to be moved
d) The peg to be used as a temporary holding area
Your program should print the precise instructions it will take to
move the disks from the starting peg to the destination peg. For
example, to move a stack of three disks from peg 1 to peg 3, your
program should print the following series of moves:
1 → 3 (This means move one disk from peg 1 to peg 3.)
1 → 2
3 → 2
1 → 3
2 → 1
2→ 3
1→ 3

-- 
Sent from my mobile device

Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (de)serialization questions

2010-09-30 Thread Lee Harr

 I have data about zip codes, street and city names (and perhaps later also of
 street numbers). I made a dictionary of the form {zipcode: (street, city)}

One dictionary with all of the data?

That does not seem like it will work. What happens when
2 addresses have the same zip code?


 Are there forms of object permanence that do not read all data into memory?

How about a file?

You could write your data one record per line, and then
read it in one line at a time also.



You could also use a csv file, or maybe use a database
like sqlite.

  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
On 9/30/10, Walter Prins wpr...@gmail.com wrote:
 On 30 September 2010 23:32, Alex Hall mehg...@gmail.com wrote:

 txt=str(self.original).split(r\n+) #create an array where elements


 OK, consider this Python shell session:

 s = line1\nline2
 s.split()
 ['line1', 'line2']
 s.split(r\n+)
 ['line1\nline2']

 Hmm, so split doesn't like that seperator.

 Taking a step back -- It looks like you're trying to specify a regular
 expression as a split string.  A string object's split method doesn't
 support regular expressions.  The split function in the re module however
 does.
Ah-ha!!
re.split(r\n+, self.original)
That did it, and my program once again runs as expected. Thanks!

 HTH
Very much.

 Walter

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Steve Willoughby

On 30-Sep-10 15:49, Alex Hall wrote:

re.split(r\n+, self.original)
That did it, and my program once again runs as expected. Thanks!


If you don't need blank lines stripped out (r'\n+' considers multiple 
consecutive \n characters to be a single record separator), you can 
avoid the regex and just use the normal string split:


list_of_lines = giant_string.split('\n')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help - server health check reporter

2010-09-30 Thread Russell Smith
Hey guys,



I’m trying to put together a script using urllib2, smtplib and
stripogram/html2text which will use a healthcheck url, read the response
after loading it and then email me the results without any unwanted html
tags. I was able to do that but, when I get a timeout on one of the servers
the script breaks with an error response. I’m very new to python and I don’t
know how to take that error and have it sent as well, instead of breaking
the script. Any advice or links I can check out that might be helpful? I
appreciate it.


I can include the python code if needed though at this point I'm sure it is
not very pythonic. {smile}


Regards,

-russ
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help - server health check reporter

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 09:26:16 am Russell Smith wrote:

 I’m trying to put together a script using urllib2, smtplib and
 stripogram/html2text which will use a healthcheck url, read the
 response after loading it and then email me the results without any
 unwanted html tags. I was able to do that but, when I get a timeout
 on one of the servers the script breaks with an error response. 

Could you copy and paste the exact error message, including the full 
traceback?

Also, what version of Python are you using?

 I’m 
 very new to python and I don’t know how to take that error and have
 it sent as well, instead of breaking the script. Any advice or links
 I can check out that might be helpful? I appreciate it.

try:
code that times out goes here
except Exception as error:
do something with error


Obviously this isn't exactly Python code, but I can be more specific 
once you've answered the above two questions.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python Task

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 08:38:31 am Dipo Elegbede wrote:

 4.4 An integer greater than 1 is said to be prime if it is divisible
 by only 1 and itself. For example,
 2, 3, 5 and 7 are prime numbers, but 4, 6, 8 and 9 are not.
 a) Write a function that determines whether a number is prime.

The first thing you need to know is that you can find out the remainder 
after division by using the % operator. For example:

10 % 5 = 0  # 10 = 5*2
11 % 5 = 1  # 11 = 5*2 + 1
12 % 5 = 2  # 12 = 5*2 + 2

and so forth.


So you can check whether a number is divisible by another with:

if n % divisor == 0:
print n is exactly divisible by divisor
else:
print n is not divisible by divisor


So to find out whether a number n is prime, you need to check whether it 
is divisible by each whole number starting from 2:

for divisor in range(2, n):
if n is divisible by divisor then n is not prime
# outside the loop
print prime


The above does a LOT of unnecessary work. Some improvements:

* Once you've discovered that a number is not prime, you can 
  exit the loop.
* There's no need to test every number up to n-1. Think about
  what the greatest number you need to test would be.
* If a number isn't divisible by 2, then it can't possibly be
  divisible by 4, 6, 8, 10, ... either. So apart from 2, there's
  no need to check even numbers.




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 08:49:31 am Alex Hall wrote:

 Ah-ha!!
 re.split(r\n+, self.original)
 That did it, and my program once again runs as expected. Thanks!

There is no need to crack that tiny peanut with the 40 lb sledgehammer 
of a regular expression.

list_of_lines = string.split('\n')

Much faster, simpler, and does the job. To get rid of empty lines:

list_of_lines = filter(None, string.split('\n'))




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-09-30 Thread Alan Gauld

Roelof Wobben rwob...@hotmail.com wrote


So i have this programm now :



class Deck:
   def __init__(self):
   self.cards = []
   for suit in range(4):
   for rank in range(1, 14):
   self.cards.append(Card(suit, rank))

   def deal(self, hands, num_cards=999):
   num_hands = len(hands)
   for i in range(num_cards):
   if self.is_empty(): break   # break if out of cards
   card = self.pop()   # take the top card
   hand = hands[i % num_hands] # whose turn is next?
   hand.add(card)  # add the card to the hand

   def shuffle(self):
   import random
   num_cards = len(self.cards)
   for i in range(num_cards):
   j = random.randrange(i, num_cards)
   self.cards[i], self.cards[j] = self.cards[j], 
self.cards[i]


   def remove(self, card):
   if card in self.cards:
   self.cards.remove(card)
   return True
   else:
   return False
   def is_empty(self):
   return (len(self.cards) == 0)



But now Im getting this error message:

Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126, 
in module

   game.deck.deal([hand], 13)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24, 
in deal

   card = self.pop()   # take the top card
AttributeError: Deck instance has no attribute 'pop'


What went wrong here.


The error tells you what is wrong, the Deck has no attribute called 
pop.

Can you see a pop anywhere?

So if the code you copied has an error how should it assign a card?
Where are the cards stored? How would you get the first card from
the collection? Does that work?

Think about what the error is telling you and think about how you
would fix it. If you don't understand what the error is saying then 
tell

us and we can explain it, but in this case its pretty clearly stated
and is one you have seen before.

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 08:32:40 am Alex Hall wrote:

 I fully expected to see txt be an array of strings since I figured
 self.original would have been split on one or more new lines. It
 turns out, though, that I get this instead:
 ['l\nvx vy z\nvx vy z']

There's no need to call str() on something that already is a string. 
Admittedly it doesn't do much harm, but it is confusing for the person 
reading, who may be fooled into thinking that perhaps the argument 
wasn't a string in the first place.

The string split method doesn't interpret its argument as a regular 
expression. r'\n+' has no special meaning here. It's just three literal 
characters backslash, the letter n, and the plus sign. split() tries to 
split on that substring, and since your data doesn't include that 
combination anywhere, returns a list containing a single item:

 abcde.split(ZZZ)
['abcde']



 How is it that txt is not an array of the lines in the file, but
 instead still holds \n characters? I thought the manual said read()
 returns a string:

It does return a string. It is a string including the newline 
characters.


[...]
 I know I can use f.readline(), and I was doing that before and it all
 worked fine. However, I saw that I was reading the file twice and, in
 the interest of good practice if I ever have this sort of project
 with a huge file, I thought I would try to be more efficient and read
 it once.

You think that keeping a huge file in memory *all the time* is more 
efficient? It's the other way around -- when dealing with *small* files 
you can afford to keep it in memory. When dealing with huge files, you 
need to re-write your program to deal with the file a piece at a time. 
(This is often a good strategy for small files as well, but it is 
essential for huge ones.)

Of course, small and huge is relative to the technology of the day. 
I remember when 1MB was huge. These days, huge would mean gigabytes. 
Small would be anything under a few tens of megabytes.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Runnig a windows.exe from python

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 04:05:08 am Susana Iraiis Delgado Rodriguez wrote:
 Hello !

 I apoligize for the format of my last message, I didn't realize that
 putting my text in bold format will show those asterisks.
 By the way you're Alan, for the pythom module I first had to read my
 arguments and passed them to the os.system(), it worked. Now when I
 execute this command, in my normal DOS Windows, I must change to
 another path before I run the .exe, I don't know how to tell this to
 my python module. 

os.chrdir(path)

changes to a new path.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Doubly linked list

2010-09-30 Thread Steven D'Aprano
On Thu, 30 Sep 2010 11:24:06 pm T MURPHY wrote:
 I was having trouble, where on the python site can i find steps on
 classes 

Google is your friend: googling for python tutorial brings up lots of 
tutorials that will help. Here's the first one:

http://docs.python.org/tutorial/

 and making a doubly linked list, is there a help option for 
 linked lists.

Python doesn't supply a doubly-linked list, but it's easy to make your 
own. Here's a singly-linked list for you:

class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next


mylist = Node(a)
mylist.next = Node(b, Node(c))

node = mylist
while node is not None:
print node.data
node = node.next


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing prime numbers

2010-09-30 Thread Steven D'Aprano
On Thu, 30 Sep 2010 11:52:49 pm Emmanuel Ruellan wrote:
 On Thu, Sep 30, 2010 at 1:57 PM, delegb...@dudupay.com wrote:
  1 is prime

 One is /not/ prime. /pedant

There's no need to apologize for pedantry. Saying that one is prime is 
like saying that 2 is an odd number, or that glass is a type of meat.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Mutable Properties

2010-09-30 Thread Chris King

 Dear Tutors,
I noticed that when you make a property to represent a mutable value

*class Obj(object):
def get(self):
print 'Get'
return self.prop
def set(self, new):
print 'Set'
self.prop = new
prop = property(get, set)

test = Obj()
test.prop = ['Hello']
*
and then try and use one of its methods.

*test.prop.append('World')

*It will treat it as a get, not a set.

*Output: Get

*Even thou you are basically changing its value.

*Before: ['Hello']
After: ['Hello', 'World']

*I know this happens because I'm not technically setting it to something 
else, just getting one of its properties.

I was wondering how to make it fire off set to for certain methods.

Sincerely,
Me
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable Properties

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 10:24:50 am Chris King wrote:
   Dear Tutors,
  I noticed that when you make a property to represent a mutable
 value

 *class Obj(object):
  def get(self):
  print 'Get'
  return self.prop
  def set(self, new):
  print 'Set'
  self.prop = new
  prop = property(get, set)

 test = Obj()
 test.prop = ['Hello']
 *
 and then try and use one of its methods.

 *test.prop.append('World')

 *It will treat it as a get, not a set.

That's because it is a get. You get the property, and then you call one 
of its methods. How could it be any different?

The object stored in the property could be anything. How can the class 
know which methods modify it in place, and which ones don't?

test.prop.sort()

Did this modify the list or not?


 *Output: Get

 *Even thou you are basically changing its value.

But changing a mutable value means modifying it in place, not 
re-assigning it. This is no different from:

mylist = test.prop  # this is a get
mylist.append(something)  # change it in place

Since there is no assignment to prop, there is no set.



 *Before: ['Hello']
 After: ['Hello', 'World']

 *I know this happens because I'm not technically setting it to
 something else, just getting one of its properties.
 I was wondering how to make it fire off set to for certain methods.


You can't. 

What problem are you trying to solve? There is likely another way to 
solve it. (Not necessarily an easy way, but we'll see.)



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable Properties

2010-09-30 Thread Chris King

 On 9/30/2010 8:43 PM, Steven D'Aprano wrote:

On Fri, 1 Oct 2010 10:24:50 am Chris King wrote:

   Dear Tutors,
  I noticed that when you make a property to represent a mutable
value

*class Obj(object):
  def get(self):
  print 'Get'
  return self.prop
  def set(self, new):
  print 'Set'
  self.prop = new
  prop = property(get, set)

test = Obj()
test.prop = ['Hello']
*
and then try and use one of its methods.

*test.prop.append('World')

*It will treat it as a get, not a set.

That's because it is a get. You get the property, and then you call one
of its methods. How could it be any different?

The object stored in the property could be anything. How can the class
know which methods modify it in place, and which ones don't?

test.prop.sort()

Did this modify the list or not?



*Output: Get

*Even thou you are basically changing its value.

But changing a mutable value means modifying it in place, not
re-assigning it. This is no different from:

mylist = test.prop  # this is a get
mylist.append(something)  # change it in place

Since there is no assignment to prop, there is no set.




*Before: ['Hello']
After: ['Hello', 'World']

*I know this happens because I'm not technically setting it to
something else, just getting one of its properties.
I was wondering how to make it fire off set to for certain methods.


You can't.

What problem are you trying to solve? There is likely another way to
solve it. (Not necessarily an easy way, but we'll see.)



So I'll have to create my own object which modifies each method to fire 
off the set method if the old form and the new form are unequal, there 
is no easy way?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] just what does read() return?

2010-09-30 Thread Alex Hall
On 9/30/10, Steven D'Aprano st...@pearwood.info wrote:
 On Fri, 1 Oct 2010 08:32:40 am Alex Hall wrote:

 I fully expected to see txt be an array of strings since I figured
 self.original would have been split on one or more new lines. It
 turns out, though, that I get this instead:
 ['l\nvx vy z\nvx vy z']

 There's no need to call str() on something that already is a string.
 Admittedly it doesn't do much harm, but it is confusing for the person
 reading, who may be fooled into thinking that perhaps the argument
 wasn't a string in the first place.
Agreed. I was having some (unrelated) trouble and was desperate enough
to start forcing things to the data type I needed, just in case.

 The string split method doesn't interpret its argument as a regular
 expression. r'\n+' has no special meaning here. It's just three literal
 characters backslash, the letter n, and the plus sign. split() tries to
 split on that substring, and since your data doesn't include that
 combination anywhere, returns a list containing a single item:

 abcde.split(ZZZ)
 ['abcde']
Yes, that makes sense.

 How is it that txt is not an array of the lines in the file, but
 instead still holds \n characters? I thought the manual said read()
 returns a string:

 It does return a string. It is a string including the newline
 characters.


 [...]
 I know I can use f.readline(), and I was doing that before and it all
 worked fine. However, I saw that I was reading the file twice and, in
 the interest of good practice if I ever have this sort of project
 with a huge file, I thought I would try to be more efficient and read
 it once.

 You think that keeping a huge file in memory *all the time* is more
 efficient?
Ah, I see what you mean now. I work with the data later, so you are
saying that it would be better to just read the file as necessary,
then then, when I need the file's data later, just read it again.
 It's the other way around -- when dealing with *small* files
 you can afford to keep it in memory. When dealing with huge files, you
 need to re-write your program to deal with the file a piece at a time.
 (This is often a good strategy for small files as well, but it is
 essential for huge ones.)

 Of course, small and huge is relative to the technology of the day.
 I remember when 1MB was huge. These days, huge would mean gigabytes.
 Small would be anything under a few tens of megabytes.


 --
 Steven D'Aprano
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable Properties

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 11:24:16 am Chris King wrote:
  What problem are you trying to solve? There is likely another way
  to solve it. (Not necessarily an easy way, but we'll see.)

 So I'll have to create my own object which modifies each method to
 fire off the set method if the old form and the new form are unequal,
 there is no easy way?

I repeat... what problem are you trying to solve?

Calling the set method for something that *doesn't* set a property 
doesn't sound like a solution to a problem to me. It sounds like a 
problem itself.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Mutable Properties

2010-09-30 Thread Dave Angel



On 2:59 PM, Chris King wrote:

 On 9/30/2010 8:43 PM, Steven D'Aprano wrote:

snip


What problem are you trying to solve? There is likely another way to
solve it. (Not necessarily an easy way, but we'll see.)



So I'll have to create my own object which modifies each method to 
fire off the set method if the old form and the new form are unequal, 
there is no easy way?


Try rephrasing that in English.  Or just answer Chris's question.  What 
problem are you trying to solve?


The system will call the get() method if you're accessing the existing 
object, whether to look at it or modify it.  It'll call the set() method 
if you're binding a new object to the attribute.


DaveA


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] regexp: a bit lost

2010-09-30 Thread Alex Hall
Hi, once again...
I have a regexp that I am trying to use to make sure a line matches the format:
[c*]n [c*]n n
where c* is (optionally) 0 or more non-numeric characters and n is any
numeric character. The spacing should not matter. These should pass:
v1 v2   5
2 someword7 3

while these should not:
word 2  3
1 2

Here is my test:
s=re.search(r[\d+\s+\d+\s+\d], l)
if s: #do stuff

However:
1. this seems to pass with *any* string, even when l is a single
character. This causes many problems and cannot happen since I have to
ignore any strings not formatted as described above. So if I have
for a in b:
  s=re.search(r[\d+\s+\d+\s+\d], l)
  if s: c.append(a)

then c will have every string in b, even if the string being examined
looks nothing like the pattern I am after.

2. How would I make my regexp able to match 0-n characters? I know to
use \D*, but I am not sure about brackets or parentheses for putting
the \D* into the parent expression (the \d\s one).

3. Once I get the above working, I will need a way of pulling the
characters out of the string and sticking them somewhere. For example,
if the string were
v9 v10 15
I would want an array:
n=[9, 10, 15]
but the array would be created from a regexp. This has to be possible,
but none of the manuals or tutorials on regexp say just how this is
done. Mentions are made of groups, but nothing explicit (to me at
least).

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp: a bit lost

2010-09-30 Thread Gerard Flanagan

Alex Hall wrote:

Hi, once again...
I have a regexp that I am trying to use to make sure a line matches the format:
[c*]n [c*]n n
where c* is (optionally) 0 or more non-numeric characters and n is any
numeric character. The spacing should not matter. These should pass:
v1 v2   5
2 someword7 3

while these should not:
word 2  3
1 2

Here is my test:
s=re.search(r[\d+\s+\d+\s+\d], l)
if s: #do stuff

However:
1. this seems to pass with *any* string, even when l is a single
character. This causes many problems and cannot happen since I have to

[...]

You want to match a whole line, so you should use re.match not 
re.search. See the docs:


http://docs.python.org/library/re.html#matching-vs-searching


You can also use re.split in this case:

yes = 
v1 v2   5
2 someword7 3
.splitlines()
yes = [line for line in yes if line.strip()]

import re

pattern = (\w*\d\s+?) # there may be a better pattern than this
rx = re.compile(pattern)

for line in yes:
print [part for part in rx.split(line) if part]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp: a bit lost

2010-09-30 Thread Steven D'Aprano
On Fri, 1 Oct 2010 12:45:38 pm Alex Hall wrote:
 Hi, once again...
 I have a regexp that I am trying to use to make sure a line matches
 the format: [c*]n [c*]n n
 where c* is (optionally) 0 or more non-numeric characters and n is
 any numeric character. The spacing should not matter. These should
 pass: v1 v2   5
 2 someword7 3

 while these should not:
 word 2  3
 1 2

 Here is my test:
 s=re.search(r[\d+\s+\d+\s+\d], l)

Try this instead:

re.search(r'\d+\s+\D*\d+\s+\d', l)

This searches for:
one or more digits
at least one whitespace char (space, tab, etc)
zero or more non-digits
at least one digit
at least one whitespace
exactly one digit


 However:
 1. this seems to pass with *any* string, even when l is a single
 character. This causes many problems
[...]

I'm sure it does.

You don't have to convince us that if the regular expression is broken, 
the rest of your code has a problem. That's a given. It's enough to 
know that the regex doesn't do what you need it to do.


 3. Once I get the above working, I will need a way of pulling the
 characters out of the string and sticking them somewhere. For
 example, if the string were
 v9 v10 15
 I would want an array:
 n=[9, 10, 15]


Modify the regex to be this:

r'(\d+)\s+\D*(\d+)\s+(\d)'

and then query the groups of the match object that is returned:

 mo = re.search(r'(\d+)\s+\D*(\d+)\s+(\d)', 'spam42   eggs239')
 mo.groups()
('42', '23', '9')

Don't forget that mo will be None if the regex doesn't match, and don't 
forget that the items returned are strings.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regexp: a bit lost

2010-09-30 Thread Gerard Flanagan

with coffee:



yes = 
v1 v2   5
2 someword7 3
.splitlines()[1:]

no = 
word 2 3
1 2
.splitlines()[1:]

import re

pattern = (\w*\d\s+?)(\w*\d\s+?)(\d)$
rx = re.compile(pattern)

for line in yes:
m = rx.match(line)
assert m
print([part.rstrip() for part in m.groups()])

for line in no:
m = rx.match(line)
assert not m




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor