From matt.gregory at oregonstate.edu  Wed Sep  1 01:24:23 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Tue, 31 Aug 2010 16:24:23 -0700
Subject: [Tutor] polymorphism for file-like objects
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032E210@EXCH2.nws.oregonstate.edu>

Hi all,

In the 2nd edition of Python Cookbook, Mark Lutz writes the intro to Chapter 2 (Files) and gives the following example of polymorphism for file like objects (adapted for brevity):

def firstword(line):
    print line.split()[0]

def scanner(fileobject, linehandler):
    for line in fileobject:
        linehandler(line)

my_file = open('foo.txt')
scanner(my_file, firstword)

from cStringIO import StringIO
my_string = StringIO('one\ntwo xxx\nthree\n')
scanner(my_string, firstword)

class MyStream(object):
    def __iter__(self):
        return iter(['a\n', 'b c d\n'])
my_stream = MyStream()
scanner(my_stream, firstword)

I understand this code and the polymorphic behavior of scanner.  But then he says you can extend this idea to other file like objects (SQL databases, XML, interactive user, etc.).  My question is how do you extend the idea when 'lines' aren't so clearly defined such as this XML snippet:

<root>
  <line>a b c</line>
  <line>d</line>
  <block>
    <line>a x</line>
  </block>
</root>

I assume you need to write a MyXMLParser that somehow defines the iteration behavior that you want such that it will work with the scanner function?  But it doesn't necessarily need to subclass file, correct?

thanks for help, matt


From cappy2112 at gmail.com  Wed Sep  1 06:59:18 2010
From: cappy2112 at gmail.com (Tony Cappellini)
Date: Tue, 31 Aug 2010 21:59:18 -0700
Subject: [Tutor] Installation problem: Python 2.6.6 (32-Bit) on Windows 7
	(32-Bit)
Message-ID: <AANLkTi=q3gbyyN02s3nbNRjRc5ueDHy-kxa76AZOgNfG@mail.gmail.com>

Has anyone else had problems running the msi for Python 2.6.6 on Windows 7?

If I don't check "Compile .py to byte code", the installer completes
without error.
Checking "Compile .py to byte code" causes the following to be displayed

"There is a problem with the windows installer package. A program run
as part of setup did not complete as expected"

1. Yes I have plenty of disk space.
2. Yes I have admin privileges
3. Yes, the MD5 checksum of the downloaded installer matches the MD5
checksum on python.org
4. Run As Adminsitrator is not available when I Shift-Right Click
(probably because my user already has admin privileges)

I'm also having a similar issue with the PythonWin32 extensions
installer on the same machine.

From ranjithtenz at gmail.com  Wed Sep  1 07:24:58 2010
From: ranjithtenz at gmail.com (Ranjith Kumar)
Date: Wed, 1 Sep 2010 10:54:58 +0530
Subject: [Tutor] How to print the installed web browser
Message-ID: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>

Hi all,
     I`m using ubuntu how to find and print the installed web browsers using
python scripting.

-- 
Cheers
Ranjith,
Software Engineer,
Sedin Technologies,
Chennai

http://ranjith10z.wordpress.com
http://ranjithtenz.wordpress.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100901/b2dd8ddb/attachment-0001.html>

From payal-tutor at scriptkitchen.com  Wed Sep  1 03:45:22 2010
From: payal-tutor at scriptkitchen.com (Payal)
Date: Tue, 31 Aug 2010 18:45:22 -0700
Subject: [Tutor] __new__ over __init__
In-Reply-To: <i5i7bb$uqt$1@dough.gmane.org>
References: <20100831022240.GA6772@scriptkitchen.com>
	<i5i7bb$uqt$1@dough.gmane.org>
Message-ID: <20100901014522.GA17953@scriptkitchen.com>

On Tue, Aug 31, 2010 at 08:27:10AM +0200, Peter Otten wrote:
> Subclasses of immutable types, e. g. tuple:

That was one great example, thanks. Some doubts,

a. I have seen this cls before, what does it mean?
b. What does type(_) mean?

Thanks a lot in advance.

With warm regards,
-Payal
-- 


> >>> class A(tuple):
> ...     def __new__(cls, a, b):
> ...             return tuple.__new__(cls, (a, b))
> ...
> >>> A(1, 2)
> (1, 2)
> >>> type(_)
> <class '__main__.A'>
> 
> Peter
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Wed Sep  1 10:14:50 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 1 Sep 2010 09:14:50 +0100
Subject: [Tutor] __new__ over __init__
References: <20100831022240.GA6772@scriptkitchen.com><i5i7bb$uqt$1@dough.gmane.org>
	<20100901014522.GA17953@scriptkitchen.com>
Message-ID: <i5l21n$rni$1@dough.gmane.org>

"Payal" <payal-tutor at scriptkitchen.com> wrote

>> >>> class A(tuple):
>> ...     def __new__(cls, a, b):
>> ...             return tuple.__new__(cls, (a, b))

> a. I have seen this cls before, what does it mean?

It is an abbreviation for class. The first parameter to new() must be 
a refernce to the class.
It is similar to self in an instance method, where the first parameter 
is a reference
to the instance.


> b. What does type(_) mean?

The _ refers to the last evaluated result, in this case the tuple 
(1,2).
Its a shorthand trick, I think it only works in the interpreter, I 
don't like
it and never use it, but many do. (FWIW Perl has a similar shortcut
and Perl fans use it a lot!)

Try:
>>> 5+5
10
>>> A = 1+2
>>> print _
10
>>> A
3
>>> print _
3

HTH,

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



From alan.gauld at btinternet.com  Wed Sep  1 10:17:30 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 1 Sep 2010 09:17:30 +0100
Subject: [Tutor] How to print the installed web browser
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
Message-ID: <i5l26n$san$1@dough.gmane.org>

"Ranjith Kumar" <ranjithtenz at gmail.com> wrote

>     I`m using ubuntu how to find and print the installed web 
> browsers using
> python scripting.

How would you do it without Python scripting?
Is it even possible?

And on a multiuser system like Linux would you print out all the 
browsers
installed for the current user or for all users?

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



From airscorp at otenet.gr  Wed Sep  1 10:46:08 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 01 Sep 2010 11:46:08 +0300
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <i5l26n$san$1@dough.gmane.org>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
	<i5l26n$san$1@dough.gmane.org>
Message-ID: <4C7E12D0.908@otenet.gr>

On 09/01/2010 11:17 AM, Alan Gauld wrote:
> "Ranjith Kumar" <ranjithtenz at gmail.com> wrote
>
>>     I`m using ubuntu how to find and print the installed web browsers 
>> using
>> python scripting.
>
> How would you do it without Python scripting?
> Is it even possible?
>
> And on a multiuser system like Linux would you print out all the browsers
> installed for the current user or for all users?
>
Alan, let me make a wild guess here.

Ubuntu does have little "Preferred applications" config tool. I don't 
know how or where it stores this data, but my guess is it's the same 
place xdg (as in xdg-open) gets it's configuration from. This article 
might help http://www.crystalorb.net/mikem/xdg-settings.html

Quote from above article (near the end): "...especially as there is 
(currently) no single, portable, authoritative way for applications to 
query the values of these settings..."

Ranjith, get ready for some configuration file parsing.
But if you just want to open a url with the default browser, you can 
just execute "xdg-open your-url" as a subprocess.

Hope I shifted you to the right direction.

Nick

PS-trivia: I got to guess these just because I've read the source from 
"import antigravity"

From ranjithtenz at gmail.com  Wed Sep  1 10:48:03 2010
From: ranjithtenz at gmail.com (Ranjith Kumar)
Date: Wed, 1 Sep 2010 14:18:03 +0530
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <i5l26n$san$1@dough.gmane.org>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
	<i5l26n$san$1@dough.gmane.org>
Message-ID: <AANLkTi=dGNgfF9dKnE-wB_yEPe1FkiSJo5vY-d3LN2uq@mail.gmail.com>

On Wed, Sep 1, 2010 at 1:47 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Ranjith Kumar" <ranjithtenz at gmail.com> wrote
>
>
>     I`m using ubuntu how to find and print the installed web browsers using
>> python scripting.
>>
>
> How would you do it without Python scripting?
> Is it even possible?
>
> And on a multiuser system like Linux would you print out all the browsers
> installed for the current user or for all users?
>
for all users

>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Cheers
Ranjith,
Software Engineer,
Sedin Technologies,
Chennai

http://ranjith10z.wordpress.com
http://ranjithtenz.wordpress.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100901/dbc0bfd9/attachment.html>

From airscorp at otenet.gr  Wed Sep  1 10:51:05 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Wed, 01 Sep 2010 11:51:05 +0300
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <4C7E12D0.908@otenet.gr>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>	<i5l26n$san$1@dough.gmane.org>
	<4C7E12D0.908@otenet.gr>
Message-ID: <4C7E13F9.6050202@otenet.gr>

On 09/01/2010 11:46 AM, Nick Raptis wrote:
>
> Alan, let me make a wild guess here.
>
> Ubuntu does have little "Preferred applications" config tool. I don't 
> know how or where it stores this data, but my guess is it's the same 
> place xdg (as in xdg-open) gets it's configuration from. This article 
> might help http://www.crystalorb.net/mikem/xdg-settings.html
>
> Quote from above article (near the end): "...especially as there is 
> (currently) no single, portable, authoritative way for applications to 
> query the values of these settings..."
>
> Ranjith, get ready for some configuration file parsing.
> But if you just want to open a url with the default browser, you can 
> just execute "xdg-open your-url" as a subprocess.
>
> Hope I shifted you to the right direction.
>
> Nick
>
> PS-trivia: I got to guess these just because I've read the source from 
> "import antigravity"

Ooops! Sorry if I caused any confusion, I thought the goal was to print 
the default browser, not all of the installed ones. Silly me.
Still, the "Preferred applications" tool seems to know that info (so to 
give you a choice) so it might be something to dig into.

Nick

From steve at pearwood.info  Wed Sep  1 12:49:48 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 1 Sep 2010 20:49:48 +1000
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
Message-ID: <201009012049.49195.steve@pearwood.info>

On Wed, 1 Sep 2010 03:24:58 pm Ranjith Kumar wrote:
> Hi all,
>      I`m using ubuntu how to find and print the installed web
> browsers using python scripting.


You already asked this question on the 9th of August, in an email 
titled "Need a mentor":


4) Lastly I need to know is how to print the list of web browsers 
installed on a machine.


The answer is the same now as it was then:

You can't. 

I gave a much longer reply back then. But in summary:

* there's no canonical list of web browsers you could look for;
* there's no reliable way of recognizing a web browser short of human 
intelligence;
* it's not even clear what a web browser is.

Obviously a web browser is something that can browse the WWW, but that's 
much, much broader than just Firefox and IE. Python can browse the web. 
Does that mean Python is a web browser? Adobe Acrobat can download 
upgrades over the web. Does that make it a web browser? How about curl 
or wget?

Many applications can read files remotely over http. Some of them can 
follow embedded hyperlinks. Are they web browsers?




-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep  1 12:53:09 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 1 Sep 2010 20:53:09 +1000
Subject: [Tutor] Installation problem: Python 2.6.6 (32-Bit) on Windows
	7 (32-Bit)
In-Reply-To: <AANLkTi=q3gbyyN02s3nbNRjRc5ueDHy-kxa76AZOgNfG@mail.gmail.com>
References: <AANLkTi=q3gbyyN02s3nbNRjRc5ueDHy-kxa76AZOgNfG@mail.gmail.com>
Message-ID: <201009012053.09596.steve@pearwood.info>

On Wed, 1 Sep 2010 02:59:18 pm Tony Cappellini wrote:
> Has anyone else had problems running the msi for Python 2.6.6 on
> Windows 7?

Sorry, I'm not a Windows guy, I can't help.

You might have more luck on the python-list at python.org mailing list, 
which is also available on comp.lang.python:

http://mail.python.org/mailman/listinfo/python-list


-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep  1 13:23:19 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 1 Sep 2010 21:23:19 +1000
Subject: [Tutor] polymorphism for file-like objects
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032E210@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D6426032E210@EXCH2.nws.oregonstate.edu>
Message-ID: <201009012123.20406.steve@pearwood.info>

On Wed, 1 Sep 2010 09:24:23 am Gregory, Matthew wrote:
> Hi all,
>
> In the 2nd edition of Python Cookbook, Mark Lutz writes the intro to
> Chapter 2 (Files) and gives the following example of polymorphism for
> file like objects (adapted for brevity):
[...]
> I understand this code and the polymorphic behavior of scanner.  But
> then he says you can extend this idea to other file like objects (SQL
> databases, XML, interactive user, etc.).  My question is how do you
> extend the idea when 'lines' aren't so clearly defined such as this
> XML snippet:
>
> <root>
>   <line>a b c</line>
>   <line>d</line>
>   <block>
>     <line>a x</line>
>   </block>
> </root>

I expect that iterating over lines would be equivalent to:

a b c
d
a x

If you agree, then just walk the XML, and every time you see a <line> 
item, yield it.

Things get tricky if you can nest lines...

<line>a b<line>d</line>c</line>

I don't know what to expect if I see that.



> I assume you need to write a MyXMLParser that somehow defines the
> iteration behavior that you want such that it will work with the
> scanner function?  But it doesn't necessarily need to subclass file,
> correct?

Correct.

Forget about inheritance in this case, what you care about is the 
interface. You want an object that iterates over "lines", whatever that 
happens to be.

Inheritance is useful, but it's just one way of making objects with the 
same interface.


-- 
Steven D'Aprano

From payo2000 at gmail.com  Wed Sep  1 16:28:43 2010
From: payo2000 at gmail.com (pa yo)
Date: Wed, 1 Sep 2010 16:28:43 +0200
Subject: [Tutor] P2PU Beginning Python Webservices
Message-ID: <AANLkTik19P0AqCOtOyO6K_cv8zAQ0cnCommcmXw5ZpZC@mail.gmail.com>

I thought some of you might be interested in this course:

http://www.p2pu.org/webcraft/beginning-python-webservices

From andrew.currall at aecom.com  Wed Sep  1 17:22:05 2010
From: andrew.currall at aecom.com (Currall, Andrew)
Date: Wed, 1 Sep 2010 16:22:05 +0100
Subject: [Tutor] Exec function problem
Message-ID: <6339264FEDC410449B22F2B4D78BB5DF14337446@UKSTA1EX025V.eu.aecomnet.com>

Using Python 2.5. 
DemandModel.py is a valid, working python script. If I create another
script file, then:

execfile('DemandModel.py')

works fine. However, the apparently similar:

def runfile():
	execfile('DemandModel.py')
runfile()

doesn't, for no apparent reason: I get 

  File "DemandModel.py", line 12, in DemandModel
    Parameters=ReadDmData(segname)
NameError: global name 'ReadDmData' is not defined

Any ideas why? 

Use of 

CodeFile=open('DemandModel.py', 'r')
exec(CodeFile)

instead of execfile, doesn't make any difference either way, nor does it
make any difference if I read the file using read() and then execute the
string- in all cases the top-level command works; placed in a function
it doesn't.
Regards and thanks,
Andrew Currall MPhys
Senior Consultant, Transportation
D +44 (0)1727 535612
andrew.currall at aecom.com
AECOM
AECOM House
63-77 Victoria Street
St Albans, Herts AL1 3ER
T +44 (0)1727 535000 F +44 (0)1727 535099
www.aecom.com <http://www.aecom.com/> 



 
This email is confidential and is for the intended recipient only. If you are not the intended recipient, please contact the author and you must not disclose or use the contents in any way. The author bears responsibility for any legal action or disputes arising from views or professional advice expressed which do not relate to the business of AECOM Ltd.
 
AECOM Limited Registered in England No: 1846493
Registered Office: AECOM House, 63-77 Victoria Street, St Albans, Herts, AL1 3ER
 
Please consider the environment before printing this e-mail
 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100901/16c9ed10/attachment-0001.html>

From alan.gauld at btinternet.com  Wed Sep  1 20:24:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 1 Sep 2010 19:24:16 +0100
Subject: [Tutor] How to print the installed web browser
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>	<i5l26n$san$1@dough.gmane.org><4C7E12D0.908@otenet.gr>
	<4C7E13F9.6050202@otenet.gr>
Message-ID: <i5m5od$qcf$1@dough.gmane.org>


"Nick Raptis" <airscorp at otenet.gr> wrote

> Ooops! Sorry if I caused any confusion, I thought the goal was to 
> print the default browser, not all of the installed ones. Silly me.
> Still, the "Preferred applications" tool seems to know that info (so 
> to give you a choice) so it might be something to dig into.

The problem remains that the config tool will only know about
those browsers that have been "politely" installeed. If someone just
built the source in a local folder then its unlikely to be rgisterd,
but its still a valid browser, and may even be that users default.

You can only ever get an approximation and its a dangerous
assumption to think you can get more than that. But depending
on the reason for asking it may be good enough.

HTH,

Alan G. 



From alan.gauld at btinternet.com  Wed Sep  1 20:33:09 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 1 Sep 2010 19:33:09 +0100
Subject: [Tutor] Exec function problem
References: <6339264FEDC410449B22F2B4D78BB5DF14337446@UKSTA1EX025V.eu.aecomnet.com>
Message-ID: <i5m693$skr$1@dough.gmane.org>


"Currall, Andrew" <andrew.currall at aecom.com> wrote

> DemandModel.py is a valid, working python script. 
> If I create another script file, then:
>
> execfile('DemandModel.py')

You probably shouldn't. You should probably be importing it. 
Is there a reason why you want to use execfile()? 
Its nearly always the wrong solution...

> def runfile():
>     execfile('DemandModel.py')
> 
> runfile()

>   File "DemandModel.py", line 12, in DemandModel
>     Parameters=ReadDmData(segname)
> NameError: global name 'ReadDmData' is not defined

So it works on a line by itself but not in a function?
And it is running the file but getting an undefined name. odd.
What happens if you run execfile() from a new interpreter prompt?

> CodeFile=open('DemandModel.py', 'r')
> exec(CodeFile)

What happens if you use import (assuming you store in 
somewhere in sys.path...)


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



From mark at martialfit.net  Wed Sep  1 22:10:37 2010
From: mark at martialfit.net (Mark Weil)
Date: Wed, 1 Sep 2010 13:10:37 -0700
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <i5m5od$qcf$1@dough.gmane.org>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>
	<i5l26n$san$1@dough.gmane.org> <4C7E12D0.908@otenet.gr>
	<4C7E13F9.6050202@otenet.gr> <i5m5od$qcf$1@dough.gmane.org>
Message-ID: <AANLkTi=RjYGX05Yhb7-NwWTjGf-XF4dySF+nHq_x-6OK@mail.gmail.com>

Not perfect, but you could check for each browser's binary.

import os
os.path.isfile("/usr/bin/firefox")
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100901/8e25c713/attachment.html>

From steve at alchemy.com  Wed Sep  1 23:36:59 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Wed, 01 Sep 2010 14:36:59 -0700
Subject: [Tutor] How to print the installed web browser
In-Reply-To: <AANLkTi=RjYGX05Yhb7-NwWTjGf-XF4dySF+nHq_x-6OK@mail.gmail.com>
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>	<i5l26n$san$1@dough.gmane.org>
	<4C7E12D0.908@otenet.gr>	<4C7E13F9.6050202@otenet.gr>
	<i5m5od$qcf$1@dough.gmane.org>
	<AANLkTi=RjYGX05Yhb7-NwWTjGf-XF4dySF+nHq_x-6OK@mail.gmail.com>
Message-ID: <4C7EC77B.5070400@alchemy.com>

On 01-Sep-10 13:10, Mark Weil wrote:
> Not perfect, but you could check for each browser's binary.
>
> import os
> os.path.isfile("/usr/bin/firefox")

You'd probably be better off at least looking at the user's PATH 
variable, which would likely catch platform variations in where the 
browser would be located, and catch local installations by that user. 
Of course, you're still playing a guessing game of what to even look for 
or what the browser binary is called.  Maybe it's 
/usr/local/bin/firefox3, for example.


From alan.gauld at btinternet.com  Thu Sep  2 02:02:08 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 2 Sep 2010 01:02:08 +0100
Subject: [Tutor] How to print the installed web browser
References: <AANLkTik3-VnfngVAujdppALj3M_YRyqkhn7vB3=Pq8Q-@mail.gmail.com>	<i5l26n$san$1@dough.gmane.org><4C7E12D0.908@otenet.gr>	<4C7E13F9.6050202@otenet.gr><i5m5od$qcf$1@dough.gmane.org><AANLkTi=RjYGX05Yhb7-NwWTjGf-XF4dySF+nHq_x-6OK@mail.gmail.com>
	<4C7EC77B.5070400@alchemy.com>
Message-ID: <i5mphu$8oo$1@dough.gmane.org>


"Steve Willoughby" <steve at alchemy.com> wrote

>> Not perfect, but you could check for each browser's binary.
>>
>> import os
>> os.path.isfile("/usr/bin/firefox")

But then you have to know of all browsers and thats almost impossible.
And what if the user has built their own browser - I've written at 
least
3 web browsers of varying quality over the years! Including one batch
oriented one that ran overnight in the days when I only had a
14400 baud modem connection...

> You'd probably be better off at least looking at the user's PATH 
> variable, which would likely catch platform variations in where the 
> browser would be located, and catch local installations by that 
> user.

But only if they used path.
When I was a Unix user I used to just set up aliases to many of
the binaries that I installed locally. Or I would use a shell script 
to
launch them after setting up environment variables etc. The shell
script would be in my PATH but not the binary...

It really is an impossible task to get right. The best you will get is
a check against a small set of the most common browsers

firefox, opera, konqueror, chrome, lynx, safari(is it on Linux?) etc.

And as Steven pointed out many office type programs include the
ability to act as a basic browser nowadays. Even trhe Eclipse IDE
can display HTML pages. Does that count?


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



From __peter__ at web.de  Thu Sep  2 12:26:45 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 02 Sep 2010 12:26:45 +0200
Subject: [Tutor] __new__ over __init__
References: <20100831022240.GA6772@scriptkitchen.com>
	<i5i7bb$uqt$1@dough.gmane.org>
	<20100901014522.GA17953@scriptkitchen.com>
	<i5l21n$rni$1@dough.gmane.org>
Message-ID: <i5nu4a$tuq$1@dough.gmane.org>

Alan Gauld wrote:

> "Payal" <payal-tutor at scriptkitchen.com> wrote
>> b. What does type(_) mean?
> 
> The _ refers to the last evaluated result, in this case the tuple
> (1,2).
> Its a shorthand trick, I think it only works in the interpreter, I
> don't like
> it and never use it, but many do. (FWIW Perl has a similar shortcut
> and Perl fans use it a lot!)

_ does indeed only work in interactive mode. It is handy when you evaluate 
an expression and only then notice that you want to do something with the 
result. 

I added the type(_) line as an afterthought when I saw that the A instance 
was indistinguishable from a tuple.

A more forward-thinking demo would have been

>>> class A(tuple):
...     def __new__(cls, a, b):
...             return tuple.__new__(cls, (a, b))
...
>>> a = A(1, 2)
>>> a
(1, 2)
>>> type(a)
<class '__main__.A'>

Peter




From payal-python at scriptkitchen.com  Thu Sep  2 13:26:27 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Thu, 2 Sep 2010 04:26:27 -0700
Subject: [Tutor] __new__ over __init__
In-Reply-To: <i5l21n$rni$1@dough.gmane.org>
References: <20100901014522.GA17953@scriptkitchen.com>
	<i5l21n$rni$1@dough.gmane.org>
Message-ID: <20100902112627.GA2073@scriptkitchen.com>

On Wed, Sep 01, 2010 at 09:14:50AM +0100, Alan Gauld wrote:
> It is an abbreviation for class. The first parameter to new() must be a 
> refernce to the class.
> It is similar to self in an instance method, where the first parameter  
> is a reference
> to the instance.

Thanks a lot.

With warm regards,
-Payal
-- 



From kagebatsu at cox.net  Thu Sep  2 22:57:41 2010
From: kagebatsu at cox.net (kagebatsu)
Date: Thu, 2 Sep 2010 13:57:41 -0700 (PDT)
Subject: [Tutor] NLTK needs YAML?
In-Reply-To: <j2n388161951004232213v288643f7u577cf62c7c5074c6@mail.gmail.com>
References: <j2n388161951004232213v288643f7u577cf62c7c5074c6@mail.gmail.com>
Message-ID: <29609058.post@talk.nabble.com>




Michael Scharf-6 wrote:
> 
> 
> ImportError: No module named yaml
> 
> So my question is: do I really not have what I need here?  Or is it a
> question of  something not finding something that's there?  Maybe I'm
> using the wrong name somewhere?  Or??
> 
> 
> 

Mike, I've just gotten nltk to work on my iMac. I was having the exact same
problem as you. Perhaps you've already fixed this issue--but maybe someone
else will have the problem, too. 

1. First, you need to install PyYAML, here: http://www.nltk.org/download
(scroll down to where it says install PyYAML). Remember where you extract
PyYAML. 
2. Then, boot up terminal, direct terminal to the correct directory (i.e. cd
/Applications/PyYAML...) and then do: sudo python setup.py install. PyYAML
will install. 
3. After it's installed, direct terminal to the correct directory where
NLTK's setup.py file is located (i.e. cd /Applications/Python\
2.6/tmp/nltk-installer/...) and then do: sudo python setup.py install. NLTK
will install. 
4. Check this by then typing python into terminal and: import nltk at the
prompt. Like the NLTK site says, if after typing import nltk at  the prompt
(>>>) returns silently, your installation was successful. 

Feel free to email me if this doesn't work or you need more help. 

-Brandon
-- 
View this message in context: http://old.nabble.com/-Tutor--NLTK-needs-YAML--tp28348409p29609058.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From smokefloat at gmail.com  Fri Sep  3 04:24:00 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 2 Sep 2010 22:24:00 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
Message-ID: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>

In the below function I'm trying to iterate over the lines in a textfile,
and try to match with a regex pattern that iterates over the lines in
a dictionary(not {}, but turns a text list of alphabetical words into a
list using readlines()).

def regexfiles(filename):
	textfile = file(filename, 'r+')
                # Open the dictionary file
	dictionary = file('/var/www/main/american-english', 'r')
	search = 0
	readict = dictionary.readlines()
	readfile = textfile.readlines()
	select = 'abbott'
	for item in readict:
		search += 1
		print search, '\nselect =' , select , 'item = ' , item , 'readfile =
' , str(readfile) , '\nre.findall =' , re.findall( select,
str(readfile)) , '\nre.search = ' , re.search(select,
str(readfile[:])), '\n'

My last entry that comes up is:

14
select = abbott
item =  abbott
len readfile =  6
readfile =  ['|aaolaachenaaliyahaaronabbasabbasidabbottsaaolaachenaaliyahaaronabbasabbasidabbott"aaolaachenaaliyahaaronabbasabbasidabbott}aaolaachenaaliyahaaronabbasabbasidabbottvaaolaachenaaliyahaaronabbasabbasidabbott']
re.findall = ['abbott', 'abbott', 'abbott', 'abbott', 'abbott']
re.search =  <_sre.SRE_Match object at 0x8838b80>

Which is fine until I begin trying to iterate over the words in my
word 'dictionary' list to use as
replacement patterns with each new word iterated over in the list
getting placed as the regex pattern.

If I try to replace the variable 'select' with anything other than
select = 'abbott'(or whatever random
word being used that is in the file), with something like
str(readict[13]), which is a list of words, and the 13th
word in the list is also abbott, and is turned into a string, yielding
an extra +1 len, I get.

14
select = abbott
item =  abbott
len readfile =  7
readfile =  ['|aaolaachenaaliyahaaronabbasabbasidabbottsaaolaachenaaliyahaaronabbasabbasidabbott']
re.findall = []
re.search =  None

re.findall, and re.search show none, even when the variables show the
same, other than len,
and they've been turned into strings.

So my main question is...drum roll please...how do I iterate through a
list of terms inside of the regex,
without it yielding the second result?

Right now, I can see that it searches the file for the term if it's in
' ', so that
part works, and on other attempts than this one, I can get it to loop
through the words in the dictionary
list and replace the regex pattern as it goes through, then use
readlines() to check the files lines, but
even with this the changing variable makes it show none.

TIA,
David

From smokefloat at gmail.com  Fri Sep  3 05:05:19 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 2 Sep 2010 23:05:19 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
Message-ID: <AANLkTimCB5+0GJ-_5_JhAnDkr4s3Gef87k1+9EiQ5xxH@mail.gmail.com>

I just added +'*' to select in re.search(select+'*', str(readfile[:])),
and it now shows the same in both.

But if you have any input on modifications let me know.

Thanks,
David

From songbird42371 at gmail.com  Fri Sep  3 06:11:08 2010
From: songbird42371 at gmail.com (Colleen Glaeser)
Date: Thu, 2 Sep 2010 23:11:08 -0500
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow morning.
Message-ID: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>

Dear Python Tutors,

I'm having trouble while typing a beginner program for python.
Due to troublesome circumstances, I had to take pictures of the assignment
sheet on my phone, and work from that.
Although it is all clearly legible, I still think something with my program
is not working.

If I run the program in the shell, I should be getting something that asks
for a number, and I need to try positive and negative numbers and see what
spits out.

However, I'm getting the number 24, and a repetition of the words "Hello"
and "Greetings, earthlings."

This below is my program, and I've retyped it too many times to remember,
while looking at the assignment sheet.
What am I doing wrong?  Can anybody help?  D:  I need to turn my results in
to class tomorrow morning!

# Lab 1
# Programmed by Colleen G.

x = 12

print (2*x)

def greetings():
    for i in range (3):
        print ('Hello ')
    print ('Greetings, earthling')

def regreet():
    for j in range(4):
        greetings()

regreet()


End of program.....help needed quickly!  Thank you!  I am using Python 3.1.2

-- 
Colleen Glaeser
songbird42371 at gmail.com
636.357.8519
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100902/bd983136/attachment.html>

From alan.gauld at btinternet.com  Fri Sep  3 11:10:17 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 3 Sep 2010 10:10:17 +0100
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow
	morning.
References: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
Message-ID: <i5qe1r$db5$1@dough.gmane.org>


"Colleen Glaeser" <songbird42371 at gmail.com> wrote

> Although it is all clearly legible, I still think something with my 
> program
> is not working.

Why, can you explain what you think should happen?

> If I run the program in the shell, I should be getting something 
> that asks
> for a number, and I need to try positive and negative numbers and 
> see what
> spits out.

Where do you think your code asks for a number?

> However, I'm getting the number 24, and a repetition of the words 
> "Hello"
> and "Greetings, earthlings."

That seems to be what your code prints so it would appear to be 
reasonable.

> What am I doing wrong?  Can anybody help?  D:  I need to turn my 
> results in
> to class tomorrow morning!
>
> x = 12
> print (2*x)

Here is your 24

> def greetings():
>    for i in range (3):
>        print ('Hello ')
>    print ('Greetings, earthling')

And this repeatedly prints Hello and Greetings Earthling

> def regreet():
>    for j in range(4):
>        greetings()

And this calls greetings() repeatedly, so even
more printing of the messages.

> regreet()

And this actually calls regreet() which triggers the whole thing off.

So your code appears to be doing exactly what you told it to do.
Where should the reading of numbers come in?
And what would you do with the numbers when you got them?

You might find the "Talking to the user" topic of my tutorial useful.

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



From fomcl at yahoo.com  Fri Sep  3 11:15:56 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 3 Sep 2010 02:15:56 -0700 (PDT)
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow
	morning.
In-Reply-To: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
References: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
Message-ID: <356623.3354.qm@web110716.mail.gq1.yahoo.com>

Hi,

Just guessing:

x = 12

print (2*x)

def greetings(no):
    for i in range (no+1):
        print ('Hello ')
    print ('Greetings, earthling')

def regreet(no):
    for j in range(no+1):
        greetings(no)

prompt = "Enter a number: "
no = raw_input(prompt)
regreet(no)

It's not tested because I run Python 2.7 It's generally recommended that novice 
programmers run Py 2.x

 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: Colleen Glaeser <songbird42371 at gmail.com>
To: tutor at python.org
Sent: Fri, September 3, 2010 6:11:08 AM
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow morning.

Dear Python Tutors,

I'm having trouble while typing a beginner program for python.
Due to troublesome circumstances, I had to take pictures of the assignment sheet 
on my phone, and work from that.
Although it is all clearly legible, I still think something with my program is 
not working.

If I run the program in the shell, I should be getting something that asks for a 
number, and I need to try positive and negative numbers and see what spits out.

However, I'm getting the number 24, and a repetition of the words "Hello" and 
"Greetings, earthlings."

This below is my program, and I've retyped it too many times to remember, while 
looking at the assignment sheet.
What am I doing wrong?  Can anybody help?  D:  I need to turn my results in to 
class tomorrow morning!

# Lab 1
# Programmed by Colleen G.

x = 12

print (2*x)

def greetings():
    for i in range (3):
        print ('Hello ')
    print ('Greetings, earthling')

def regreet():
    for j in range(4):
        greetings()

regreet()


End of program.....help needed quickly!  Thank you!  I am using Python 3.1.2

-- 
Colleen Glaeser
songbird42371 at gmail.com 
636.357.8519



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100903/4c0ced8a/attachment.html>

From steve at pearwood.info  Fri Sep  3 11:20:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 3 Sep 2010 19:20:30 +1000
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow
	morning.
In-Reply-To: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
References: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
Message-ID: <201009031920.31577.steve@pearwood.info>

On Fri, 3 Sep 2010 02:11:08 pm Colleen Glaeser wrote:
> Dear Python Tutors,
>
> I'm having trouble while typing a beginner program for python.
> Due to troublesome circumstances, I had to take pictures of the
> assignment sheet on my phone, and work from that.
> Although it is all clearly legible, I still think something with my
> program is not working.
>
> If I run the program in the shell, I should be getting something that
> asks for a number, and I need to try positive and negative numbers
> and see what spits out.

There's nothing in your program that actually asks the user for a 
number. You need to use the function input(), like this:

answer = input("Hello puny human, give me a number. ")

If you type (say) 42 then press the Enter key, the variable answer will 
be set to the string "42". You then need to change it to an integer:

number = int(answer) 

or a float:

number = float(answer)



> However, I'm getting the number 24, and a repetition of the words
> "Hello" and "Greetings, earthlings."

Yes, that's because greetings() prints "Hello" three times, followed 
by "Greetings earthling" once. Then regreet() calls greetings() four 
times in a row, so it prints "Hello" twelve times in total 
and "Greetings earthling" four times.


> This below is my program, and I've retyped it too many times to
> remember, while looking at the assignment sheet.
> What am I doing wrong?  Can anybody help?  D:  I need to turn my
> results in to class tomorrow morning!

I hope the above clues will set you on the right track.

We won't do your homework for you, but if you come back with *specific* 
questions, we can help.



-- 
Steven D'Aprano

From delegbede at dudupay.com  Fri Sep  3 11:30:51 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Fri, 3 Sep 2010 10:30:51 +0100
Subject: [Tutor] Begginer Python Problems - Urgent! Due by tomorrow
	morning.
In-Reply-To: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
References: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
Message-ID: <AANLkTimtdxEnB7JP_GFOc9nKAMx6PjgeJm68889EgoVT@mail.gmail.com>

>From what I can understand, I think you are getting what you should
get. If you want the program to ask you for a number onput, i think
you should type something like:
x = raw_input('Enter a Number: ')
x is a variable that takes whatever value you type in.
This I feel should be the line if you are on python 3 and I should even ask why.
I got the same advice as a beginner to learn with python 2.6 due to
availability of books and tutorials.
However, if it were python 2.6, type:
x = input('Enter a Number: ')
Here, x also takes any value you enter.
Clearly, from what you have shown here, you should get something like:
24
Hello
Greetings Earthing
Hello
Greetings Earthing
Hello
Greetings Earthing
Hello
Greetings Earthing
Hello
Greetings Earthing
Hello
Greetings Earthing
Here's the explanation:
The greeting functions if called should have given this:
Hello
Greetings Earthing
Hello
Greetings Earthing
I iterates over the print call 2 times because you stated range(3)
However, you called the greeting function in the regreet function, and
stated that j should iterate in the range(4).
That way, greeting is called 3 times and then you have what i have
already stated above.
I hope this is correct and it helps.
Regards.

On 9/3/10, Colleen Glaeser <songbird42371 at gmail.com> wrote:
> Dear Python Tutors,
>
> I'm having trouble while typing a beginner program for python.
> Due to troublesome circumstances, I had to take pictures of the assignment
> sheet on my phone, and work from that.
> Although it is all clearly legible, I still think something with my program
> is not working.
>
> If I run the program in the shell, I should be getting something that asks
> for a number, and I need to try positive and negative numbers and see what
> spits out.
>
> However, I'm getting the number 24, and a repetition of the words "Hello"
> and "Greetings, earthlings."
>
> This below is my program, and I've retyped it too many times to remember,
> while looking at the assignment sheet.
> What am I doing wrong?  Can anybody help?  D:  I need to turn my results in
> to class tomorrow morning!
>
> # Lab 1
> # Programmed by Colleen G.
>
> x = 12
>
> print (2*x)
>
> def greetings():
>     for i in range (3):
>         print ('Hello ')
>     print ('Greetings, earthling')
>
> def regreet():
>     for j in range(4):
>         greetings()
>
> regreet()
>
>
> End of program.....help needed quickly!  Thank you!  I am using Python 3.1.2
>
> --
> Colleen Glaeser
> songbird42371 at gmail.com
> 636.357.8519
>

-- 
Sent from my mobile device

Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development

From alan.gauld at btinternet.com  Fri Sep  3 19:01:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 3 Sep 2010 18:01:05 +0100
Subject: [Tutor] Begginer Python Problems - Urgent! Due by
	tomorrowmorning.
References: <AANLkTinWgTBktaEWtHJ5=y-1sLqknTDVX+jjwOo3KkXS@mail.gmail.com>
	<AANLkTimtdxEnB7JP_GFOc9nKAMx6PjgeJm68889EgoVT@mail.gmail.com>
Message-ID: <i5r9kh$5t9$1@dough.gmane.org>


"Dipo Elegbede" <delegbede at dudupay.com> wrote 

> you should type something like:
> x = raw_input('Enter a Number: ')
> x is a variable that takes whatever value you type in.
> However, if it were python 2.6, type:
> x = input('Enter a Number: ')

Actually the other way round.
input() for Python v 3 and raw_input() for Python 2.x.

Alan G.


From smokefloat at gmail.com  Fri Sep  3 20:51:03 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 3 Sep 2010 14:51:03 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTimCB5+0GJ-_5_JhAnDkr4s3Gef87k1+9EiQ5xxH@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<AANLkTimCB5+0GJ-_5_JhAnDkr4s3Gef87k1+9EiQ5xxH@mail.gmail.com>
Message-ID: <AANLkTinnvD6CjxXR02BnZ+VHA-npTZkjNEBiaqk3mHxn@mail.gmail.com>

On Thu, Sep 2, 2010 at 11:05 PM, David Hutto <smokefloat at gmail.com> wrote:
> I just added +'*' to select in re.search(select+'*', str(readfile[:])),
> and it now shows the same in both.
>
> But if you have any input on modifications let me know.
>
> Thanks,
> David
>

Still a problem. When I use the re.search(select+'*', str(readfile))
the asterisk  for re matches it to any character, so if there are any
letters of the word it matches.

I would like to match the exact word being sent not just any of the
characters, and the only way is with the exact word nothing following it,
but substituting the string parameter with the word even str(word), it
always shows negative for a match, search or findall.

So does this have something to do with the extra len on the str(wordfromlist)
as stated in the first email, and if so how do I remove whats there.

If not, what is the, probably small, thing I'm not doing to the item being
used as the re.search/findall parameter?

Thanks,
David

From matt.gregory at oregonstate.edu  Fri Sep  3 21:17:34 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Fri, 3 Sep 2010 12:17:34 -0700
Subject: [Tutor] best practices for where to set instance member variables
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032E33E@EXCH2.nws.oregonstate.edu>

Hi all,

Is there a guideline on where instance member variables should be set within a class?  That is, is it a bad idea to set self variables within private member functions rather than returning them to the enclosing caller?  Or should I avoid calls to internal functions from other member functions altogether (even if they are somewhat complex)?

class Foo:
    def __init__(self, a):
        self._f1(a)
    def _f1(self, a):
        self.a = a

-or-

class Foo:
    def __init__(self, a):
        self.a = self._f1(a)
    def _f1(self, a):
        return a

The first method seems to me to 'hide' where the variables get set, but in looking through some of my site-packages, developers seem to do this both ways.

As always, thanks for help,
matt

From smokefloat at gmail.com  Fri Sep  3 23:19:02 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 3 Sep 2010 17:19:02 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTinnvD6CjxXR02BnZ+VHA-npTZkjNEBiaqk3mHxn@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<AANLkTimCB5+0GJ-_5_JhAnDkr4s3Gef87k1+9EiQ5xxH@mail.gmail.com>
	<AANLkTinnvD6CjxXR02BnZ+VHA-npTZkjNEBiaqk3mHxn@mail.gmail.com>
Message-ID: <AANLkTi=tDnu2OD5KosXMjaSdDjD2LLPeOekxh=HM-wo2@mail.gmail.com>

On Fri, Sep 3, 2010 at 2:51 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Thu, Sep 2, 2010 at 11:05 PM, David Hutto <smokefloat at gmail.com> wrote:
>> I just added +'*' to select in re.search(select+'*', str(readfile[:])),
>> and it now shows the same in both.
>>
>> But if you have any input on modifications let me know.
>>
>> Thanks,
>> David
>>
>
> Still a problem. When I use the re.search(select+'*', str(readfile))
> the asterisk ?for re matches it to any character, so if there are any
> letters of the word it matches.
>
> I would like to match the exact word being sent not just any of the
> characters, and the only way is with the exact word nothing following it,
> but substituting the string parameter with the word even str(word), it
> always shows negative for a match, search or findall.
>
> So does this have something to do with the extra len on the str(wordfromlist)
> as stated in the first email, and if so how do I remove whats there.
>
> If not, what is the, probably small, thing I'm not doing to the item being
> used as the re.search/findall parameter?
>
> Thanks,
> David
>

Fixed by rstrip() on item being iterated from dictionary file.

re.findall(str.rstrip(select), str(readfile)

From steve at pearwood.info  Sat Sep  4 03:12:27 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 4 Sep 2010 11:12:27 +1000
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
Message-ID: <201009041112.28651.steve@pearwood.info>

On Fri, 3 Sep 2010 12:24:00 pm David Hutto wrote:
> In the below function I'm trying to iterate over the lines in a
> textfile, and try to match with a regex pattern that iterates over
> the lines in a dictionary(not {}, but turns a text list of
> alphabetical words into a list using readlines()).
>
> def regexfiles(filename):
[...]

Your function does too much. It:

1 manages a file opened for input and output;
2 manages a dictionary file;
3 handles multiple searches at once (findall and search);
4 handles print output;

and you want it to do more:

5 handle multiple "select" terms.


Your function is also poorly defined -- I've read your description 
repeatedly, and studied the code you give, and your three follow up 
posts, and I still don't have the foggiest clue of what it's supposed 
to accomplish! You do two searches on each iteration, but other than 
print the results, you don't do anything with it.

What is the *meaning* of the function? "regexfiles" is a meaningless 
name, and your description "I'm trying to iterate over the lines in a 
textfile, and try to match with a regex pattern that iterates over the 
lines in a dictionary" is confusing -- the first part is fine, but what 
do you mean by a regex that iterates over the lines in a dictionary?

What is the purpose of a numeric variable called "search"? It looks like 
a counter to me, not a search, it is incremented each time through the 
loop. The right way to do that is with enumerate(), not a manual loop 
variable.

Why do you call readlines() instead of read()? This makes no sense to 
me. You then convert a list of strings into a single string like this:

readlines() returns ['a\n', 'b\n', 'c\n']
calling str() returns "['a\n', 'b\n', 'c\n']"

but the result includes a lot of noise that weren't in the original 
file: open and close square brackets, commas, quotation marks.

I think perhaps you want ''.join(readlines()) instead, but even that is 
silly, because you should just call read() and get 'a\nb\nc\n'.

You should split this up into multiple functions. It will make 
comprehension, readability, debugging and testing all much, much 
easier. Code should be self-documenting -- ideally you will never need 
to write a comment, because what the code does should be obvious from 
your choice of function and variable names.

I don't understand why you're using regex here. If I'm guessing 
correctly, the entries in the dictionary are all ordinary (non-regex) 
strings, like:

ape
cat
dog

only many, many more words :)

Given that, using the re module is like using a bulldozer to crack a 
peanut, and about as efficient. Instead of re.search(target, text) you 
should just use text.find(target). There's no built-in equivalent to 
re.findall, but it's not hard to write one:

def findall(text, target):
    results = []
    start = 0
    p = text.find(target)
    while p != -1:
        results.append(p)
        p = text.find(target)
    return results

(This returns a list of starting positions rather than words. It's easy 
to modify to do the other -- just append target instead of p.)


Anyway, here's my attempt to re-write your function. I've stuck to 
regexes just in case, and there's lots of guess-work here, because I 
don't understand what you're trying to accomplish, but here goes 
nothing:


# Change this to use real English  *wink*
DEFAULT_DICT =  '/var/www/main/american-english'

def get_dict_words(filename=''):
    """Return a list of words from the given dictionary file.

    If not given, a default dictionary is used.
    The format of the file should be one word per line.
    """
    if not filename:
        filename = DEFAULT_DICT
    # Don't use file, use open.
    dictionary = open(filename)
    words = dictionary.readlines()
    # Best practice is to explicitly close files when done.
    dictionary.close()
    return words


def search(target, text):
    """Return the result of two different searches for target in text.

    target should be a regular expression or regex object; text should
    be a string.

    Result returned is a two-tuple:
    (list of matches, regex match object or None)
    """
    if isinstance(target, str):
        target = re.compile(target)
    a = target.findall(text)
    b = target.search(text)
    return (a, b)


def print_stuff(i, target, text, a, b):
    # Boring helper function to do printing.
    print "counter = %d" % i
    print "target = %s" % target
    print "text = %s" % text
    print "findall = %s" % a
    print "search = %s" % b
    print


def main(text):
    """Print the results of many regex searches on text."""
    for i, word in get_dict_words():
        a, b, = search(word, text)
        print_stuff(i, word, text, a, b)


# Now call it:
fp = open(filename)
text = fp.read()
fp.close()
main(text)



I *think* this should give the same results you got.


-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep  4 03:41:58 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 4 Sep 2010 11:41:58 +1000
Subject: [Tutor] best practices for where to set instance member
	variables
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032E33E@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D6426032E33E@EXCH2.nws.oregonstate.edu>
Message-ID: <201009041141.59146.steve@pearwood.info>

On Sat, 4 Sep 2010 05:17:34 am Gregory, Matthew wrote:
> Hi all,
>
> Is there a guideline on where instance member variables should be set
> within a class?


The normal terminology used in Python is "attributes" instead of "member 
variables", and "methods" rather than "member functions".


[...]
> class Foo:
>     def __init__(self, a):
>         self._f1(a)
>     def _f1(self, a):
>         self.a = a

In general, I would avoid that style of coding. Method _f1 operates by 
side-effect. That makes it harder to test, which means you probably 
avoid testing it, which means it probably has bugs. The more 
complicated _f1 is, the more you need to test it, and the less likely 
you are to do so. This is a bad mix!

You should try to limit methods with side-effects to only those that 
*need* to have side-effects, like list.append() and similar.

(Note: functional programming proponents would argue that you *never* 
need to have side-effects, except perhaps in one tiny little corner of 
the language where you handle file I/O. Maybe so, but Python is not and 
never will be a pure FP language, and there's no need to take it to 
such extremes to realise that side-effects are often bad and should be 
avoided as much as possible.)


> -or-
>
> class Foo:
>     def __init__(self, a):
>         self.a = self._f1(a)
>     def _f1(self, a):
>         return a

That's much better. Now you can easily write a test to ensure that _f1 
is correct, without having to worry about side-effects.

However, remember that _f1 is being called from within the 
initialization method. That means that at the point that _f1 is called, 
self is not fully initialized! That makes it hard to reason about the 
state of the instance, and hard to know which attributes exist, and 
which methods are safe to call. These added complications should be 
avoided. Since you can't rely on self, it's best to avoid passing it as 
an argument to the method:

    @staticmethod  # nothing like C++ static methods
    def _f1(a):
        # Method _f1 can't see self or self's class.
        return a

    @classmethod
    def _f1(cls, a):
        # Method _f1 can't see self but does see self's class.
        return a

Instead of hoping that the caller will remember that _f1 can't rely on 
self being fully initialized, you can prohibit it.

The worst case is when _f1 needs access to self. That requires careful 
handling, and is best avoided.


Aside: 

The use of private methods in Python is looked on with mild suspicion. 
It's not so much frowned upon, as considered a sign that the author is 
trying to write Java or C++ instead of Python. My own feeling is, 
anytime I think I want a private method, that's possibly a hint that 
the method is too specific and not general (i.e. useful) enough. But 
I'll assume that you have a good reason for making _f1 a private method 
rather than public. Just remembering that in Python, there's no such 
thing as "private", it's just a naming convention.



> The first method seems to me to 'hide' where the variables get set,

Which is another reason to avoid it.


> but in looking through some of my site-packages, developers seem to
> do this both ways.

Yes, they do. Doesn't mean you have to follow their bad ideas :)


-- 
Steven D'Aprano

From smokefloat at gmail.com  Sat Sep  4 03:57:00 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 3 Sep 2010 21:57:00 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <201009041112.28651.steve@pearwood.info>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<201009041112.28651.steve@pearwood.info>
Message-ID: <AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>

First of all, I'll respond more thoroughly tomorrow, when I can review
what you said more clearly, but for now I'll clarify.

Here is the whole code that I'm using:

http://pastebin.com/Ak8DFjrb

On Fri, Sep 3, 2010 at 9:12 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 3 Sep 2010 12:24:00 pm David Hutto wrote:
>> In the below function I'm trying to iterate over the lines in a
>> textfile, and try to match with a regex pattern that iterates over
>> the lines in a dictionary(not {}, but turns a text list of
>> alphabetical words into a list using readlines()).
>>
>> def regexfiles(filename):
> [...]
>
> Your function does too much. It:
>
> 1 manages a file opened for input and output;
> 2 manages a dictionary file;
> 3 handles multiple searches at once (findall and search);
> 4 handles print output;
>
> and you want it to do more:
>
> 5 handle multiple "select" terms.
>
>
> Your function is also poorly defined -- I've read your description
> repeatedly, and studied the code you give, and your three follow up
> posts, and I still don't have the foggiest clue of what it's supposed
> to accomplish!

This is supposed to recreate a thought experiment I've heard about, in which,
if you have an infinite amount of monkeys, with an infinite amount of
typewriters,
they'll eventually spit out Shakespeare.

So, I create a random length file, with random characters, then regex
it for the iteration
of dictionary terms, but the regex is needed further for the
theoretical exploratory purposes
into the thought experiment. If dictionary patterns are matched, then
it needs further regex
for grammatically proper structures, even if they don't make
sense(take mad libs for example),
but are still grammatically correct, randomly produced files.

So the bulldozer is needed.


You do two searches on each iteration, but other than
> print the results, you don't do anything with it.

I had to print the results, in order to understand why using 'apple'
in a variable
yielded something different than when I iterated over the text file.
The end result was that
the list of dictionary words ['a\n'', 'b\n'] had \n, which was the
extra character in the iteration I was referring to,
and thanks to printing it out I was able to further isolate the
problem through len().

So rstrip() removed '\n' from the iterated term in the text file,
yielding just the ['term'], and not ['term\n'].

Print helps you see the info first hand.

>
> What is the *meaning* of the function? "regexfiles" is a meaningless
> name, and your description "I'm trying to iterate over the lines in a
> textfile, and try to match with a regex pattern that iterates over the
> lines in a dictionary" is confusing -- the first part is fine, but what
> do you mean by a regex that iterates over the lines in a dictionary?
>
> What is the purpose of a numeric variable called "search"? It looks like
> a counter to me, not a search, it is incremented each time through the
> loop. The right way to do that is with enumerate(), not a manual loop
> variable.
>
> Why do you call readlines() instead of read()? This makes no sense to
> me. You then convert a list of strings into a single string like this:
>
> readlines() returns ['a\n', 'b\n', 'c\n']
> calling str() returns "['a\n', 'b\n', 'c\n']"
>
> but the result includes a lot of noise that weren't in the original
> file: open and close square brackets, commas, quotation marks.
>
> I think perhaps you want ''.join(readlines()) instead, but even that is
> silly, because you should just call read() and get 'a\nb\nc\n'.
>
> You should split this up into multiple functions. It will make
> comprehension, readability, debugging and testing all much, much
> easier. Code should be self-documenting -- ideally you will never need
> to write a comment, because what the code does should be obvious from
> your choice of function and variable names.
>
> I don't understand why you're using regex here. If I'm guessing
> correctly, the entries in the dictionary are all ordinary (non-regex)
> strings, like:
>
> ape
> cat
> dog
>
> only many, many more words :)
>
> Given that, using the re module is like using a bulldozer to crack a
> peanut, and about as efficient. Instead of re.search(target, text) you
> should just use text.find(target). There's no built-in equivalent to
> re.findall, but it's not hard to write one:
>
> def findall(text, target):
> ? ?results = []
> ? ?start = 0
> ? ?p = text.find(target)
> ? ?while p != -1:
> ? ? ? ?results.append(p)
> ? ? ? ?p = text.find(target)
> ? ?return results
>
> (This returns a list of starting positions rather than words. It's easy
> to modify to do the other -- just append target instead of p.)
>
>
> Anyway, here's my attempt to re-write your function. I've stuck to
> regexes just in case, and there's lots of guess-work here, because I
> don't understand what you're trying to accomplish, but here goes
> nothing:

The above should explain a little more, and tomorrow, I'll thoroughly
review your post.
>
>
> # Change this to use real English ?*wink*
> DEFAULT_DICT = ?'/var/www/main/american-english'
>
> def get_dict_words(filename=''):
> ? ?"""Return a list of words from the given dictionary file.
>
> ? ?If not given, a default dictionary is used.
> ? ?The format of the file should be one word per line.
> ? ?"""
> ? ?if not filename:
> ? ? ? ?filename = DEFAULT_DICT
> ? ?# Don't use file, use open.
> ? ?dictionary = open(filename)
> ? ?words = dictionary.readlines()
> ? ?# Best practice is to explicitly close files when done.
> ? ?dictionary.close()
> ? ?return words
>
>
> def search(target, text):
> ? ?"""Return the result of two different searches for target in text.
>
> ? ?target should be a regular expression or regex object; text should
> ? ?be a string.
>
> ? ?Result returned is a two-tuple:
> ? ?(list of matches, regex match object or None)
> ? ?"""
> ? ?if isinstance(target, str):
> ? ? ? ?target = re.compile(target)
> ? ?a = target.findall(text)
> ? ?b = target.search(text)
> ? ?return (a, b)
>
>
> def print_stuff(i, target, text, a, b):
> ? ?# Boring helper function to do printing.
> ? ?print "counter = %d" % i
> ? ?print "target = %s" % target
> ? ?print "text = %s" % text
> ? ?print "findall = %s" % a
> ? ?print "search = %s" % b
> ? ?print
>
>
> def main(text):
> ? ?"""Print the results of many regex searches on text."""
> ? ?for i, word in get_dict_words():
> ? ? ? ?a, b, = search(word, text)
> ? ? ? ?print_stuff(i, word, text, a, b)
>
>
> # Now call it:
> fp = open(filename)
> text = fp.read()
> fp.close()
> main(text)
>
>
>
> I *think* this should give the same results you got.
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From smokefloat at gmail.com  Sat Sep  4 04:02:08 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 3 Sep 2010 22:02:08 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<201009041112.28651.steve@pearwood.info>
	<AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
Message-ID: <AANLkTikBvZ=oh+z862OiT4FLGv+sMDKHSpfvD=dj8FRb@mail.gmail.com>

On Fri, Sep 3, 2010 at 9:57 PM, David Hutto <smokefloat at gmail.com> wrote:
> First of all, I'll respond more thoroughly tomorrow, when I can review
> what you said more clearly, but for now I'll clarify.
>
> Here is the whole code that I'm using:
>
> http://pastebin.com/Ak8DFjrb
>
> On Fri, Sep 3, 2010 at 9:12 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On Fri, 3 Sep 2010 12:24:00 pm David Hutto wrote:
>>> In the below function I'm trying to iterate over the lines in a
>>> textfile, and try to match with a regex pattern that iterates over
>>> the lines in a dictionary(not {}, but turns a text list of
>>> alphabetical words into a list using readlines()).
>>>
>>> def regexfiles(filename):
>> [...]
>>
>> Your function does too much. It:
>>
>> 1 manages a file opened for input and output;
>> 2 manages a dictionary file;
>> 3 handles multiple searches at once (findall and search);
>> 4 handles print output;
>>
>> and you want it to do more:
>>
>> 5 handle multiple "select" terms.
>>
>>
>> Your function is also poorly defined -- I've read your description
>> repeatedly, and studied the code you give, and your three follow up
>> posts, and I still don't have the foggiest clue of what it's supposed
>> to accomplish!
>
> This is supposed to recreate a thought experiment I've heard about, in which,
> if you have an infinite amount of monkeys, with an infinite amount of
> typewriters,
> they'll eventually spit out Shakespeare.
>
> So, I create a random length file, with random characters, then regex
> it for the iteration
> of dictionary terms, but the regex is needed further for the
> theoretical exploratory purposes
> into the thought experiment. If dictionary patterns are matched, then
> it needs further regex
> for grammatically proper structures, even if they don't make
> sense(take mad libs for example),
> but are still grammatically correct, randomly produced files.
>
> So the bulldozer is needed.

I forgot, the randomly generated files with random len, are regexed,
for words,, then sorted into a range file
for len of the words contained, then regexed for grammatical
structure, and sorted again.

The latters of this have not been set in yet, just up until it finds
the len of real words in the file, then regex of
the grammar is next on my list. So it's more practice with regex, than
use a bulldozer to dig a fire pit.
>
>
> You do two searches on each iteration, but other than
>> print the results, you don't do anything with it.
>
> I had to print the results, in order to understand why using 'apple'
> in a variable
> yielded something different than when I iterated over the text file.
> The end result was that
> the list of dictionary words ['a\n'', 'b\n'] had \n, which was the
> extra character in the iteration I was referring to,
> and thanks to printing it out I was able to further isolate the
> problem through len().
>
> So rstrip() removed '\n' from the iterated term in the text file,
> yielding just the ['term'], and not ['term\n'].
>
> Print helps you see the info first hand.
>
>>
>> What is the *meaning* of the function? "regexfiles" is a meaningless
>> name, and your description "I'm trying to iterate over the lines in a
>> textfile, and try to match with a regex pattern that iterates over the
>> lines in a dictionary" is confusing -- the first part is fine, but what
>> do you mean by a regex that iterates over the lines in a dictionary?
>>
>> What is the purpose of a numeric variable called "search"? It looks like
>> a counter to me, not a search, it is incremented each time through the
>> loop. The right way to do that is with enumerate(), not a manual loop
>> variable.
>>
>> Why do you call readlines() instead of read()? This makes no sense to
>> me. You then convert a list of strings into a single string like this:
>>
>> readlines() returns ['a\n', 'b\n', 'c\n']
>> calling str() returns "['a\n', 'b\n', 'c\n']"
>>
>> but the result includes a lot of noise that weren't in the original
>> file: open and close square brackets, commas, quotation marks.
>>
>> I think perhaps you want ''.join(readlines()) instead, but even that is
>> silly, because you should just call read() and get 'a\nb\nc\n'.
>>
>> You should split this up into multiple functions. It will make
>> comprehension, readability, debugging and testing all much, much
>> easier. Code should be self-documenting -- ideally you will never need
>> to write a comment, because what the code does should be obvious from
>> your choice of function and variable names.
>>
>> I don't understand why you're using regex here. If I'm guessing
>> correctly, the entries in the dictionary are all ordinary (non-regex)
>> strings, like:
>>
>> ape
>> cat
>> dog
>>
>> only many, many more words :)
>>
>> Given that, using the re module is like using a bulldozer to crack a
>> peanut, and about as efficient. Instead of re.search(target, text) you
>> should just use text.find(target). There's no built-in equivalent to
>> re.findall, but it's not hard to write one:
>>
>> def findall(text, target):
>> ? ?results = []
>> ? ?start = 0
>> ? ?p = text.find(target)
>> ? ?while p != -1:
>> ? ? ? ?results.append(p)
>> ? ? ? ?p = text.find(target)
>> ? ?return results
>>
>> (This returns a list of starting positions rather than words. It's easy
>> to modify to do the other -- just append target instead of p.)
>>
>>
>> Anyway, here's my attempt to re-write your function. I've stuck to
>> regexes just in case, and there's lots of guess-work here, because I
>> don't understand what you're trying to accomplish, but here goes
>> nothing:
>
> The above should explain a little more, and tomorrow, I'll thoroughly
> review your post.
>>
>>
>> # Change this to use real English ?*wink*
>> DEFAULT_DICT = ?'/var/www/main/american-english'
>>
>> def get_dict_words(filename=''):
>> ? ?"""Return a list of words from the given dictionary file.
>>
>> ? ?If not given, a default dictionary is used.
>> ? ?The format of the file should be one word per line.
>> ? ?"""
>> ? ?if not filename:
>> ? ? ? ?filename = DEFAULT_DICT
>> ? ?# Don't use file, use open.
>> ? ?dictionary = open(filename)
>> ? ?words = dictionary.readlines()
>> ? ?# Best practice is to explicitly close files when done.
>> ? ?dictionary.close()
>> ? ?return words
>>
>>
>> def search(target, text):
>> ? ?"""Return the result of two different searches for target in text.
>>
>> ? ?target should be a regular expression or regex object; text should
>> ? ?be a string.
>>
>> ? ?Result returned is a two-tuple:
>> ? ?(list of matches, regex match object or None)
>> ? ?"""
>> ? ?if isinstance(target, str):
>> ? ? ? ?target = re.compile(target)
>> ? ?a = target.findall(text)
>> ? ?b = target.search(text)
>> ? ?return (a, b)
>>
>>
>> def print_stuff(i, target, text, a, b):
>> ? ?# Boring helper function to do printing.
>> ? ?print "counter = %d" % i
>> ? ?print "target = %s" % target
>> ? ?print "text = %s" % text
>> ? ?print "findall = %s" % a
>> ? ?print "search = %s" % b
>> ? ?print
>>
>>
>> def main(text):
>> ? ?"""Print the results of many regex searches on text."""
>> ? ?for i, word in get_dict_words():
>> ? ? ? ?a, b, = search(word, text)
>> ? ? ? ?print_stuff(i, word, text, a, b)
>>
>>
>> # Now call it:
>> fp = open(filename)
>> text = fp.read()
>> fp.close()
>> main(text)
>>
>>
>>
>> I *think* this should give the same results you got.
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>

From smokefloat at gmail.com  Sat Sep  4 04:21:17 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 3 Sep 2010 22:21:17 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTikBvZ=oh+z862OiT4FLGv+sMDKHSpfvD=dj8FRb@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<201009041112.28651.steve@pearwood.info>
	<AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
	<AANLkTikBvZ=oh+z862OiT4FLGv+sMDKHSpfvD=dj8FRb@mail.gmail.com>
Message-ID: <AANLkTino8y8eKHVnmVKBh3Tw431cWNS_wC_9_EDSk+Cj@mail.gmail.com>

snip

I'll go further with this though, just to get the response.
Hypothetically, if I wanted AI(artificial imagination),
then I would want random thoughts that made sense, every once in a
while. So, I hypothesize that the first step
in Artificial Imagination, is random thoughts, and then they have to
make grammatical/formulatic sense, hence the regex.

From alan.gauld at btinternet.com  Sat Sep  4 10:13:45 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 4 Sep 2010 09:13:45 +0100
Subject: [Tutor] best practices for where to set instance member
	variables
References: <1D673F86DDA00841A1216F04D1CE70D6426032E33E@EXCH2.nws.oregonstate.edu>
Message-ID: <i5sv3p$gth$1@dough.gmane.org>


"Gregory, Matthew" <matt.gregory at oregonstate.edu> wrote

> Is there a guideline on where instance member variables should
> be set within a class?  That is, is it a bad idea to set self 
> variables
> within private member functions rather than returning them to
> the enclosing caller?

There is nothing really specific to OOPP its just the normal rules
of defining functions. ie they should not have side effects so far
as is possible. So retrning results to the caller is generally 
preferred.
The only significant difference with methods is that you can look
up attributtes of self rather than pass them as arguments. This
is different to normal functions where we prefer passing arguments
rather than using global top access varuiables outside the function
defiitioon. But otherwise its all the same rules.

> Or should I avoid calls to internal functions from other member
> functions altogether (even if they are somewhat complex)?

No! This is one of the most powerful ways of achieving reuse.

For example if you define top level methods that are implemented
almost entirely by calling lower level methods then it is easy for
a subclass to modify the top level function by overriding just the
low level methods that it needs to change. That is a very powerful
technique for minimisiong change to the external interface and
thereby maintaining the Liskov Substitution Principle.

A concrete example:

class Shape:
    def draw(self, X, Y): pass
    def erase(self): pass
    def move(self,X,Y):
         self.erase()
         self.draw(X,Y)


Now subclasses only need to implement draw and erase
and they get move() for free.

> class Foo:
>    def __init__(self, a):
>        self.a = self._f1(a)
>    def _f1(self, a):
>        return a

This one is nearly always better.


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



From steve at pearwood.info  Sat Sep  4 12:16:12 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 4 Sep 2010 20:16:12 +1000
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<201009041112.28651.steve@pearwood.info>
	<AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
Message-ID: <201009042016.13581.steve@pearwood.info>

On Sat, 4 Sep 2010 11:57:00 am David Hutto wrote:
> First of all, I'll respond more thoroughly tomorrow, when I can
> review what you said more clearly, but for now I'll clarify.
>
> Here is the whole code that I'm using:
>
> http://pastebin.com/Ak8DFjrb

David, in genrandfiles() you say this:

    mkd = 0
    # This makes the range dir for range of the files for later matched
    # len of dictionary regex word matches
    if mkd == 0:
        makerangedirs()

Firstly, I don't understand the comment. All the words individually make 
sense, but altogether, they look like something generated by one of 
those monkeys with a typewriter... *wink*

Secondly, given that in the previous line you just set mkd = 0, is there 
any possible circumstance where the test "if mkd == 0" would *not* 
succeed? Why don't you just unconditionally call makerangedirs()?

    mkd = 0
    makerangedirs()



> This is supposed to recreate a thought experiment I've heard about,
> in which, if you have an infinite amount of monkeys, with an infinite
> amount of typewriters, they'll eventually spit out Shakespeare.

Ha ha, well, I don't want to discourage you, but the sun will burn out 
and die long before you get more than a couple of words of Shakespeare 
from this technique.

On the other hand, there are ways to randomly generate non-random text 
*incredibly quickly*. See http://en.wikipedia.org/wiki/Weasel_program 
for more detail.


-- 
Steven D'Aprano

From roberto03 at gmail.com  Sat Sep  4 13:10:05 2010
From: roberto03 at gmail.com (roberto)
Date: Sat, 4 Sep 2010 13:10:05 +0200
Subject: [Tutor] nested functions
Message-ID: <AANLkTi=3Hh=Sdpw1F=UPrWK050aZ+NR7f7ha2g=KZTKB@mail.gmail.com>

hello,
i have to plug two functions b() and c() inside another one a();
i wonder if the code defining b and c must be in the same text file of
a or it is possible to import b and c somehow, hence giving the code a
neater appearance

thank you !


-- 
roberto

From evert.rol at gmail.com  Sat Sep  4 13:25:51 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 4 Sep 2010 13:25:51 +0200
Subject: [Tutor] nested functions
In-Reply-To: <AANLkTi=3Hh=Sdpw1F=UPrWK050aZ+NR7f7ha2g=KZTKB@mail.gmail.com>
References: <AANLkTi=3Hh=Sdpw1F=UPrWK050aZ+NR7f7ha2g=KZTKB@mail.gmail.com>
Message-ID: <4248EC39-D022-4420-9F75-5821A4236A28@gmail.com>

> hello,
> i have to plug two functions b() and c() inside another one a();
> i wonder if the code defining b and c must be in the same text file of
> a or it is possible to import b and c somehow, hence giving the code a
> neater appearance

Definitely!
Read through http://docs.python.org/tutorial/modules.html, that should definitely get you started.

Basically, with b & c defined in file1.py (choose your own appropriate name), from file2.py you can do:

import file1

def a(...):
    file1.b()
    file1.c()

or (bit shorter, but can be less clear):

from file1 import b, c

def a(...):
    b()
    c()



  Evert


From lists at justuber.com  Sat Sep  4 16:14:37 2010
From: lists at justuber.com (lists)
Date: Sat, 4 Sep 2010 15:14:37 +0100
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
Message-ID: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>

Hi folks,

I'm new to Python, I'm working my way through some intro books, and I
have a question that I wonder if someone could help me with please?

This is my attempt at solving an exercise where the program is
supposed to flip a coin 100 times and then tell you the number of
heads and tails.

ATTEMPT 1 returns:

The coin landed on tails 100 times

The coin landed on heads 0 times

ATTEMPT 2 returns:

The coin landed on tails 75 times

The coin landed on heads 25 times

I expected to see the result in attempt 2. I don't fully understand
why the results are different however. Is it because Python only runs
the randint function once when I call it by the name I assigned to it
in attempt 1, but it runs the function fully on each iteration of the
loop in attempt 2? Why are these two things different?

Thanks in advance,

Chris
------------------------------------------------------------------
ATTEMPT 1
------------------------------------------------------------------
import random

heads = 0
tails = 0
tossNo = 0
toss = random.randint(1,2)

while tossNo <= 99:
    if toss == 1:
        heads += 1
        tossNo += 1
    elif toss == 2:
         tails += 1
         tossNo += 1

print "The coin landed on tails " + str(tails) + " times \n"
print "The coin landed on heads " + str(heads) + " times \n"

------------------------------------------------------------------
ATTEMPT 2
------------------------------------------------------------------
import random

heads = 0
tails = 0
tossNo = 0

while tossNo <= 99:
    if random.randint(1,2) == 1:
        heads += 1
        tossNo += 1
    elif random.randint(1,2) == 2:
         tails += 1
         tossNo += 1

print "The coin landed on tails " + str(tails) + " times \n"
print "The coin landed on heads " + str(heads) + " times \n"

From mehgcap at gmail.com  Sat Sep  4 16:48:04 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Sat, 4 Sep 2010 10:48:04 -0400
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
Message-ID: <AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>

On 9/4/10, lists <lists at justuber.com> wrote:
> Hi folks,
>
> I'm new to Python, I'm working my way through some intro books, and I
> have a question that I wonder if someone could help me with please?
>
> This is my attempt at solving an exercise where the program is
> supposed to flip a coin 100 times and then tell you the number of
> heads and tails.
>
> ATTEMPT 1 returns:
>
> The coin landed on tails 100 times
>
> The coin landed on heads 0 times
>
> ATTEMPT 2 returns:
>
> The coin landed on tails 75 times
>
> The coin landed on heads 25 times
>
> I expected to see the result in attempt 2. I don't fully understand
> why the results are different however. Is it because Python only runs
> the randint function once when I call it by the name I assigned to it
> in attempt 1, but it runs the function fully on each iteration of the
> loop in attempt 2? Why are these two things different?
Exactly. Essentially when you say
x=random.randint(1,2)
you are putting the value returned by randint into x, and this happens
only once. Had you moved that assignment into the while loop it would
keep replacing x, or toss in your case, with a random integer, but
because you just call it once it is only assigned once. Python, or any
language, would have no way of knowing that you want to reassign toss
each time. Loops are used to repeat actions, but you left the
assignment of your random int outside of the loop in attempt1 and so
there is no way for Python to know that you actually want toss updated
100 times. I hope I explained this okay.
>
> Thanks in advance,
>
> Chris
> ------------------------------------------------------------------
> ATTEMPT 1
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
> toss = random.randint(1,2)
>
> while tossNo <= 99:
>     if toss == 1:
>         heads += 1
>         tossNo += 1
>     elif toss == 2:
>          tails += 1
>          tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> ------------------------------------------------------------------
> ATTEMPT 2
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
>
> while tossNo <= 99:
>     if random.randint(1,2) == 1:
>         heads += 1
>         tossNo += 1
>     elif random.randint(1,2) == 2:
>          tails += 1
>          tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
> _______________________________________________
> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From wallenpb at gmail.com  Sat Sep  4 19:14:24 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 4 Sep 2010 12:14:24 -0500
Subject: [Tutor] iterating over less than a full list
Message-ID: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>

Say I have and iterable called some_stuff which is thousands of items in
length and I am looping thru it as such:

for x in some_stuff
     etc...

However, what if I want only to iterate through only the first ten items of
some_stuff, for testing purposes.  Is there a concise way of specifying that
in the for statement line?


-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/57a85d53/attachment.html>

From nitinpawar432 at gmail.com  Sat Sep  4 19:21:23 2010
From: nitinpawar432 at gmail.com (Nitin Pawar)
Date: Sat, 4 Sep 2010 22:51:23 +0530
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
Message-ID: <AANLkTimmtVA+Od45vfN9U0FUZ0qLxm3MzDnoVw9u7Gh4@mail.gmail.com>

if its a dictionary, then I think you will need to use limit

if its normal array you can use range(0,10) and access some_stuff[i]

On Sat, Sep 4, 2010 at 10:44 PM, Bill Allen <wallenpb at gmail.com> wrote:

> Say I have and iterable called some_stuff which is thousands of items in
> length and I am looping thru it as such:
>
> for x in some_stuff
>      etc...
>
> However, what if I want only to iterate through only the first ten items of
> some_stuff, for testing purposes.  Is there a concise way of specifying that
> in the for statement line?
>
>
> -Bill
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Nitin Pawar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/31f4b647/attachment-0001.html>

From sander.sweers at gmail.com  Sat Sep  4 19:25:01 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Sat, 4 Sep 2010 19:25:01 +0200
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
Message-ID: <AANLkTikoFjXMAKb6h8Jvt1Uf+8Wfy5BTnSyXu-X2pdPR@mail.gmail.com>

On 4 September 2010 19:14, Bill Allen <wallenpb at gmail.com> wrote:
> Say I have and iterable called some_stuff which is thousands of items in
> length and I am looping thru it as such:
>
> for x in some_stuff
> ???? etc...
>
> However, what if I want only to iterate through only the first ten items of
> some_stuff, for testing purposes.? Is there a concise way of specifying that
> in the for statement line?

You can use a slice or use a counter.

slice,

for x in some_stuff[:10]:
    etc

counter,

count = 0

for x in some_stuff:
    if x <= 10:
        print x
    else:
        break

greets
Sander

From sander.sweers at gmail.com  Sat Sep  4 19:29:23 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Sat, 4 Sep 2010 19:29:23 +0200
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTikoFjXMAKb6h8Jvt1Uf+8Wfy5BTnSyXu-X2pdPR@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
	<AANLkTikoFjXMAKb6h8Jvt1Uf+8Wfy5BTnSyXu-X2pdPR@mail.gmail.com>
Message-ID: <AANLkTinsHf6iLPVh0Osrfi0h8X4oPEg_XmsmDkx_vr4K@mail.gmail.com>

On 4 September 2010 19:25, Sander Sweers <sander.sweers at gmail.com> wrote:
> for x in some_stuff:
> ? ?if x <= 10:
> ? ? ? ?print x
> ? ?else:
> ? ? ? ?break

Oops, corrected version...

count = 0
for x in some_stuff:
    if count < 10:
        print x
        count +=1
    else:
        break

Greets
Sander

From augdawg09 at gmail.com  Sat Sep  4 19:40:13 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Sat, 4 Sep 2010 13:40:13 -0400
Subject: [Tutor] Creating custom GUI elements
Message-ID: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>

Hey guys,

How would I go about creating custom GUI elements? For example, if I wanted
to make a simple LEGO maker app, how would I write the code for the bricks
so that the user could drag them around and then build LEGO models?

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/af213e71/attachment.html>

From breamoreboy at yahoo.co.uk  Sat Sep  4 19:40:39 2010
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 04 Sep 2010 18:40:39 +0100
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTinsHf6iLPVh0Osrfi0h8X4oPEg_XmsmDkx_vr4K@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>	<AANLkTikoFjXMAKb6h8Jvt1Uf+8Wfy5BTnSyXu-X2pdPR@mail.gmail.com>
	<AANLkTinsHf6iLPVh0Osrfi0h8X4oPEg_XmsmDkx_vr4K@mail.gmail.com>
Message-ID: <i5u0as$vhd$1@dough.gmane.org>

On 04/09/2010 18:29, Sander Sweers wrote:
> On 4 September 2010 19:25, Sander Sweers<sander.sweers at gmail.com>  wrote:
>> for x in some_stuff:
>>     if x<= 10:
>>         print x
>>     else:
>>         break
>
> Oops, corrected version...
>
> count = 0
> for x in some_stuff:
>      if count<  10:
>          print x
>          count +=1
>      else:
>          break
>
> Greets
> Sander
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

I prefer

for i, x in enumerate(some_stuff):
     if i < 10:
         do_it(x)
     else:
         break


Cheers.

Mark Lawrence.


From steve at pearwood.info  Sat Sep  4 20:45:08 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Sep 2010 04:45:08 +1000
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
Message-ID: <201009050445.09098.steve@pearwood.info>

On Sun, 5 Sep 2010 03:14:24 am Bill Allen wrote:
> Say I have and iterable called some_stuff which is thousands of items
> in length and I am looping thru it as such:
>
> for x in some_stuff
>      etc...
>
> However, what if I want only to iterate through only the first ten
> items of some_stuff, for testing purposes.  Is there a concise way of
> specifying that in the for statement line?

The Pythonic way is to use itertools.islice.


import itertools

for x in itertools.islice(some_stuff, 10):
    blah blah blah


will stop at the end of some_stuff, or after 10 items, whichever happens 
first.

islice() optionally takes the full set of arguments that ordinary list 
slicing takes, so that islice(iterable, start, end, stride) is nearly 
the same as list(iterable)[start:end:stride].


-- 
Steven D'Aprano

From davea at ieee.org  Sat Sep  4 20:53:14 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 04 Sep 2010 14:53:14 -0400
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
Message-ID: <4C82959A.6010401@ieee.org>

lists wrote:
> Hi folks,
>
> I'm new to Python, I'm working my way through some intro books, and I
> have a question that I wonder if someone could help me with please?
>
> This is my attempt at solving an exercise where the program is
> supposed to flip a coin 100 times and then tell you the number of
> heads and tails.
>
> ATTEMPT 1 returns:
>
> The coin landed on tails 100 times
>
> The coin landed on heads 0 times
>
> ATTEMPT 2 returns:
>
> The coin landed on tails 75 times
>
> The coin landed on heads 25 times
>
> I expected to see the result in attempt 2. I don't fully understand
> why the results are different however. Is it because Python only runs
> the randint function once when I call it by the name I assigned to it
> in attempt 1, but it runs the function fully on each iteration of the
> loop in attempt 2? Why are these two things different?
>
> Thanks in advance,
>
> Chris
> ------------------------------------------------------------------
> ATTEMPT 1
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
> toss = random.randint(1,2)
>
> while tossNo <= 99:
>     if toss == 1:
>         heads += 1
>         tossNo += 1
>     elif toss == 2:
>          tails += 1
>          tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> ------------------------------------------------------------------
> ATTEMPT 2
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
>
> while tossNo <= 99:
>     if random.randint(1,2) == 1:
>         heads += 1
>         tossNo += 1
>     elif random.randint(1,2) == 2:
>          tails += 1
>          tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
>   
If your purpose was really to "give a name to a function," you can do 
that by:

toss = random.randint

Notice that we do *not* include the parentheses.  You want to call the 
function (by whatever name) inside the loop.  So change it to

while tossNo <= 99:
    if toss(1,2) == 1:
        heads += 1
        tossNo += 1


I have no idea why you have an elif clause in there.

DaveA


From gregbair at gmail.com  Sat Sep  4 20:54:21 2010
From: gregbair at gmail.com (Greg)
Date: Sat, 4 Sep 2010 14:54:21 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
Message-ID: <AANLkTi=f8vcedzMY7FPPYyRdGDyMdzfPhu8ufh6bbmj7@mail.gmail.com>

On Sat, Sep 4, 2010 at 1:40 PM, aug dawg <augdawg09 at gmail.com> wrote:

> Hey guys,
>
> How would I go about creating custom GUI elements? For example, if I wanted
> to make a simple LEGO maker app, how would I write the code for the bricks
> so that the user could drag them around and then build LEGO models?
>
> Thanks!
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
You'd probably want to look into one of the gui toolkits, wxPython, PyGTK,
PyQT, etc.  No need to reinvent the wheel.


-- 
Greg Bair
gregbair at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/fb976101/attachment-0001.html>

From davea at ieee.org  Sat Sep  4 21:07:16 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 04 Sep 2010 15:07:16 -0400
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
Message-ID: <4C8298E4.5040507@ieee.org>



Bill Allen wrote:
> Say I have and iterable called some_stuff which is thousands of items in
> length and I am looping thru it as such:
>
> for x in some_stuff
>      etc...
>
> However, what if I want only to iterate through only the first ten items of
> some_stuff, for testing purposes.  Is there a concise way of specifying that
> in the for statement line?
>
>
> -Bill
>
>   
You could use islice()

import itertools
for x in itertools.islice(some_stuff, 0, 10)
    print x

DaveA



From kushal.kumaran at gmail.com  Sat Sep  4 21:25:16 2010
From: kushal.kumaran at gmail.com (Kushal Kumaran)
Date: Sun, 05 Sep 2010 00:55:16 +0530
Subject: [Tutor] Giving a name to a function and calling it,
	rather	than calling the function directly
In-Reply-To: <AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>
Message-ID: <1283628316.29106.12.camel@Nokia-N900>

----- Original message -----
> On 9/4/10, lists <lists at justuber.com> wrote:
> > Hi folks,
> > 
> > I'm new to Python, I'm working my way through some intro books, and I
> > have a question that I wonder if someone could help me with please?
> > 
> > This is my attempt at solving an exercise where the program is
> > supposed to flip a coin 100 times and then tell you the number of
> > heads and tails.
> > 
> > ATTEMPT 1 returns:
> > 
> > The coin landed on tails 100 times
> > 
> > The coin landed on heads 0 times
> > 
> > ATTEMPT 2 returns:
> > 
> > The coin landed on tails 75 times
> > 
> > The coin landed on heads 25 times
> > 
> > I expected to see the result in attempt 2. I don't fully understand
> > why the results are different however. Is it because Python only runs
> > the randint function once when I call it by the name I assigned to it
> > in attempt 1, but it runs the function fully on each iteration of the
> > loop in attempt 2? Why are these two things different?
> Exactly. Essentially when you say
> x=random.randint(1,2)
> you are putting the value returned by randint into x, and this happens
> only once. Had you moved that assignment into the while loop it would
> keep replacing x, or toss in your case, with a random integer, but
> because you just call it once it is only assigned once. Python, or any
> language, would have no way of knowing that you want to reassign toss
> each time. Loops are used to repeat actions, but you left the
> assignment of your random int outside of the loop in attempt1 and so
> there is no way for Python to know that you actually want toss updated
> 100 times. I hope I explained this okay.
> > 
> > Thanks in advance,
> > 
> > Chris
> > ------------------------------------------------------------------
> > ATTEMPT 1
> > ------------------------------------------------------------------
> > import random
> > 
> > heads = 0
> > tails = 0
> > tossNo = 0
> > toss = random.randint(1,2)
> > 
> > while tossNo <= 99:
> > if toss == 1:
> > heads += 1
> > tossNo += 1
> > elif toss == 2:
> > tails += 1
> > tossNo += 1
> > 
> > print "The coin landed on tails " + str(tails) + " times \n"
> > print "The coin landed on heads " + str(heads) + " times \n"
> > 
> > ------------------------------------------------------------------
> > ATTEMPT 2
> > ------------------------------------------------------------------
> > import random
> > 
> > heads = 0
> > tails = 0
> > tossNo = 0
> > 
> > while tossNo <= 99:
> > if random.randint(1,2) == 1:
> > heads += 1
> > tossNo += 1
> > elif random.randint(1,2) == 2:
> > tails += 1
> > tossNo += 1
> > 
> > print "The coin landed on tails " + str(tails) + " times \n"
> > print "The coin landed on heads " + str(heads) + " times \n"

Alex has already answered the question you've asked.  I would just like to point out a subtle bug in your ATTEMPT 2 code.  What your code does is this:

- generate a random number 1 or 2
- test if it is 1
- if it isn't, generate a *new* random number
- test if this new random number is 2

That the number of 1s and 2s add up to 100 is an accident of the way you are counting them.

You should modify the code to generate a single random number each time through the loop and test whether it is 1 or 2.

-- 
sent from my Nokia N900
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/8754d443/attachment.html>

From alan.gauld at btinternet.com  Sat Sep  4 22:23:27 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 4 Sep 2010 21:23:27 +0100
Subject: [Tutor] Creating custom GUI elements
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
Message-ID: <i5u9s0$vm2$1@dough.gmane.org>


"aug dawg" <augdawg09 at gmail.com> wrote

> How would I go about creating custom GUI elements? For example, if I 
> wanted
> to make a simple LEGO maker app, how would I write the code for the 
> bricks
> so that the user could drag them around and then build LEGO models?

You find the nearest widget to what you want then you create a new 
subclass
of that widget. Then you override all the methods that act 
differently. Then you
add any new methods that are unique to your widget.

If there is nothing really like it you may need to go up to the 
abstract
widgets like Window and use composition to build a new widget built
from the standard ones. Thats even harder because thre is less you
get to reuse for free.

If its a 3D widget you may want to start with Pygame rather than a
standard GUI tooklit...

Warning, it's a non trivial exercise thats a pain to get exactly right 
unless its
a very minor tweak to an existing widget. But there is no real 
alternative.
The good news is that once you get it right the final app that uses it 
will be
a snap by comparison!

HTH,

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



From lists at justuber.com  Sat Sep  4 23:49:44 2010
From: lists at justuber.com (lists)
Date: Sat, 4 Sep 2010 22:49:44 +0100
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <1283628316.29106.12.camel@Nokia-N900>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>
	<1283628316.29106.12.camel@Nokia-N900>
Message-ID: <AANLkTim=8zNjKHYNCMX3YqUXkMpGNiTTVkQ-TBxSCXJX@mail.gmail.com>

>> On 9/4/10, lists <lists at justuber.com> wrote:
>> > Hi folks,
>> >
>> > I'm new to Python, I'm working my way through some intro books, and I
>> > have a question that I wonder if someone could help me with please?
>> >
>> > This is my attempt at solving an exercise where the program is
>> > supposed to flip a coin 100 times and then tell you the number of
>> > heads and tails.
>> >
>> > ATTEMPT 1 returns:
>> >
>> > The coin landed on tails 100 times
>> >
>> > The coin landed on heads 0 times
>> >
>> > ATTEMPT 2 returns:
>> >
>> > The coin landed on tails 75 times
>> >
>> > The coin landed on heads 25 times
>> >
>> > I expected to see the result in attempt 2. I don't fully understand
>> > why the results are different however. Is it because Python only runs
>> > the randint function once when I call it by the name I assigned to it
>> > in attempt 1, but it runs the function fully on each iteration of the
>> > loop in attempt 2? Why are these two things different?
>> Exactly. Essentially when you say
>> x=random.randint(1,2)
>> you are putting the value returned by randint into x, and this happens
>> only once. Had you moved that assignment into the while loop it would
>> keep replacing x, or toss in your case, with a random integer, but
>> because you just call it once it is only assigned once. Python, or any
>> language, would have no way of knowing that you want to reassign toss
>> each time. Loops are used to repeat actions, but you left the
>> assignment of your random int outside of the loop in attempt1 and so
>> there is no way for Python to know that you actually want toss updated
>> 100 times. I hope I explained this okay.
>> >
>> > Thanks in advance,
>> >
>> > Chris
>> > ------------------------------------------------------------------
>> > ATTEMPT 1
>> > ------------------------------------------------------------------
>> > import random
>> >
>> > heads = 0
>> > tails = 0
>> > tossNo = 0
>> > toss = random.randint(1,2)
>> >
>> > while tossNo <= 99:
>> > if toss == 1:
>> > heads += 1
>> > tossNo += 1
>> > elif toss == 2:
>> > tails += 1
>> > tossNo += 1
>> >
>> > print "The coin landed on tails " + str(tails) + " times \n"
>> > print "The coin landed on heads " + str(heads) + " times \n"
>> >
>> > ------------------------------------------------------------------
>> > ATTEMPT 2
>> > ------------------------------------------------------------------
>> > import random
>> >
>> > heads = 0
>> > tails = 0
>> > tossNo = 0
>> >
>> > while tossNo <= 99:
>> > if random.randint(1,2) == 1:
>> > heads += 1
>> > tossNo += 1
>> > elif random.randint(1,2) == 2:
>> > tails += 1
>> > tossNo += 1
>> >
>> > print "The coin landed on tails " + str(tails) + " times \n"
>> > print "The coin landed on heads " + str(heads) + " times \n"
>
> Alex has already answered the question you've asked. I would just like to
> point out a subtle bug in your ATTEMPT 2 code. What your code does is this:
>
> - generate a random number 1 or 2
> - test if it is 1
> - if it isn't, generate a *new* random number
> - test if this new random number is 2
>
> That the number of 1s and 2s add up to 100 is an accident of the way you are
> counting them.
>
> You should modify the code to generate a single random number each time
> through the loop and test whether it is 1 or 2.
>
> --
> sent from my Nokia N900
>

Thanks so much for your fast and friendly response guys, I'm bowled
over! As you can tell, I'm just starting out and it helps so much to
be able to get a helping hand like this.

I've taken on board what you have said and edited the code.

Kushal, it didn't occur to me that what I was doing in essence was
flipping a coin and attempting to get one result, then only flipping a
coin if I didn't get that first result. Now that I've edited the code
it gives much 'saner' results. I guess I'll have to be much more
careful in the future in the design stage!!

Here's what I have now:

--------------------------------------------
import random

heads = 0
tails = 0
tossNo = 0

while tossNo <= 99:
    coinToss = random.randint
    if coinToss(1,2) == 1:
        heads += 1
        tossNo += 1
    else:
        tails += 1
        tossNo += 1

print "The coin landed on tails " + str(tails) + " times \n"
print "The coin landed on heads " + str(heads) + " times \n"

From amonroe at columbus.rr.com  Sun Sep  5 00:24:31 2010
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 4 Sep 2010 18:24:31 -0400
Subject: [Tutor] Giving a name to a function and calling it,
	rather than calling the function directly
In-Reply-To: <AANLkTim=8zNjKHYNCMX3YqUXkMpGNiTTVkQ-TBxSCXJX@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>
	<1283628316.29106.12.camel@Nokia-N900>
	<AANLkTim=8zNjKHYNCMX3YqUXkMpGNiTTVkQ-TBxSCXJX@mail.gmail.com>
Message-ID: <13254518884.20100904182431@columbus.rr.com>

>     if coinToss(1,2) == 1:
>         heads += 1
>         tossNo += 1
>     else:
>         tails += 1
>         tossNo += 1

Looking good. You can hoist "tossNo += 1" out of each branch of your if
statement too, if you like, to make it even more streamlined (In
other words, execute it once, right after the coin flip, and before
the if-statement).

Alan


From lists at justuber.com  Sun Sep  5 00:39:07 2010
From: lists at justuber.com (lists)
Date: Sat, 4 Sep 2010 23:39:07 +0100
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <13254518884.20100904182431@columbus.rr.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<AANLkTikbM4Vg8H93NTxjTvN1tvJj1Ypoz0E+2Zheso0X@mail.gmail.com>
	<1283628316.29106.12.camel@Nokia-N900>
	<AANLkTim=8zNjKHYNCMX3YqUXkMpGNiTTVkQ-TBxSCXJX@mail.gmail.com>
	<13254518884.20100904182431@columbus.rr.com>
Message-ID: <AANLkTikf8KNQtk32rL8mbPu9rTENTYnHRyosx2R9f2ii@mail.gmail.com>

>> ? ? if coinToss(1,2) == 1:
>> ? ? ? ? heads += 1
>> ? ? ? ? tossNo += 1
>> ? ? else:
>> ? ? ? ? tails += 1
>> ? ? ? ? tossNo += 1
>
> Looking good. You can hoist "tossNo += 1" out of each branch of your if
> statement too, if you like, to make it even more streamlined (In
> other words, execute it once, right after the coin flip, and before
> the if-statement).
>
> Alan

Ah right, I get you. i.e

while tossNo <= 99:
    coinToss = random.randint
    tossNo += 1
    if coinToss(1,2) == 1:
        heads += 1
    else:
        tails += 1

That makes sense. :-)

Chris

From steve at pearwood.info  Sun Sep  5 02:25:32 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Sep 2010 10:25:32 +1000
Subject: [Tutor] Giving a name to a function and calling it,
	rather than calling the function directly
In-Reply-To: <AANLkTikf8KNQtk32rL8mbPu9rTENTYnHRyosx2R9f2ii@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<13254518884.20100904182431@columbus.rr.com>
	<AANLkTikf8KNQtk32rL8mbPu9rTENTYnHRyosx2R9f2ii@mail.gmail.com>
Message-ID: <201009051025.33454.steve@pearwood.info>

On Sun, 5 Sep 2010 08:39:07 am lists wrote:

> while tossNo <= 99:
>     coinToss = random.randint

Move that out of the loop. There's no need to make the assignment 100 
times.

>     tossNo += 1
>     if coinToss(1,2) == 1:
>         heads += 1
>     else:
>         tails += 1


Rather than count the number of loops yourself, let Python do the 
counting:

import random
coinToss = random.randint
heads = tails = 0
for tossNo in range(100):
    if coinToss(1, 2) == 1:
        heads += 1
    else: 
        tails += 1



Can we do better? Absolutely! Since we know that there are exactly 100 
coin tosses, and the number of heads plus the number of tails makes 
100, why are we counting them both?


import random
coinToss = random.randint
heads = 0
for tossNo in range(100):
    if coinToss(1, 2) == 1:
        heads += 1

print "The coin landed on tails " + str(100-heads) + " times."
print "The coin landed on heads " + str(heads) + " times."

One small weakness -- if we ever decide to change the number of coin 
tosses from 100 to some other number, we have to remember to change 100 
in two places. We can fix that by defining a named constant. Python 
doesn't actually have constants, so we use the naming convention "all 
uppercase means this is a constant, please don't modify it":


import random
coinToss = random.randint
heads = 0
COUNT = 100
for tossNo in range(COUNT):
    if coinToss(1, 2) == 1:
        heads += 1

print "The coin landed on tails " + str(COUNT-heads) + " times."
print "The coin landed on heads " + str(heads) + " times."


Can we do better? Absolutely -- nothing says that heads must be 1 and 
tails 2. If we make heads 1 and tails 0, we get a neat optimization:

import random
coinToss = random.randint
heads = 0
COUNT = 100
for tossNo in range(COUNT):
    heads += coinToss(0, 1)



Can we do better? Yes. The function "coinToss" is misleading. It doesn't 
toss a coin, not even figuratively speaking -- it takes two arguments, 
and returns an integer between those two limits. How is that related to 
tossing a coin? What are you going to do, this?

coinToss(1, 7)  # toss a seven-sided coin

No, that's ridiculous, and so the name is misleading. What your function 
does is return a random integer. That's no surprise, because it's just 
random.randint renamed. So let's fix that by making a proper coinToss 
function:

import random
def coinToss():
    return random.randint(0, 1)

heads = 0
COUNT = 100
for tossNo in range(COUNT):
    heads += coinToss()


Can we do better? Yes, for some definition of "better":

import random
import functools
coinToss = functools.partial(random.randint, 0, 1)
COUNT = 100
heads = sum(coinToss() for tossNo in range(COUNT))
print "The coin landed on tails %d times." % (COUNT-heads)
print "The coin landed on heads %d times." % heads


It's certainly short and concise. You should be able to guess what sum 
does, and if you can guess what functools.partial does you're doing 
well :)



-- 
Steven D'Aprano

From bgailer at gmail.com  Sun Sep  5 03:32:58 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 04 Sep 2010 21:32:58 -0400
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
Message-ID: <4C82F34A.90607@gmail.com>

  On 9/4/2010 10:14 AM, lists wrote:
> Hi folks,
>
> I'm new to Python, I'm working my way through some intro books, and I
> have a question that I wonder if someone could help me with please?
>
> This is my attempt at solving an exercise where the program is
> supposed to flip a coin 100 times and then tell you the number of
> heads and tails.
>
> ATTEMPT 1 returns:
>
> The coin landed on tails 100 times
>
> The coin landed on heads 0 times
>
> ATTEMPT 2 returns:
>
> The coin landed on tails 75 times
>
> The coin landed on heads 25 times
>
> I expected to see the result in attempt 2. I don't fully understand
> why the results are different however. Is it because Python only runs
> the randint function once when I call it by the name I assigned to it
> in attempt 1, but it runs the function fully on each iteration of the
> loop in attempt 2? Why are these two things different?
>
> Thanks in advance,
>
> Chris
> ------------------------------------------------------------------
> ATTEMPT 1
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
> toss = random.randint(1,2)
>
> while tossNo<= 99:
>      if toss == 1:
>          heads += 1
>          tossNo += 1
>      elif toss == 2:
>           tails += 1
>           tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> ------------------------------------------------------------------
> ATTEMPT 2
> ------------------------------------------------------------------
> import random
>
> heads = 0
> tails = 0
> tossNo = 0
>
You should have only 1 call to randint in the loop
> while tossNo<= 99:
>      if random.randint(1,2) == 1:
>          heads += 1
>          tossNo += 1
>      else:
>           tails += 1
>           tossNo += 1
>
> print "The coin landed on tails " + str(tails) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"

You can also simplify:

import random
heads = 0
tosses = 100
for i in range(tosses):
     heads += random.randint(0,1)
print "The coin landed on tails " + str(tosses - heads) + " times \n"
print "The coin landed on heads " + str(heads) + " times \n"

Or even simpler:

import random
tosses = 100
heads = sum(random.randint(0,1) for i in range(tosses))
print ...


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From wallenpb at gmail.com  Sun Sep  5 04:00:38 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 4 Sep 2010 21:00:38 -0500
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <4C8298E4.5040507@ieee.org>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>
	<4C8298E4.5040507@ieee.org>
Message-ID: <AANLkTikX+Kyr-NMtM=rc8rs0oY+PBRhg4W_T+v9-NeMe@mail.gmail.com>

Thanks to everyone who replied.   Some of the methods presented where some I
had thought of, others were new to me.   Particularly, I did not realize I
could apply a slice to a list.   The for x in some_stuff[:value] form worked
very well for my purposes.  I can also see I need to look into the itertools
module and see what goodies are to be found there.

-Bill



On Sat, Sep 4, 2010 at 2:07 PM, Dave Angel <davea at ieee.org> wrote:

>
>
> Bill Allen wrote:
>
>> Say I have and iterable called some_stuff which is thousands of items in
>> length and I am looping thru it as such:
>>
>> for x in some_stuff
>>     etc...
>>
>> However, what if I want only to iterate through only the first ten items
>> of
>> some_stuff, for testing purposes.  Is there a concise way of specifying
>> that
>> in the for statement line?
>>
>>
>> -Bill
>>
>>
>>
> You could use islice()
>
> import itertools
> for x in itertools.islice(some_stuff, 0, 10)
>   print x
>
> DaveA
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/01bda490/attachment.html>

From pine508 at hotmail.com  Sun Sep  5 04:35:13 2010
From: pine508 at hotmail.com (Che M)
Date: Sat, 4 Sep 2010 22:35:13 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
Message-ID: <SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>




> How would I go about creating custom GUI elements? For example, 
> if I wanted to make a simple LEGO maker app, how would I write the 
> code for the bricks so that the user could drag them around and then 
> build LEGO models?

For 2D legos, using the wxPython widget toolkit, you could probably use 
its widget called FloatCanvas to provide a space in which bitmaps can be 
moved around a screen and their coordinates tracked.  Then you would 
have to write the code that determines if the bitmap of the brick is in the 
right position to snap into place with another brick.

Che
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100904/255d5275/attachment.html>

From davea at ieee.org  Sun Sep  5 10:26:58 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 05 Sep 2010 04:26:58 -0400
Subject: [Tutor] iterating over less than a full list
In-Reply-To: <AANLkTikX+Kyr-NMtM=rc8rs0oY+PBRhg4W_T+v9-NeMe@mail.gmail.com>
References: <AANLkTiknWpyNcQJFTo=R5JpGDBm4tA_-GoZtLG6DVYVV@mail.gmail.com>	<4C8298E4.5040507@ieee.org>
	<AANLkTikX+Kyr-NMtM=rc8rs0oY+PBRhg4W_T+v9-NeMe@mail.gmail.com>
Message-ID: <4C835452.9070108@ieee.org>

Bill Allen wrote:
> Thanks to everyone who replied.   Some of the methods presented where some I
> had thought of, others were new to me.   Particularly, I did not realize I
> could apply a slice to a list.   The for x in some_stuff[:value] form worked
> very well for my purposes.  I can also see I need to look into the itertools
> module and see what goodies are to be found there.
>
> -Bill
>   
You're certainly welcome.

One advantage of itertools islice() is that it works on a generator (for 
example), not just on a list, tuple, string,etc..  For example, if you 
have a generator that generates all prime numbers, there's no way to 
turn that into a list, because it would be infinite in size.  Thus the 
usual [:10] syntax won't work on it.  But islice() will.

DaveA




From lists at justuber.com  Sun Sep  5 12:49:26 2010
From: lists at justuber.com (lists)
Date: Sun, 5 Sep 2010 11:49:26 +0100
Subject: [Tutor] Giving a name to a function and calling it,
 rather than calling the function directly
In-Reply-To: <4C82F34A.90607@gmail.com>
References: <AANLkTi=K9ywKit4q2_Msxh44M_=g5eHsLGebgOdXeGQc@mail.gmail.com>
	<4C82F34A.90607@gmail.com>
Message-ID: <AANLkTinzWanEwYCN0_2inZT4GG1u9dL2wupC9kC4LuNY@mail.gmail.com>

> ?On 9/4/2010 10:14 AM, lists wrote:
>>
>> Hi folks,
>>
>> I'm new to Python, I'm working my way through some intro books, and I
>> have a question that I wonder if someone could help me with please?
>>
>> This is my attempt at solving an exercise where the program is
>> supposed to flip a coin 100 times and then tell you the number of
>> heads and tails.
>>
>> ATTEMPT 1 returns:
>>
>> The coin landed on tails 100 times
>>
>> The coin landed on heads 0 times
>>
>> ATTEMPT 2 returns:
>>
>> The coin landed on tails 75 times
>>
>> The coin landed on heads 25 times
>>
>> I expected to see the result in attempt 2. I don't fully understand
>> why the results are different however. Is it because Python only runs
>> the randint function once when I call it by the name I assigned to it
>> in attempt 1, but it runs the function fully on each iteration of the
>> loop in attempt 2? Why are these two things different?
>>
>> Thanks in advance,
>>
>> Chris
>> ------------------------------------------------------------------
>> ATTEMPT 1
>> ------------------------------------------------------------------
>> import random
>>
>> heads = 0
>> tails = 0
>> tossNo = 0
>> toss = random.randint(1,2)
>>
>> while tossNo<= 99:
>> ? ? if toss == 1:
>> ? ? ? ? heads += 1
>> ? ? ? ? tossNo += 1
>> ? ? elif toss == 2:
>> ? ? ? ? ?tails += 1
>> ? ? ? ? ?tossNo += 1
>>
>> print "The coin landed on tails " + str(tails) + " times \n"
>> print "The coin landed on heads " + str(heads) + " times \n"
>>
>> ------------------------------------------------------------------
>> ATTEMPT 2
>> ------------------------------------------------------------------
>> import random
>>
>> heads = 0
>> tails = 0
>> tossNo = 0
>>
> You should have only 1 call to randint in the loop
>>
>> while tossNo<= 99:
>> ? ? if random.randint(1,2) == 1:
>> ? ? ? ? heads += 1
>> ? ? ? ? tossNo += 1
>> ? ? else:
>> ? ? ? ? ?tails += 1
>> ? ? ? ? ?tossNo += 1
>>
>> print "The coin landed on tails " + str(tails) + " times \n"
>> print "The coin landed on heads " + str(heads) + " times \n"
>
> You can also simplify:
>
> import random
> heads = 0
> tosses = 100
> for i in range(tosses):
> ? ?heads += random.randint(0,1)
> print "The coin landed on tails " + str(tosses - heads) + " times \n"
> print "The coin landed on heads " + str(heads) + " times \n"
>
> Or even simpler:
>
> import random
> tosses = 100
> heads = sum(random.randint(0,1) for i in range(tosses))
> print ...
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>

Thanks again all! Hopefully as I learn more I'll find it easier to
make the most efficient design choices :-)

Chris

From rwobben at hotmail.com  Sun Sep  5 15:44:09 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 5 Sep 2010 13:44:09 +0000
Subject: [Tutor] (no subject)
Message-ID: <SNT118-W4483BE98647EE302DC8667AE8F0@phx.gbl>


Hello, 

 

I have made this program as solution to a exercise from thinking like a computer scientist.

 

def encapsulate(val, seq):
if type(seq) == type(""):
return str(val)
if type(seq) == type([]):
return [val]
return (val,)
 

def insert_in_middle(val, seq):
middle = len(seq)/2
return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 
def make_empty(seq):
"""
>>> make_empty([1, 2, 3, 4])
[]
>>> make_empty(('a', 'b', 'c'))
()
>>> make_empty("No, not me!")
''
"""
if type(element) == type([]):
for word2 in seq :
word2 = ""
elif type(element) == type(()):
tup2 = list (seq)
while teller > tup2.len():
tup2[teller]=""
teller = teller + 1
seq = tuple(tup2)
else:
seq = ""

test = make_empty([1, 2, 3, 4])
print test

 

But now Im getting this error message :

 

Traceback (most recent call last):
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 33, in <module>
test = make_empty([1, 2, 3, 4])
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 21, in make_empty
if type(element) == type([]):
NameError: global name 'element' is not defined

 

What went wrong here ?

 

Roelof
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/d978fb45/attachment.html>

From steve at pearwood.info  Sun Sep  5 15:55:32 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 5 Sep 2010 23:55:32 +1000
Subject: [Tutor] (no subject)
In-Reply-To: <SNT118-W4483BE98647EE302DC8667AE8F0@phx.gbl>
References: <SNT118-W4483BE98647EE302DC8667AE8F0@phx.gbl>
Message-ID: <201009052355.33195.steve@pearwood.info>

On Sun, 5 Sep 2010 11:44:09 pm Roelof Wobben wrote:
> Hello,
>
> I have made this program as solution to a exercise from thinking like
> a computer scientist.
[...]
> But now Im getting this error message :
>
> Traceback (most recent call last):
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 33, in
> <module> test = make_empty([1, 2, 3, 4])
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 21, in
> make_empty if type(element) == type([]):
> NameError: global name 'element' is not defined
>
>
>
> What went wrong here ?

Read the error message again:

NameError: global name 'element' is not defined

You are trying to use something called "element", but you haven't 
created anything with that name. The error message even tells you were 
the problem is: line 21, in the function "make_empty".



-- 
Steven D'Aprano

From rwobben at hotmail.com  Sun Sep  5 16:17:06 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 5 Sep 2010 14:17:06 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <201009052355.33195.steve@pearwood.info>
References: <SNT118-W4483BE98647EE302DC8667AE8F0@phx.gbl>,
	<201009052355.33195.steve@pearwood.info>
Message-ID: <SNT118-W423F76EE3FCE94A3E3767AAE8F0@phx.gbl>



 

> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sun, 5 Sep 2010 23:55:32 +1000
> Subject: Re: [Tutor] (no subject)
> 
> On Sun, 5 Sep 2010 11:44:09 pm Roelof Wobben wrote:
> > Hello,
> >
> > I have made this program as solution to a exercise from thinking like
> > a computer scientist.
> [...]
> > But now Im getting this error message :
> >
> > Traceback (most recent call last):
> > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 33, in
> > <module> test = make_empty([1, 2, 3, 4])
> > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 21, in
> > make_empty if type(element) == type([]):
> > NameError: global name 'element' is not defined
> >
> >
> >
> > What went wrong here ?
> 
> Read the error message again:
> 
> NameError: global name 'element' is not defined
> 
> You are trying to use something called "element", but you haven't 
> created anything with that name. The error message even tells you were 
> the problem is: line 21, in the function "make_empty".
> 
> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


Hello Steven.

 

I understand the error message.

I follow this example in the book : http://openbookproject.net/thinkcs/python/english2e/ch11.html

And there element is not defined.

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/6741ef53/attachment.html>

From augdawg09 at gmail.com  Sun Sep  5 16:42:39 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Sun, 5 Sep 2010 10:42:39 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
Message-ID: <AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>

Would Pygame allow me to code all of the bricks instead of drawing them out?


On Sat, Sep 4, 2010 at 10:35 PM, Che M <pine508 at hotmail.com> wrote:

>
>
> > How would I go about creating custom GUI elements? For example,
> > if I wanted to make a simple LEGO maker app, how would I write the
> > code for the bricks so that the user could drag them around and then
> > build LEGO models?
>
> For 2D legos, using the wxPython widget toolkit, you could probably use
> its widget called FloatCanvas to provide a space in which bitmaps can be
> moved around a screen and their coordinates tracked.  Then you would
> have to write the code that determines if the bitmap of the brick is in the
>
> right position to snap into place with another brick.
>
> Che
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/8177a803/attachment-0001.html>

From andreengels at gmail.com  Sun Sep  5 16:42:45 2010
From: andreengels at gmail.com (Andre Engels)
Date: Sun, 5 Sep 2010 16:42:45 +0200
Subject: [Tutor] (no subject)
In-Reply-To: <SNT118-W423F76EE3FCE94A3E3767AAE8F0@phx.gbl>
References: <SNT118-W4483BE98647EE302DC8667AE8F0@phx.gbl>
	<201009052355.33195.steve@pearwood.info>
	<SNT118-W423F76EE3FCE94A3E3767AAE8F0@phx.gbl>
Message-ID: <AANLkTincM9ad1bmUy-0CJiD+NfwEtPixK7gbnxWhepkH@mail.gmail.com>

On Sun, Sep 5, 2010 at 4:17 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

> I understand the error message.
> I follow this example in the book :
> http://openbookproject.net/thinkcs/python/english2e/ch11.html
> And there element is not defined.

It is:

for element in nested_num_list:



-- 
Andr? Engels, andreengels at gmail.com

From pine508 at hotmail.com  Sun Sep  5 17:32:38 2010
From: pine508 at hotmail.com (Che M)
Date: Sun, 5 Sep 2010 11:32:38 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>,
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>,
	<AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
Message-ID: <SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>





> Would Pygame allow me to code all of the bricks instead of drawing them out?

I've never used Pygame; I have no idea.  What I was suggesting was just getting
a picture of a real or Lego-like brick from somewhere and using that image in
your program.  No drawing required.



 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/dba34c62/attachment.html>

From allison.william at gmail.com  Sun Sep  5 17:45:30 2010
From: allison.william at gmail.com (William Allison)
Date: Sun, 5 Sep 2010 11:45:30 -0400
Subject: [Tutor] Scrabble Help
Message-ID: <AANLkTikrcOCVWe=Hcr1S2GiDwXqE3CxuCUnijM7r2uMO@mail.gmail.com>

I'd like to write a program to help find words for Scrabble but I've
been having trouble
right from the beginning.

tiles = 'aeirstw'

dictionary = ['aardvark', 'cat', 'dog', 'taste', 'stare', 'wrist']

for word in range(len(dictionary)):
    for letter in range(len(dictionary[word])):
        if dictionary[word][letter] in tiles:
            nothing here quite works

I guess what I'm trying to do is step through every letter of every
word in my dictionary
and if that letter is in my tiles set it aside and compare it back to
the dictionary.  So in
the dictionary above, 'aardvark' would not be included because there
is only 1 'a' in my
tiles, but 'stare' and 'wrist' should be even though there are letters
left over in the tiles.

Am I going about this wrong?  Should I be looking at some module or a
regular expression?
Of course any advice is appreciated.
Thanks,
Will

From steve at pearwood.info  Sun Sep  5 18:56:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 6 Sep 2010 02:56:07 +1000
Subject: [Tutor] Scrabble Help
In-Reply-To: <AANLkTikrcOCVWe=Hcr1S2GiDwXqE3CxuCUnijM7r2uMO@mail.gmail.com>
References: <AANLkTikrcOCVWe=Hcr1S2GiDwXqE3CxuCUnijM7r2uMO@mail.gmail.com>
Message-ID: <201009060256.07835.steve@pearwood.info>

On Mon, 6 Sep 2010 01:45:30 am William Allison wrote:
> I'd like to write a program to help find words for Scrabble but I've
> been having trouble
> right from the beginning.
>
> tiles = 'aeirstw'
>
> dictionary = ['aardvark', 'cat', 'dog', 'taste', 'stare', 'wrist']
>
> for word in range(len(dictionary)):

That's misleading -- "word" isn't a word at all, it's a number.

>     for letter in range(len(dictionary[word])):

And likewise for letter.

>         if dictionary[word][letter] in tiles:
>             nothing here quite works

Better to write that loop as:

for word in dictionary:
    for letter in word:
        if letter in tiles:
            nothing here quite works either...

> I guess what I'm trying to do is step through every letter of every
> word in my dictionary
> and if that letter is in my tiles set it aside and compare it back to
> the dictionary.

The approach I think you're trying to take is to find out if each letter 
in the tiles matches a word in the dictionary. Let's separate that 
functionality into a function of its own:

def match(word, tiles):
    """Return true if every letter in word matches a tile."""
    for letter in word:
        if letter not in tiles:
            # Mismatch, so fail.
            return False
    # if we get to the end, all the letters must have matched
    return True


Let's test it:

>>> match("ape", "axdeps")
True
>>> match("cat", "axdeps")
False

So far so good! But we can simplify it, because there's a built-in 
function that does the same thing:


def match(word, tiles):
    """Return true if every letter in word matches a tile."""
    return all(letter in tiles for letter in word)

Don't worry too much about this though, because unfortunately this 
function, and my first version, have a logic bug: they fail to take 
into account repeated letters.

>>> match("moon", "monabc")  # Should give false.
True

Oops. Okay, let's think about the problem a bit more... it's not enough 
for each letter to be in the tiles, but that there must be at least as 
many copies as in the word. So, let's do another version:


def match(word, tiles):
    """Return true if every letter in word matches a tile."""
    for letter in word:
        if word.count(letter) > tiles.count(letter):
            return False
    return True

>>> match("man", "monabc")
True
>>> match("moon", "monabc")
False

That looks better! It's not the most efficient code in the word, but for 
comparing small words and a small set of tiles, it's good enough -- 
there's no need to optimize the code at this early stage. Get it 
working first, then make it fast.


So, putting it back together:

for word in dictionary:
    if match(word, tiles):
        play_word()  # whatever...



-- 
Steven D'Aprano

From augdawg09 at gmail.com  Sun Sep  5 19:37:54 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Sun, 5 Sep 2010 13:37:54 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
	<AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
	<SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>
Message-ID: <AANLkTin=qW85kxwC4sWxv4JRbDtRm+LWe99O73ykLFrL@mail.gmail.com>

That would work, but I want there to be a palette and then the user can drag
the Lego, flip it, and turn it. In order to do this, it would have to be 3D.


On Sun, Sep 5, 2010 at 11:32 AM, Che M <pine508 at hotmail.com> wrote:

>
>
>
> > Would Pygame allow me to code all of the bricks instead of drawing them
> out?
>
> I've never used Pygame; I have no idea.  What I was suggesting was just
> getting
> a picture of a real or Lego-like brick from somewhere and using that image
> in
> your program.  No drawing required.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/fffa9c50/attachment.html>

From smokefloat at gmail.com  Sun Sep  5 20:00:12 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 5 Sep 2010 14:00:12 -0400
Subject: [Tutor] Iterating through a list of replacement regex patterns
In-Reply-To: <201009042016.13581.steve@pearwood.info>
References: <AANLkTinKC63706XmnPqSb8CfbkQTmFKGbcrYKOiL240_@mail.gmail.com>
	<201009041112.28651.steve@pearwood.info>
	<AANLkTikfq2vSbihKrGfE3Bw1aG8dex2Xb3yZrgWaqjqy@mail.gmail.com>
	<201009042016.13581.steve@pearwood.info>
Message-ID: <AANLkTikLPXa3zCp5RgWNb-TR8QOkfDFfqZm9wtq_uJHk@mail.gmail.com>

On Sat, Sep 4, 2010 at 6:16 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 4 Sep 2010 11:57:00 am David Hutto wrote:
>> First of all, I'll respond more thoroughly tomorrow, when I can
>> review what you said more clearly, but for now I'll clarify.
>>
>> Here is the whole code that I'm using:
>>
>> http://pastebin.com/Ak8DFjrb
>
> David, in genrandfiles() you say this:
>
> ? ?mkd = 0
> ? ?# This makes the range dir for range of the files for later matched
> ? ?# len of dictionary regex word matches
> ? ?if mkd == 0:
> ? ? ? ?makerangedirs()
>
> Firstly, I don't understand the comment. All the words individually make
> sense, but altogether, they look like something generated by one of
> those monkeys with a typewriter... *wink*

The comments are mainly for me, which is why they get wordy, so I know
exactly why I placed it there.

>
> Secondly, given that in the previous line you just set mkd = 0, is there
> any possible circumstance where the test "if mkd == 0" would *not*
> succeed? Why don't you just unconditionally call makerangedirs()?
>
> ? ?mkd = 0
> ? ?makerangedirs()

This only called once to initially create the list of range files. If
it gets called again then it throws an error that the dir
already exists. I haven't checked to see, but I did this because I was
under the impression, that once the while loop is broken it went back
through the function. But once I have it working correctly, I'll
revise it a little more.
>
>
>
>> This is supposed to recreate a thought experiment I've heard about,
>> in which, if you have an infinite amount of monkeys, with an infinite
>> amount of typewriters, they'll eventually spit out Shakespeare.
>
> Ha ha, well, I don't want to discourage you, but the sun will burn out
> and die long before you get more than a couple of words of Shakespeare
> from this technique.

But that would be the point, that infinite monkeys with infinite typewriters,
would be forced to work until the end of time like good little domesticated
beasts of burden.

>
> On the other hand, there are ways to randomly generate non-random text
> *incredibly quickly*. See http://en.wikipedia.org/wiki/Weasel_program
> for more detail.

Will take a look at it later. The characters were just to start at the
initial. I was going to replace that with
randomly selected words from the dictionary instead because of the
above mentioned
time constraints on testing it continuously. Although I'd like to see
it, I might not have until
the sun burns out to test the theory.

Thanks for the help though.
David


>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From smokefloat at gmail.com  Sun Sep  5 20:04:25 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 5 Sep 2010 14:04:25 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTin=qW85kxwC4sWxv4JRbDtRm+LWe99O73ykLFrL@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
	<AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
	<SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>
	<AANLkTin=qW85kxwC4sWxv4JRbDtRm+LWe99O73ykLFrL@mail.gmail.com>
Message-ID: <AANLkTi=Bbq1JjRfW6GF-OW7Dfdew6SU5gTVGi3HCpDvO@mail.gmail.com>

I'd suggest you take a look at blender. It has a pretty easy to use
game engine with actuators, sensors and controllers, with a Python
scripts api. It'll take the time out of going 3-d with pygame, and you
can build the custom legos within it as well.

From mikelbt at gmail.com  Sun Sep  5 20:06:38 2010
From: mikelbt at gmail.com (Micheal Beatty)
Date: Sun, 05 Sep 2010 13:06:38 -0500
Subject: [Tutor] for loop results into list
Message-ID: <4C83DC2E.6020808@gmail.com>

  Hello all,

I'm having a little problem figuring out how to accomplish this simple 
task. I'd like to take a list of 6 numbers and add every permutation of 
those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 
+ 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a 
for loop, that was the easy part, now I'd like to take the results and 
count the number of times each number occurs.
My problem occurs when I try to create a list from the results of the 
for loop, it puts each individual number into its own list. I've looked 
everywhere for the solution to this and can find nothing to help.

Any suggestions would be much appreciated

Thanks
mwb

From evert.rol at gmail.com  Sun Sep  5 20:26:45 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 5 Sep 2010 20:26:45 +0200
Subject: [Tutor] for loop results into list
In-Reply-To: <4C83DC2E.6020808@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
Message-ID: <44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>

> Hello all,
> 
> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
> 
> Any suggestions would be much appreciated

If you had some code, that would be very helpful. Now it's a bit of guesswork what exactly you have (code tends to be clearer than a full paragraph or two of text).
At least, I currently don't understand what your problem is (or what your for-loop involves).
Eg, are you looping and calling a function recursively, do you have four nested loops (or nested list comprehensions)? Or some other convenient loop to step through all combinations?

Anway, if you have a recent Python version (2.7 or 3.1), the itertools module provides a handy utiity: http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
Eg,

>>> map(sum, combinations_with_replacement(range(1,7), 4))
[4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 22, 23, 24]

seems to do what you want.

But, I'd still say to adopt your own code first, and when you've learned from that, just use the one-liner above. You're most welcome to ask your question, best done in combination with code, actual output and expected output. Then we can point you in the right direction.

Cheers,

  Evert


From mikelbt at gmail.com  Sun Sep  5 20:51:41 2010
From: mikelbt at gmail.com (Micheal Beatty)
Date: Sun, 05 Sep 2010 13:51:41 -0500
Subject: [Tutor] for loop results into list
In-Reply-To: <44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
Message-ID: <4C83E6BD.8050706@gmail.com>

  On 09/05/2010 01:26 PM, Evert Rol wrote:
>> Hello all,
>>
>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
>>
>> Any suggestions would be much appreciated
> If you had some code, that would be very helpful. Now it's a bit of guesswork what exactly you have (code tends to be clearer than a full paragraph or two of text).
> At least, I currently don't understand what your problem is (or what your for-loop involves).
> Eg, are you looping and calling a function recursively, do you have four nested loops (or nested list comprehensions)? Or some other convenient loop to step through all combinations?
>
> Anway, if you have a recent Python version (2.7 or 3.1), the itertools module provides a handy utiity: http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
> Eg,
>
>>>> map(sum, combinations_with_replacement(range(1,7), 4))
> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 22, 23, 24]
>
> seems to do what you want.
>
> But, I'd still say to adopt your own code first, and when you've learned from that, just use the one-liner above. You're most welcome to ask your question, best done in combination with code, actual output and expected output. Then we can point you in the right direction.
>
> Cheers,
>
>    Evert
>
Thanks Evert, here is the code.


fourdsix = [1, 2, 3, 4, 5, 6]
for i in fourdsix:
     for j in fourdsix:
         for k in fourdsix:
             for l in fourdsix:
                 fourdsix_result = [i, j, k, l]
                 attribs = sum(fourdsix_result) - min(fourdsix_result)
                 print attribs

This gives me the proper results, now it's just a matter of getting it 
into a list so I can further work with the data.
I've tried the following
attrib_list = [attribs]

and
attrib_list = []
attrib_list.append(attribs)
print attrib_list

but these both only create a list of the last number.

I'm sure there is a pre-existing module that will do all of this for me 
but I'm trying to learn by doing.

Thanks
mwb


From andreengels at gmail.com  Sun Sep  5 21:16:47 2010
From: andreengels at gmail.com (Andre Engels)
Date: Sun, 5 Sep 2010 21:16:47 +0200
Subject: [Tutor] for loop results into list
In-Reply-To: <4C83E6BD.8050706@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
Message-ID: <AANLkTik_H8NLRiUuD6TN874NOnPNL6tGPKWqQXwUJFYy@mail.gmail.com>

On Sun, Sep 5, 2010 at 8:51 PM, Micheal Beatty <mikelbt at gmail.com> wrote:
> ?On 09/05/2010 01:26 PM, Evert Rol wrote:
>>>
>>> Hello all,
>>>
>>> I'm having a little problem figuring out how to accomplish this simple
>>> task. I'd like to take a list of 6 numbers and add every permutation of
>>> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1
>>> + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for
>>> loop, that was the easy part, now I'd like to take the results and count the
>>> number of times each number occurs.
>>> My problem occurs when I try to create a list from the results of the for
>>> loop, it puts each individual number into its own list. I've looked
>>> everywhere for the solution to this and can find nothing to help.
>>>
>>> Any suggestions would be much appreciated
>>
>> If you had some code, that would be very helpful. Now it's a bit of
>> guesswork what exactly you have (code tends to be clearer than a full
>> paragraph or two of text).
>> At least, I currently don't understand what your problem is (or what your
>> for-loop involves).
>> Eg, are you looping and calling a function recursively, do you have four
>> nested loops (or nested list comprehensions)? Or some other convenient loop
>> to step through all combinations?
>>
>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools
>> module provides a handy utiity:
>> http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>> Eg,
>>
>>>>> map(sum, combinations_with_replacement(range(1,7), 4))
>>
>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14,
>> 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12,
>> 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11,
>> 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15,
>> 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16,
>> 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20,
>> 19, 20, 21, 22, 20, 21, 22, 23, 24]
>>
>> seems to do what you want.
>>
>> But, I'd still say to adopt your own code first, and when you've learned
>> from that, just use the one-liner above. You're most welcome to ask your
>> question, best done in combination with code, actual output and expected
>> output. Then we can point you in the right direction.
>>
>> Cheers,
>>
>> ? Evert
>>
> Thanks Evert, here is the code.
>
>
> fourdsix = [1, 2, 3, 4, 5, 6]
> for i in fourdsix:
> ? ?for j in fourdsix:
> ? ? ? ?for k in fourdsix:
> ? ? ? ? ? ?for l in fourdsix:
> ? ? ? ? ? ? ? ?fourdsix_result = [i, j, k, l]
> ? ? ? ? ? ? ? ?attribs = sum(fourdsix_result) - min(fourdsix_result)
> ? ? ? ? ? ? ? ?print attribs
>
> This gives me the proper results, now it's just a matter of getting it into
> a list so I can further work with the data.
> I've tried the following
> attrib_list = [attribs]
>
> and
> attrib_list = []
> attrib_list.append(attribs)
> print attrib_list
>
> but these both only create a list of the last number.

Put the attrib_list = [] before the beginning of the outer loop, and
it should work as intended. Now you are creating a new list each time,
which is not what you want.



-- 
Andr? Engels, andreengels at gmail.com

From evert.rol at gmail.com  Sun Sep  5 21:22:20 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 5 Sep 2010 21:22:20 +0200
Subject: [Tutor] for loop results into list
In-Reply-To: <4C83E6BD.8050706@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
Message-ID: <AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>

>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
>>> 
>>> Any suggestions would be much appreciated
>> If you had some code, that would be very helpful. Now it's a bit of guesswork what exactly you have (code tends to be clearer than a full paragraph or two of text).
>> At least, I currently don't understand what your problem is (or what your for-loop involves).
>> Eg, are you looping and calling a function recursively, do you have four nested loops (or nested list comprehensions)? Or some other convenient loop to step through all combinations?
>> 
>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools module provides a handy utiity: http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>> Eg,
>> 
>>>>> map(sum, combinations_with_replacement(range(1,7), 4))
>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 22, 23, 24]
>> 
>> seems to do what you want.
>> 
>> But, I'd still say to adopt your own code first, and when you've learned from that, just use the one-liner above. You're most welcome to ask your question, best done in combination with code, actual output and expected output. Then we can point you in the right direction.
>> 
>> Cheers,
>> 
>>   Evert
>> 
> Thanks Evert, here is the code.
> 
> 
> fourdsix = [1, 2, 3, 4, 5, 6]
> for i in fourdsix:
>    for j in fourdsix:
>        for k in fourdsix:
>            for l in fourdsix:
>                fourdsix_result = [i, j, k, l]
>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>                print attribs
> 
> This gives me the proper results,

I'm not sure I understand that, because now you have a subtraction here; not sure what that does.

> now it's just a matter of getting it into a list so I can further work with the data.
> I've tried the following
> attrib_list = [attribs]
> 
> and
> attrib_list = []
> attrib_list.append(attribs)
> print attrib_list

This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
So then it's a matter of stepping through the numbers inside the list and counting their occurrences.
In fact, that could be done straight inside the quadruple nested for loops. One way I can think of, is using a dictionary, where the sum of the four-element list is the key, and the value increases by one each time. Eg:

try:
   counter[attribs] += 1
except KeyError:
   counter[attribs] = 1

or with dict.setdefault:

counter2[attribs] = counter2.setdefault(attribs, 0) + 1


(oh, and sorry: I missed the part where you wanted to count the number of times the sum appears in your initial email.)

> but these both only create a list of the last number.
> 
> I'm sure there is a pre-existing module that will do all of this for me but I'm trying to learn by doing.

Definitely. 
It's often fun to be surprised later by the amount of utilities available in the Python standard library, that would have solved a problem in a one-liner (also a bit frustrating, but not too much).

Cheers,

  Evert


From augdawg09 at gmail.com  Sun Sep  5 21:32:01 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Sun, 5 Sep 2010 15:32:01 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTi=Bbq1JjRfW6GF-OW7Dfdew6SU5gTVGi3HCpDvO@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
	<AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
	<SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>
	<AANLkTin=qW85kxwC4sWxv4JRbDtRm+LWe99O73ykLFrL@mail.gmail.com>
	<AANLkTi=Bbq1JjRfW6GF-OW7Dfdew6SU5gTVGi3HCpDvO@mail.gmail.com>
Message-ID: <AANLkTik6oQ9acss=T6utx74cJ+6kA20AAO2wL4yRxvTq@mail.gmail.com>

I took a look at Blender, but it all seemed very overwhelming. If I wanted
to, could I code all of the blocks? I want to have some functionality for
people adding their own bricks and other items.


On Sun, Sep 5, 2010 at 2:04 PM, David Hutto <smokefloat at gmail.com> wrote:

> I'd suggest you take a look at blender. It has a pretty easy to use
> game engine with actuators, sensors and controllers, with a Python
> scripts api. It'll take the time out of going 3-d with pygame, and you
> can build the custom legos within it as well.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/c15b2f6b/attachment.html>

From mikelbt at gmail.com  Sun Sep  5 21:58:02 2010
From: mikelbt at gmail.com (Mike Beatty)
Date: Sun, 5 Sep 2010 14:58:02 -0500
Subject: [Tutor] Fwd:  for loop results into list
In-Reply-To: <4C83F19C.6010107@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AANLkTik_H8NLRiUuD6TN874NOnPNL6tGPKWqQXwUJFYy@mail.gmail.com>
	<4C83F19C.6010107@gmail.com>
Message-ID: <AANLkTi=w6S0OzexaUKpTXMZDsBmoVEUoNW20ySzCJUXg@mail.gmail.com>

Should have sent this to the list too


---------- Forwarded message ----------
From: Micheal Beatty <mikelbt at gmail.com>
Date: Sun, Sep 5, 2010 at 2:38 PM
Subject: Re: [Tutor] for loop results into list
To: Andre Engels <andreengels at gmail.com>


?On 09/05/2010 02:16 PM, Andre Engels wrote:
>
> On Sun, Sep 5, 2010 at 8:51 PM, Micheal Beatty<mikelbt at gmail.com> ?wrote:
>>
>> ?On 09/05/2010 01:26 PM, Evert Rol wrote:
>>>>
>>>> Hello all,
>>>>
>>>> I'm having a little problem figuring out how to accomplish this simple
>>>> task. I'd like to take a list of 6 numbers and add every permutation of
>>>> those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1
>>>> + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for
>>>> loop, that was the easy part, now I'd like to take the results and count the
>>>> number of times each number occurs.
>>>> My problem occurs when I try to create a list from the results of the for
>>>> loop, it puts each individual number into its own list. I've looked
>>>> everywhere for the solution to this and can find nothing to help.
>>>>
>>>> Any suggestions would be much appreciated
>>>
>>> If you had some code, that would be very helpful. Now it's a bit of
>>> guesswork what exactly you have (code tends to be clearer than a full
>>> paragraph or two of text).
>>> At least, I currently don't understand what your problem is (or what your
>>> for-loop involves).
>>> Eg, are you looping and calling a function recursively, do you have four
>>> nested loops (or nested list comprehensions)? Or some other convenient loop
>>> to step through all combinations?
>>>
>>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools
>>> module provides a handy utiity:
>>> http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>>> Eg,
>>>
>>>>>> map(sum, combinations_with_replacement(range(1,7), 4))
>>>
>>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14,
>>> 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12,
>>> 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11,
>>> 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15,
>>> 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16,
>>> 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20,
>>> 19, 20, 21, 22, 20, 21, 22, 23, 24]
>>>
>>> seems to do what you want.
>>>
>>> But, I'd still say to adopt your own code first, and when you've learned
>>> from that, just use the one-liner above. You're most welcome to ask your
>>> question, best done in combination with code, actual output and expected
>>> output. Then we can point you in the right direction.
>>>
>>> Cheers,
>>>
>>> ? Evert
>>>
>> Thanks Evert, here is the code.
>>
>>
>> fourdsix = [1, 2, 3, 4, 5, 6]
>> for i in fourdsix:
>> ? ?for j in fourdsix:
>> ? ? ? ?for k in fourdsix:
>> ? ? ? ? ? ?for l in fourdsix:
>> ? ? ? ? ? ? ? ?fourdsix_result = [i, j, k, l]
>> ? ? ? ? ? ? ? ?attribs = sum(fourdsix_result) - min(fourdsix_result)
>> ? ? ? ? ? ? ? ?print attribs
>>
>> This gives me the proper results, now it's just a matter of getting it into
>> a list so I can further work with the data.
>> I've tried the following
>> attrib_list = [attribs]
>>
>> and
>> attrib_list = []
>> attrib_list.append(attribs)
>> print attrib_list
>>
>> but these both only create a list of the last number.
>
> Put the attrib_list = [] before the beginning of the outer loop, and
> it should work as intended. Now you are creating a new list each time,
> which is not what you want.
>
>
>
This gets me close, as it puts the results together into a list but it
goes through every set of permutations and gives me a list.
e.g.
[3]
[3, 4]
[3, 4, 5]
[3, 4, 5, 6]
[3, 4, 5, 6, 7] and so on

From mikelbt at gmail.com  Sun Sep  5 21:57:55 2010
From: mikelbt at gmail.com (Micheal Beatty)
Date: Sun, 05 Sep 2010 14:57:55 -0500
Subject: [Tutor] for loop results into list
In-Reply-To: <AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
Message-ID: <4C83F643.2060607@gmail.com>

  On 09/05/2010 02:22 PM, Evert Rol wrote:
>>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
>>>>
>>>> Any suggestions would be much appreciated
>>> If you had some code, that would be very helpful. Now it's a bit of guesswork what exactly you have (code tends to be clearer than a full paragraph or two of text).
>>> At least, I currently don't understand what your problem is (or what your for-loop involves).
>>> Eg, are you looping and calling a function recursively, do you have four nested loops (or nested list comprehensions)? Or some other convenient loop to step through all combinations?
>>>
>>> Anway, if you have a recent Python version (2.7 or 3.1), the itertools module provides a handy utiity: http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
>>> Eg,
>>>
>>>>>> map(sum, combinations_with_replacement(range(1,7), 4))
>>> [4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 22, 23, 24]
>>>
>>> seems to do what you want.
>>>
>>> But, I'd still say to adopt your own code first, and when you've learned from that, just use the one-liner above. You're most welcome to ask your question, best done in combination with code, actual output and expected output. Then we can point you in the right direction.
>>>
>>> Cheers,
>>>
>>>    Evert
>>>
>> Thanks Evert, here is the code.
>>
>>
>> fourdsix = [1, 2, 3, 4, 5, 6]
>> for i in fourdsix:
>>     for j in fourdsix:
>>         for k in fourdsix:
>>             for l in fourdsix:
>>                 fourdsix_result = [i, j, k, l]
>>                 attribs = sum(fourdsix_result) - min(fourdsix_result)
>>                 print attribs
>>
>> This gives me the proper results,
> I'm not sure I understand that, because now you have a subtraction here; not sure what that does.

It removes the lowest number in the group of 4. It's intended to 
replicate rolling four six sided dice, eliminating the lowest number and 
adding the remaining 3 dice roll results. I didn't mention it cause I 
felt it wasn't germane to the problem and it might needlessly complicate 
the situation.

>> now it's just a matter of getting it into a list so I can further work with the data.
>> I've tried the following
>> attrib_list = [attribs]
>>
>> and
>> attrib_list = []
>> attrib_list.append(attribs)
>> print attrib_list
> This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
> So then it's a matter of stepping through the numbers inside the list and counting their occurrences.

I've tried this in every place in the code, outside the loop, inside at 
each step of the loop and none of them get me what I want. Andre's 
suggestion that I put the empty list before the loop helped but it's 
still giving me multiple lists.
> In fact, that could be done straight inside the quadruple nested for loops. One way I can think of, is using a dictionary, where the sum of the four-element list is the key, and the value increases by one each time. Eg:
>
> try:
>     counter[attribs] += 1
> except KeyError:
>     counter[attribs] = 1
>
> or with dict.setdefault:
>
> counter2[attribs] = counter2.setdefault(attribs, 0) + 1
>
>
> (oh, and sorry: I missed the part where you wanted to count the number of times the sum appears in your initial email.)
>
>> but these both only create a list of the last number.
>>
>> I'm sure there is a pre-existing module that will do all of this for me but I'm trying to learn by doing.
> Definitely.
> It's often fun to be surprised later by the amount of utilities available in the Python standard library, that would have solved a problem in a one-liner (also a bit frustrating, but not too much).
>
> Cheers,
>
>    Evert
>


From augdawg09 at gmail.com  Sun Sep  5 22:12:53 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Sun, 5 Sep 2010 16:12:53 -0400
Subject: [Tutor] Creating custom GUI elements
In-Reply-To: <AANLkTi=pqGC10xLRMGL3wYa40NsGeSOx+62ZtgY5nUan@mail.gmail.com>
References: <AANLkTinePUjs8cnuieFWS4==xQCYQT+G0nkc-68AirFL@mail.gmail.com>
	<SNT127-W3023A7D271A0426677C876E08F0@phx.gbl>
	<AANLkTinNn7hPDHdQU=F_tgFmCtwKMOab1-wQ1-E63aAs@mail.gmail.com>
	<SNT127-W21C1DCD66134E19451C10BE08F0@phx.gbl>
	<AANLkTin=qW85kxwC4sWxv4JRbDtRm+LWe99O73ykLFrL@mail.gmail.com>
	<AANLkTi=Bbq1JjRfW6GF-OW7Dfdew6SU5gTVGi3HCpDvO@mail.gmail.com>
	<AANLkTik6oQ9acss=T6utx74cJ+6kA20AAO2wL4yRxvTq@mail.gmail.com>
	<AANLkTi=pqGC10xLRMGL3wYa40NsGeSOx+62ZtgY5nUan@mail.gmail.com>
Message-ID: <AANLkTikgKYE8v1J-_J5kkkATFFVbqQnoeN4mvpgu8c6Z@mail.gmail.com>

Okay, thanks everyone for all the help!


On Sun, Sep 5, 2010 at 3:40 PM, David Hutto <smokefloat at gmail.com> wrote:

> On Sun, Sep 5, 2010 at 3:32 PM, aug dawg <augdawg09 at gmail.com> wrote:
> > I took a look at Blender, but it all seemed very overwhelming. If I
> wanted
> > to, could I code all of the blocks? I want to have some functionality for
> > people adding their own bricks and other items.
>
> I think they would have to use blender for the blocks as well, then
> save the blend file as a runtime.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100905/ab1f218d/attachment.html>

From evert.rol at gmail.com  Sun Sep  5 22:16:13 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 5 Sep 2010 22:16:13 +0200
Subject: [Tutor] for loop results into list
In-Reply-To: <4C83F643.2060607@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
	<4C83F643.2060607@gmail.com>
Message-ID: <83D94488-ABEA-49AD-AD2C-E7B028466A80@gmail.com>

> 
>>>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.

<snip />

>>>>>  here is the code.
>>> 
>>> 
>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>> for i in fourdsix:
>>>    for j in fourdsix:
>>>        for k in fourdsix:
>>>            for l in fourdsix:
>>>                fourdsix_result = [i, j, k, l]
>>>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>                print attribs
>>> 
>>> This gives me the proper results,
>> I'm not sure I understand that, because now you have a subtraction here; not sure what that does.
> 
> It removes the lowest number in the group of 4. It's intended to replicate rolling four six sided dice, eliminating the lowest number and adding the remaining 3 dice roll results. I didn't mention it cause I felt it wasn't germane to the problem and it might needlessly complicate the situation.

<snip />

>>> attrib_list = []
>>> attrib_list.append(attribs)
>>> print attrib_list
>> This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
>> So then it's a matter of stepping through the numbers inside the list and counting their occurrences.
> 
> I've tried this in every place in the code, outside the loop, inside at each step of the loop and none of them get me what I want. Andre's suggestion that I put the empty list before the loop helped but it's still giving me multiple lists.

Can you send what you currently have? Sounds like you still have the first statement at some incorrect place in your code.



From mikelbt at gmail.com  Sun Sep  5 22:31:26 2010
From: mikelbt at gmail.com (Micheal Beatty)
Date: Sun, 05 Sep 2010 15:31:26 -0500
Subject: [Tutor] for loop results into list
In-Reply-To: <83D94488-ABEA-49AD-AD2C-E7B028466A80@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
	<4C83F643.2060607@gmail.com>
	<83D94488-ABEA-49AD-AD2C-E7B028466A80@gmail.com>
Message-ID: <4C83FE1E.60509@gmail.com>

  On 09/05/2010 03:16 PM, Evert Rol wrote:
>>>>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>>>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
> <snip />
>
>>>>>>   here is the code.
>>>>
>>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>>> for i in fourdsix:
>>>>     for j in fourdsix:
>>>>         for k in fourdsix:
>>>>             for l in fourdsix:
>>>>                 fourdsix_result = [i, j, k, l]
>>>>                 attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>>                 print attribs
>>>>
>>>> This gives me the proper results,
>>> I'm not sure I understand that, because now you have a subtraction here; not sure what that does.
>> It removes the lowest number in the group of 4. It's intended to replicate rolling four six sided dice, eliminating the lowest number and adding the remaining 3 dice roll results. I didn't mention it cause I felt it wasn't germane to the problem and it might needlessly complicate the situation.
> <snip />
>
>>>> attrib_list = []
>>>> attrib_list.append(attribs)
>>>> print attrib_list
>>> This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
>>> So then it's a matter of stepping through the numbers inside the list and counting their occurrences.
>> I've tried this in every place in the code, outside the loop, inside at each step of the loop and none of them get me what I want. Andre's suggestion that I put the empty list before the loop helped but it's still giving me multiple lists.
> Can you send what you currently have? Sounds like you still have the first statement at some incorrect place in your code.
>
>
Here is what I have.

# Program to determine frequency of each possible 4d6 die roll

attrib_list = []
fourdsix = [1, 2, 3, 4, 5, 6] #list of possible 1d6 die roll  results
for i in fourdsix:
     for j in fourdsix:
         for k in fourdsix:
             for l in fourdsix:
                 fourdsix_result = [i, j, k, l] # creating list from 
loop results
                 attribs = sum(fourdsix_result) - min(fourdsix_result)
                 attrib_list.append(attribs)
                 print attrib_list

This gets me multiple lists running through the loop.

Thanks
mike

From evert.rol at gmail.com  Sun Sep  5 22:48:35 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 5 Sep 2010 22:48:35 +0200
Subject: [Tutor] for loop results into list
In-Reply-To: <4C83FE1E.60509@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
	<4C83F643.2060607@gmail.com>
	<83D94488-ABEA-49AD-AD2C-E7B028466A80@gmail.com>
	<4C83FE1E.60509@gmail.com>
Message-ID: <73C717C1-9602-448A-969D-97CF9381D9AF@gmail.com>


On 5 Sep 2010, at 22:31 , Micheal Beatty wrote:

> On 09/05/2010 03:16 PM, Evert Rol wrote:
>>>>>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>>>>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
>> <snip />
>> 
>>>>>>>  here is the code.
>>>>> 
>>>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>>>> for i in fourdsix:
>>>>>    for j in fourdsix:
>>>>>        for k in fourdsix:
>>>>>            for l in fourdsix:
>>>>>                fourdsix_result = [i, j, k, l]
>>>>>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>>>                print attribs
>>>>> 
>>>>> This gives me the proper results,
>>>> I'm not sure I understand that, because now you have a subtraction here; not sure what that does.
>>> It removes the lowest number in the group of 4. It's intended to replicate rolling four six sided dice, eliminating the lowest number and adding the remaining 3 dice roll results. I didn't mention it cause I felt it wasn't germane to the problem and it might needlessly complicate the situation.
>> <snip />
>> 
>>>>> attrib_list = []
>>>>> attrib_list.append(attribs)
>>>>> print attrib_list
>>>> This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
>>>> So then it's a matter of stepping through the numbers inside the list and counting their occurrences.
>>> I've tried this in every place in the code, outside the loop, inside at each step of the loop and none of them get me what I want. Andre's suggestion that I put the empty list before the loop helped but it's still giving me multiple lists.
>> Can you send what you currently have? Sounds like you still have the first statement at some incorrect place in your code.
>> 
>> 
> Here is what I have.
> 
> # Program to determine frequency of each possible 4d6 die roll
> 
> attrib_list = []
> fourdsix = [1, 2, 3, 4, 5, 6] #list of possible 1d6 die roll  results
> for i in fourdsix:
>    for j in fourdsix:
>        for k in fourdsix:
>            for l in fourdsix:
>                fourdsix_result = [i, j, k, l] # creating list from loop results
>                attribs = sum(fourdsix_result) - min(fourdsix_result)
>                attrib_list.append(attribs)
>                print attrib_list
> 
> 
> This gets me multiple lists running through the loop.

Have you tried printing attrib_list at the very end of your code, *outside* all the nested loops?


I also noticed a mistake in a previous answer:

>>> map(sum, combinations_with_replacement(range(1,7), 4))

doesn't really work, because it produces eg [1, 1, 1, 2], but skips [2, 1, 1, 1], [1, 2, 1, 1] & [1, 1, 2, 1].

itertools.product does produce all of these combinations (and the docs even say "Equivalent to nested for-loops in a generator expression." for product()). 
Of course, when you want to throw away the lowest number, it becomes something like:

>>> map(lambda x: sum(x)-min(x), itertools.product(range(1,7), repeat=4))
(list with 1296 elements)

Just for future reference.



From mikelbt at gmail.com  Sun Sep  5 23:05:07 2010
From: mikelbt at gmail.com (Micheal Beatty)
Date: Sun, 05 Sep 2010 16:05:07 -0500
Subject: [Tutor] for loop results into list
In-Reply-To: <73C717C1-9602-448A-969D-97CF9381D9AF@gmail.com>
References: <4C83DC2E.6020808@gmail.com>
	<44B93BDC-9DE8-4FB1-B168-2ADD8AD9A49D@gmail.com>
	<4C83E6BD.8050706@gmail.com>
	<AA9A2599-2829-4E54-8D95-B939B2B09F35@gmail.com>
	<4C83F643.2060607@gmail.com>
	<83D94488-ABEA-49AD-AD2C-E7B028466A80@gmail.com>
	<4C83FE1E.60509@gmail.com>
	<73C717C1-9602-448A-969D-97CF9381D9AF@gmail.com>
Message-ID: <4C840603.9040509@gmail.com>

  On 09/05/2010 03:48 PM, Evert Rol wrote:
> On 5 Sep 2010, at 22:31 , Micheal Beatty wrote:
>
>> On 09/05/2010 03:16 PM, Evert Rol wrote:
>>>>>>>> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
>>>>>>>> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
>>> <snip />
>>>
>>>>>>>>   here is the code.
>>>>>> fourdsix = [1, 2, 3, 4, 5, 6]
>>>>>> for i in fourdsix:
>>>>>>     for j in fourdsix:
>>>>>>         for k in fourdsix:
>>>>>>             for l in fourdsix:
>>>>>>                 fourdsix_result = [i, j, k, l]
>>>>>>                 attribs = sum(fourdsix_result) - min(fourdsix_result)
>>>>>>                 print attribs
>>>>>>
>>>>>> This gives me the proper results,
>>>>> I'm not sure I understand that, because now you have a subtraction here; not sure what that does.
>>>> It removes the lowest number in the group of 4. It's intended to replicate rolling four six sided dice, eliminating the lowest number and adding the remaining 3 dice roll results. I didn't mention it cause I felt it wasn't germane to the problem and it might needlessly complicate the situation.
>>> <snip />
>>>
>>>>>> attrib_list = []
>>>>>> attrib_list.append(attribs)
>>>>>> print attrib_list
>>>>> This one should work, unless you've put it incorrectly inside the code. But otherwise, it will create the list you're looking for.
>>>>> So then it's a matter of stepping through the numbers inside the list and counting their occurrences.
>>>> I've tried this in every place in the code, outside the loop, inside at each step of the loop and none of them get me what I want. Andre's suggestion that I put the empty list before the loop helped but it's still giving me multiple lists.
>>> Can you send what you currently have? Sounds like you still have the first statement at some incorrect place in your code.
>>>
>>>
>> Here is what I have.
>>
>> # Program to determine frequency of each possible 4d6 die roll
>>
>> attrib_list = []
>> fourdsix = [1, 2, 3, 4, 5, 6] #list of possible 1d6 die roll  results
>> for i in fourdsix:
>>     for j in fourdsix:
>>         for k in fourdsix:
>>             for l in fourdsix:
>>                 fourdsix_result = [i, j, k, l] # creating list from loop results
>>                 attribs = sum(fourdsix_result) - min(fourdsix_result)
>>                 attrib_list.append(attribs)
>>                 print attrib_list
>>
>>
>> This gets me multiple lists running through the loop.
> Have you tried printing attrib_list at the very end of your code, *outside* all the nested loops?

*facepalm*

D'oh that worked.  I tried every other combination of placing the 
attrib_list commands except putting the print statement outside the loop 
by itself.

Thanks for finding that.

>
> I also noticed a mistake in a previous answer:
>
>>>> map(sum, combinations_with_replacement(range(1,7), 4))
> doesn't really work, because it produces eg [1, 1, 1, 2], but skips [2, 1, 1, 1], [1, 2, 1, 1]&  [1, 1, 2, 1].
>
> itertools.product does produce all of these combinations (and the docs even say "Equivalent to nested for-loops in a generator expression." for product()).
> Of course, when you want to throw away the lowest number, it becomes something like:
>
>>>> map(lambda x: sum(x)-min(x), itertools.product(range(1,7), repeat=4))
> (list with 1296 elements)
>
> Just for future reference.
I understand some of that but most of it is a little advanced for me 
right now. :-)

Thanks very much for your help.

mwb



From rwobben at hotmail.com  Mon Sep  6 08:34:35 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 6 Sep 2010 06:34:35 +0000
Subject: [Tutor] why do i get None as output
Message-ID: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>


Hello, 

 

I have this programm:

 

def encapsulate(val, seq):
    if type(seq) == type(""):
        return str(val)
    if type(seq) == type([]):
        return [val]
    return (val,)

 

def insert_in_middle(val, seq):
    middle = len(seq)/2
    return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 

def make_empty(seq):
    """
      >>> make_empty([1, 2, 3, 4])
      []
      >>> make_empty(('a', 'b', 'c'))
      ()
      >>> make_empty("No, not me!")
      ''
    """
    word2=""
    teller=0
    if type(seq) == type([]):
        teller=0 
        while teller < len(seq):
            seq[teller]=""
            teller = teller + 1 
    elif type(seq) == type(()):
        tup2 = list (seq)
        while teller > tup2.len():
            tup2[teller]=""
            teller = teller + 1
        seq = tuple(tup2)
    else:
        seq = ""
       
test = make_empty([1, 2, 3, 4])
print test

 

But now I get None as output instead of []

 

Can anyone explain why that happens ?

 

Roelof

    
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/d8f131e0/attachment.html>

From andreengels at gmail.com  Mon Sep  6 09:24:21 2010
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 6 Sep 2010 09:24:21 +0200
Subject: [Tutor] why do i get None as output
In-Reply-To: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
References: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
Message-ID: <AANLkTinmOgQc-wCHy-hrSQ-AbxBSugrc9Xw9asUJS1aU@mail.gmail.com>

On Mon, Sep 6, 2010 at 8:34 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
> Hello,
>
> I have this programm:
>
> def encapsulate(val, seq):
> ??? if type(seq) == type(""):
> ??????? return str(val)
> ??? if type(seq) == type([]):
> ??????? return [val]
> ??? return (val,)
>
> def insert_in_middle(val, seq):
> ??? middle = len(seq)/2
> ??? return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
> ??? """
> ????? >>> make_empty([1, 2, 3, 4])
> ????? []
> ????? >>> make_empty(('a', 'b', 'c'))
> ????? ()
> ????? >>> make_empty("No, not me!")
> ????? ''
> ??? """
> ??? word2=""
> ??? teller=0
> ??? if type(seq) == type([]):
> ??????? teller=0
> ??????? while teller < len(seq):
> ??????????? seq[teller]=""
> ??????????? teller = teller + 1
> ??? elif type(seq) == type(()):
> ??????? tup2 = list (seq)
> ??????? while teller > tup2.len():
> ??????????? tup2[teller]=""
> ??????????? teller = teller + 1
> ??????? seq = tuple(tup2)
> ??? else:
> ??????? seq = ""
>
> test = make_empty([1, 2, 3, 4])
> print test
>
> But now I get?None as output instead of []
>
> Can anyone explain why that happens ?

test = make_empty([1, 2, 3, 4]) makes test equal to the return value
of make_empty. But make_empty does not return anything, and in that
case its return value is made equal to empty. Compare:

def f(x):
    x = x + 1

def g(x):
    x = x + 1
    return x

def h(x):
    return x +1

print f(1)
>> None

print g(1)
>> 2

print h(1)
>> 2


-- 
Andr? Engels, andreengels at gmail.com

From alan.gauld at btinternet.com  Mon Sep  6 09:27:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 6 Sep 2010 08:27:31 +0100
Subject: [Tutor] why do i get None as output
References: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
Message-ID: <i6254u$taq$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote 

def make_empty(seq):
    word2=""
    teller=0
    if type(seq) == type([]):
        teller=0 
        while teller < len(seq):
            seq[teller]=""
            teller = teller + 1 
    elif type(seq) == type(()):
        tup2 = list (seq)
        while teller > tup2.len():
            tup2[teller]=""
            teller = teller + 1
        seq = tuple(tup2)
    else:
        seq = ""
       
test = make_empty([1, 2, 3, 4])

But now I get None as output instead of []

 
Because None is the default return value from a function.
If you do not return a value (which you don;t in this case) then 
Python automatically returns None.

You need to return something from your make_empty function.

Also, if all you want to do is return an empty version of 
whatever has been passed in there are much easier 
ways of doing it! And in fact, a list of empty strings is 
not the same as an empty list...


HTH

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



From rasjidw at gmail.com  Mon Sep  6 09:27:53 2010
From: rasjidw at gmail.com (Rasjid Wilcox)
Date: Mon, 6 Sep 2010 17:27:53 +1000
Subject: [Tutor] setattr vs __setattr__
Message-ID: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>

Hi all,

Suppose we have

class A(object):
    pass

a = A()

Is there any difference between

setattr(a, 'foo', 'bar)

and

a.__setattr__['foo'] = 'bar'

other than syntax?

And which is considered 'better' form in Python?

Cheers,

Rasjid.

From rwobben at hotmail.com  Mon Sep  6 09:41:18 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 6 Sep 2010 07:41:18 +0000
Subject: [Tutor] why do i get None as output
In-Reply-To: <i6254u$taq$1@dough.gmane.org>
References: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>,
	<i6254u$taq$1@dough.gmane.org>
Message-ID: <SNT118-W61FF9CF63827F61768C083AE700@phx.gbl>



 

> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Mon, 6 Sep 2010 08:27:31 +0100
> Subject: Re: [Tutor] why do i get None as output
> 
> 
> "Roelof Wobben" <rwobben at hotmail.com> wrote 
> 
> def make_empty(seq):
> word2=""
> teller=0
> if type(seq) == type([]):
> teller=0 
> while teller < len(seq):
> seq[teller]=""
> teller = teller + 1 
> elif type(seq) == type(()):
> tup2 = list (seq)
> while teller > tup2.len():
> tup2[teller]=""
> teller = teller + 1
> seq = tuple(tup2)
> else:
> seq = ""
> 
> test = make_empty([1, 2, 3, 4])
> 
> But now I get None as output instead of []
> 
> 
> Because None is the default return value from a function.
> If you do not return a value (which you don;t in this case) then 
> Python automatically returns None.
> 
> You need to return something from your make_empty function.
> 
> Also, if all you want to do is return an empty version of 
> whatever has been passed in there are much easier 
> ways of doing it! And in fact, a list of empty strings is 
> not the same as an empty list...
> 
> 
> HTH
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 

Oke, 

 

I put a return seq in the programm and it looks now like this :

 

def encapsulate(val, seq):
    if type(seq) == type(""):
        return str(val)
    if type(seq) == type([]):
        return [val]
    return (val,)

 

def insert_in_middle(val, seq):
    middle = len(seq)/2
    return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 

def make_empty(seq):
    """
      >>> make_empty([1, 2, 3, 4])
      []
      >>> make_empty(('a', 'b', 'c'))
      ()
      >>> make_empty("No, not me!")
      ''
    """
    if type(seq) == type([]):
        seq = []
    elif type(seq) == type(()):
        seq=()
    else:
        seq = ""
    return seq

 

if __name__ == "__main__":
    import doctest
    doctest.testmod()

 

This works but I don't think its what the exercise means :

 



Create a module named seqtools.py. Add the functions encapsulate and insert_in_middle from the chapter. Add doctests which test that these two functions work as intended with all three sequence types.

Add each of the following functions to seqtools.py:

def make_empty(seq):
    """
      >>> make_empty([1, 2, 3, 4])
      []
      >>> make_empty(('a', 'b', 'c'))
      ()
      >>> make_empty("No, not me!")
      ''
    """

So i think I have to use encapsulate and insert_in_middle. And I don't use it.

 

Roelof


 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/7c12ce6c/attachment-0001.html>

From andreengels at gmail.com  Mon Sep  6 09:53:54 2010
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 6 Sep 2010 09:53:54 +0200
Subject: [Tutor] why do i get None as output
In-Reply-To: <SNT118-W61FF9CF63827F61768C083AE700@phx.gbl>
References: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
	<i6254u$taq$1@dough.gmane.org>
	<SNT118-W61FF9CF63827F61768C083AE700@phx.gbl>
Message-ID: <AANLkTi=L5RQuBm-ObcaTFAQn9PXUFOsxDjxpp_2EJFaA@mail.gmail.com>

On Mon, Sep 6, 2010 at 9:41 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>
>> To: tutor at python.org
>> From: alan.gauld at btinternet.com
>> Date: Mon, 6 Sep 2010 08:27:31 +0100
>> Subject: Re: [Tutor] why do i get None as output
>>
>>
>> "Roelof Wobben" <rwobben at hotmail.com> wrote
>>
>> def make_empty(seq):
>> word2=""
>> teller=0
>> if type(seq) == type([]):
>> teller=0
>> while teller < len(seq):
>> seq[teller]=""
>> teller = teller + 1
>> elif type(seq) == type(()):
>> tup2 = list (seq)
>> while teller > tup2.len():
>> tup2[teller]=""
>> teller = teller + 1
>> seq = tuple(tup2)
>> else:
>> seq = ""
>>
>> test = make_empty([1, 2, 3, 4])
>>
>> But now I get None as output instead of []
>>
>>
>> Because None is the default return value from a function.
>> If you do not return a value (which you don;t in this case) then
>> Python automatically returns None.
>>
>> You need to return something from your make_empty function.
>>
>> Also, if all you want to do is return an empty version of
>> whatever has been passed in there are much easier
>> ways of doing it! And in fact, a list of empty strings is
>> not the same as an empty list...
>>
>>
>> HTH
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Oke,
>
> I put a return seq in the programm and it looks now like this :
>
> def encapsulate(val, seq):
> ??? if type(seq) == type(""):
> ??????? return str(val)
> ??? if type(seq) == type([]):
> ??????? return [val]
> ??? return (val,)
>
> def insert_in_middle(val, seq):
> ??? middle = len(seq)/2
> ??? return seq[:middle] + encapsulate(val, seq) + seq[middle:]
>
> def make_empty(seq):
> ??? """
> ????? >>> make_empty([1, 2, 3, 4])
> ????? []
> ????? >>> make_empty(('a', 'b', 'c'))
> ????? ()
> ????? >>> make_empty("No, not me!")
> ????? ''
> ??? """
> ??? if type(seq) == type([]):
> ??????? seq = []
> ??? elif type(seq) == type(()):
> ??????? seq=()
> ??? else:
> ??????? seq = ""
> ??? return seq
>
> if __name__ == "__main__":
> ??? import doctest
> ??? doctest.testmod()
>
> This works but I don't think its what the exercise means :
>
>
> Create a module named seqtools.py. Add the functions encapsulate and
> insert_in_middle from the chapter. Add doctests which test that these two
> functions work as intended with all three sequence types.
>
> Add each of the following functions to seqtools.py:
>
> def make_empty(seq):
>     """
>       >>> make_empty([1, 2, 3, 4])
>       []
>       >>> make_empty(('a', 'b', 'c'))
>       ()
>       >>> make_empty("No, not me!")
>       ''
>     """
>
> So?i think I have to use encapsulate and insert_in_middle. And I don't use
> it.

I don't think so. They don't look like the kind of thing that would be
useful for this function. In your example seqtools.py is supposed to
be a (toy example of a) library, a collection of functions to do
things with sequence-like objects to be used by other programs. These
functions in general need not have much to do with eachother, except
that they work on the same type of objects.


-- 
Andr? Engels, andreengels at gmail.com

From hugo.yoshi at gmail.com  Mon Sep  6 11:55:02 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 6 Sep 2010 11:55:02 +0200
Subject: [Tutor] setattr vs __setattr__
In-Reply-To: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>
References: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>
Message-ID: <AANLkTi=-mfoQFPM+26Ae5k2O_v163Fon7UDKJ2Kmjq++@mail.gmail.com>

On Mon, Sep 6, 2010 at 9:27 AM, Rasjid Wilcox <rasjidw at gmail.com> wrote:
> Hi all,
>
> Suppose we have
>
> class A(object):
> ? ?pass
>
> a = A()
>
> Is there any difference between
>
> setattr(a, 'foo', 'bar)
>
> and
>
> a.__setattr__['foo'] = 'bar'
>

Did you mean a.__setattr__('foo', 'bar')? That's the same thing,
though you'd generally use a.foo = 'bar' or setattr(a, 'foo', 'bar'),
in that order of preference.

If you meant a.__dict__['foo'] = 'bar', that may or may not be the
same thing depending on the class. It works for instances of object,
but fails for any class that defines __slots__, for example.  I'd
generally recommend you don't do it. Use setattr instead.

Hugo

From rasjidw at gmail.com  Mon Sep  6 13:03:30 2010
From: rasjidw at gmail.com (Rasjid Wilcox)
Date: Mon, 6 Sep 2010 21:03:30 +1000
Subject: [Tutor] setattr vs __setattr__
In-Reply-To: <AANLkTi=-mfoQFPM+26Ae5k2O_v163Fon7UDKJ2Kmjq++@mail.gmail.com>
References: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>
	<AANLkTi=-mfoQFPM+26Ae5k2O_v163Fon7UDKJ2Kmjq++@mail.gmail.com>
Message-ID: <AANLkTik8OruFPbnU3JHj-te_arvJpUuXrZLwF51vz98a@mail.gmail.com>

On 6 September 2010 19:55, Hugo Arts <hugo.yoshi at gmail.com> wrote:
> On Mon, Sep 6, 2010 at 9:27 AM, Rasjid Wilcox <rasjidw at gmail.com> wrote:
>> Hi all,
>>
>> Suppose we have
>>
>> class A(object):
>> ? ?pass
>>
>> a = A()
>>
>> Is there any difference between
>>
>> setattr(a, 'foo', 'bar)
>>
>> and
>>
>> a.__setattr__['foo'] = 'bar'
>>
>
> Did you mean a.__setattr__('foo', 'bar')? That's the same thing,
> though you'd generally use a.foo = 'bar' or setattr(a, 'foo', 'bar'),
> in that order of preference.

Sorry, yes, a.__setattr__('foo', 'bar') is what I meant.  I'm actually
iterating over a number of attributes, so AFASK the first form is not
an option.  I've been using

for attr_name in name_list:
    setattr(a, attr_name, getattr(b, attr_name))

to copy the attributes from one type of class to another, and it is
not quite as readable as I would like.  Actually, I've just thought
that the best option would be to make both classes dictionary like
objects with automatic translation between a['foo'] and a.foo.
Sqlalchemy uses that for its query result objects with good effect.

Cheers,

Rasjid.

From augdawg09 at gmail.com  Mon Sep  6 17:48:29 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Mon, 6 Sep 2010 11:48:29 -0400
Subject: [Tutor] Arguments from the command line
Message-ID: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>

I've seen Python programs that can be activated from the command line. For
example:

hg

This displays a list of commands for the Mercurial revision control system.
But another command is this:

hg commit "This is a commit name"

Mercurial is written in Python. I know that commit is a function that
commits to a repo, but what command does the program use in order to get the
commit name, like "This is a commit name" (This would make a commit with
"This is a commit name" as the commit name)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/680b50d0/attachment.html>

From hugo.yoshi at gmail.com  Mon Sep  6 18:08:27 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 6 Sep 2010 18:08:27 +0200
Subject: [Tutor] Arguments from the command line
In-Reply-To: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
References: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
Message-ID: <AANLkTi=+Qb4n68bj1G6prfpORaNGdWDCJ1ogJDwt7bHw@mail.gmail.com>

On Mon, Sep 6, 2010 at 5:48 PM, aug dawg <augdawg09 at gmail.com> wrote:
> I've seen Python programs that can be activated from the command line. For
> example:
> hg
>
> This displays a list of commands for the Mercurial revision control system.
> But another command is this:
> hg commit "This is a commit name"
> Mercurial is written in Python. I know that commit is a function that
> commits to a repo, but what command does the program use in order to get the
> commit name, like "This is a commit name" (This would make a commit with
> "This is a commit name" as the commit name)
>

sys.argv is a list of all arguments from the command line. However,
you'll rarely deal with it directly, there's various modules that deal
with handling arguments. I believe the current one is argparse:
http://docs.python.org/library/argparse.html#module-argparse

Hugo

From mark at martialfit.net  Mon Sep  6 18:11:57 2010
From: mark at martialfit.net (Mark Weil)
Date: Mon, 6 Sep 2010 09:11:57 -0700
Subject: [Tutor] Arguments from the command line
In-Reply-To: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
References: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
Message-ID: <AANLkTikAG5oskv6JRtPmgAZqfotyOsmE5aMb4aF9Onuy@mail.gmail.com>

I think you're looking for this:

http://docs.python.org/library/argparse.html

you'll also want to read up on sys.argv

http://docs.python.org/library/sys.html#sys.argv



On Mon, Sep 6, 2010 at 8:48 AM, aug dawg <augdawg09 at gmail.com> wrote:

> I've seen Python programs that can be activated from the command line. For
> example:
>
> hg
>
> This displays a list of commands for the Mercurial revision control system.
> But another command is this:
>
> hg commit "This is a commit name"
>
> Mercurial is written in Python. I know that commit is a function that
> commits to a repo, but what command does the program use in order to get the
> commit name, like "This is a commit name" (This would make a commit with
> "This is a commit name" as the commit name)
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/9c28a6a9/attachment.html>

From bgailer at gmail.com  Mon Sep  6 18:20:12 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 06 Sep 2010 12:20:12 -0400
Subject: [Tutor] Arguments from the command line
In-Reply-To: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
References: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
Message-ID: <4C8514BC.7080106@gmail.com>

  On 9/6/2010 11:48 AM, aug dawg wrote:
> I've seen Python programs that can be activated from the command line. 
> For example:
>
> hg
>
> This displays a list of commands for the Mercurial revision control 
> system. But another command is this:
>
> hg commit "This is a commit name"
>
> Mercurial is written in Python. I know that commit is a function that 
> commits to a repo, but what command does the program use in order to 
> get the commit name, like "This is a commit name" (This would make a 
> commit with "This is a commit name" as the commit name)
hg.py:
import sys
print sys.argv

$hg commit "This is a commit name"
['C:\\hg.py', 'commit', 'This is a commit name']

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Mon Sep  6 19:32:45 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 6 Sep 2010 17:32:45 +0000
Subject: [Tutor] exercise correct ??
Message-ID: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>


Hello, 

 

I have this programm :

 

def index_of(val, seq, start=0):
    """
      >>> index_of(9, [1, 7, 11, 9, 10])
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
      6
      >>> index_of('y', 'happy birthday')
      4
      >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
      1
      >>> index_of(5, [2, 3, 4])
      -1
      >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
      -1
    """
    plek = 0 
    if type(seq) == type([]):
        plek = seq.index(val)
    elif type(seq) == type(()):
        seq = list (seq)
        plek = seq.index(val)
    else :
        plek = seq.find(val)
    return plek 
    

 

But I get this message :

 

File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in __main__.index_of
Failed example:
index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
Expected:
6
Got:
3

 

But in that tuple 5 is on position 3.

 

Is the exercise here wrong ?

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/d6a68a3b/attachment-0001.html>

From kwl at aber.ac.uk  Mon Sep  6 16:16:28 2010
From: kwl at aber.ac.uk (Keith Lucas)
Date: Mon, 6 Sep 2010 14:16:28 -0000
Subject: [Tutor] Simple Python Problem
Message-ID: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>

What is wrong with the following, apparently almost straight out of Python Programming
by Michael Dawson?



# Declare variable and initialise (overkill!).
name = "ABCDEFG"

# Get value.
name = input("What is your name? ")

# Echo value
print(name)

# Issue greeting
print("Hi ", name)


Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32 Type
"copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
What is your name? Keith

Traceback (most recent call last):
  File "C:\Documents and Settings\User\My Documents\My Files\Staff\Keith
Lucas\Education\Python\Learn_Input_01.py", line 5, in <module>
    name = input("What is your name? ")
  File "<string>", line 1, in <module>
NameError: name 'Keith' is not defined





From mydomdom at gmail.com  Mon Sep  6 19:46:04 2010
From: mydomdom at gmail.com (Dominique)
Date: Mon, 6 Sep 2010 17:46:04 +0000 (UTC)
Subject: [Tutor] Multiple versions of python and paths problems
Message-ID: <loom.20100906T191621-218@post.gmane.org>

Hello,

I usually use python 2.6 and several packages. Everything's fine.

At present, I'm trying to run a package which is only available with python 2.5.
So, i installed 2.5 and the various dependencies needed to run this package:
PIL, numpy... which were already installed in my 2.6 site-packages.

Unfortunately, when I try to run it under Idle 2.5, python goes in the 2.6
site-packages to get these dependencies (PIL,...) and throws me a traceback (due
to incompatibilities).

I understand it is a paths problem.

So, I added the path of python 2.5 and that of my application to the path and
Pythonpath in the windows environ variables.
But the same problems arise.

So, I tried to load the normal 2.5 Idle and unload ('remove') everything related
to 2.6 from sys.path, but it's strangely not working completely.

Finally, I managed to run the program :
- by launching D:\python25\python.exe -E -S in a console (which seems to prevent
python from loading the paths)
- then appending the application path to sys.path
but it's really not fun working with this bloody windows console where cut and
paste is impossible...

So, here is my question:
How can I force py2.5 to go and find the dependencies only in the 2.5
site-packages ?

Thanks in advance for your help.

Dominique


From alan.gauld at btinternet.com  Mon Sep  6 19:48:00 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 6 Sep 2010 18:48:00 +0100
Subject: [Tutor] Simple Python Problem
References: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>
Message-ID: <i639gb$lsu$1@dough.gmane.org>


"Keith Lucas" <kwl at aber.ac.uk> wrote

> What is wrong with the following, apparently almost straight out of 
> Python Programming
> by Michael Dawson?
>

You are using Python v2, the tutorial seems to be written for v3.
There are big diffeernces in syntax between them, v3 is NOT
backwards compatible with v2.

> # Get value.
> name = input("What is your name? ")

In v2 that would be

name = raw_input("What is your name")

> Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit 
> (Intel)] on win32 Type
> "copyright", "credits" or "license()" for more information.
>>>> ================================ RESTART 
>>>> ================================
> What is your name? Keith

I think there is a trick in V2.7 to make it act more like v3 but 
someone
else will need to tell you what it is... :-)

HTH,

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



From fal at libero.it  Mon Sep  6 20:18:33 2010
From: fal at libero.it (Francesco Loffredo)
Date: Mon, 06 Sep 2010 20:18:33 +0200
Subject: [Tutor] why do i get None as output
In-Reply-To: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
References: <SNT118-W38B34EF93CBB4D50D39F6DAE700@phx.gbl>
Message-ID: <4C853079.2060907@libero.it>

On 06/09/2010 8.34, Roelof Wobben wrote:
> Hello,
>
> I have this programm:
> ...
> def make_empty(seq):
> """
>  >>> make_empty([1, 2, 3, 4])
> []
>  >>> make_empty(('a', 'b', 'c'))
> ()
>  >>> make_empty("No, not me!")
> ''
> """
> word2=""
> teller=0
> if type(seq) == type([]):
> teller=0
> while teller < len(seq):
> seq[teller]=""
> teller = teller + 1
> elif type(seq) == type(()):
> tup2 = list (seq)
> while teller > tup2.len():
> tup2[teller]=""
> teller = teller + 1
> seq = tuple(tup2)
> else:
> seq = ""
>
> test = make_empty([1, 2, 3, 4])
> print test
>
> But now I get None as output instead of []

I would add a line like:

return seq

at the end of the  make_empty  function.

>
> Can anyone explain why that happens ?
I think Python doesn't know what exactly is the value you need to 
receive from the  make_empty  function. That's why I'd make it clear. 
Otherwise, you know what happens...

I quote the following from
http://diveintopython.org/getting_to_know_python/declaring_functions.html
"In fact, every Python function returns a value; if the function ever 
executes a return statement, it will return that value, otherwise it 
will return None, the Python null value."

> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3115 -  Data di rilascio: 09/05/10 08:34:00

From wallenpb at gmail.com  Mon Sep  6 20:31:18 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Mon, 6 Sep 2010 13:31:18 -0500
Subject: [Tutor] Simple Python Problem
In-Reply-To: <i639gb$lsu$1@dough.gmane.org>
References: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>
	<i639gb$lsu$1@dough.gmane.org>
Message-ID: <AANLkTi=r-Z-Mbm1WqMDNVvuxAEh_bs6q+SzPdRg12jVb@mail.gmail.com>

>
>
>  Python 2.7 (r27:82525, Jul  4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]
>> on win32 Type
>> "copyright", "credits" or "license()" for more information.
>>
>>> ================================ RESTART ================================
>>>>>
>>>> What is your name? Keith
>>
>
> I think there is a trick in V2.7 to make it act more like v3 but someone
> else will need to tell you what it is... :-)
>
>
Other than changing the input() to raw_input() for Python 2 compatibility,
the following statement could be added to the beginning of the program to
allow your Python 2 program to use the Python 3 style print function.

from __future__ import print_function


-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/5bfdc870/attachment.html>

From smokefloat at gmail.com  Mon Sep  6 21:01:03 2010
From: smokefloat at gmail.com (David Hutto)
Date: Mon, 6 Sep 2010 15:01:03 -0400
Subject: [Tutor] Multiple versions of python and paths problems
In-Reply-To: <loom.20100906T191621-218@post.gmane.org>
References: <loom.20100906T191621-218@post.gmane.org>
Message-ID: <AANLkTimLHFt5gTE6QA_-x1MF+6y0hz9c0LYM0RogAy8W@mail.gmail.com>

On Mon, Sep 6, 2010 at 1:46 PM, Dominique <mydomdom at gmail.com> wrote:
> Hello,
>
> I usually use python 2.6 and several packages. Everything's fine.
>
> At present, I'm trying to run a package which is only available with python 2.5.
> So, i installed 2.5 and the various dependencies needed to run this package:
> PIL, numpy... which were already installed in my 2.6 site-packages.
>
> Unfortunately, when I try to run it under Idle 2.5, python goes in the 2.6
> site-packages to get these dependencies (PIL,...) and throws me a traceback (due
> to incompatibilities).
>
> I understand it is a paths problem.
>
> So, I added the path of python 2.5 and that of my application to the path and
> Pythonpath in the windows environ variables.
> But the same problems arise.
>
> So, I tried to load the normal 2.5 Idle and unload ('remove') everything related
> to 2.6 from sys.path, but it's strangely not working completely.
>
> Finally, I managed to run the program :
> - by launching D:\python25\python.exe -E -S in a console (which seems to prevent
> python from loading the paths)
> - then appending the application path to sys.path
> but it's really not fun working with this bloody windows console where cut and
> paste is impossible...
>
> So, here is my question:
> How can I force py2.5 to go and find the dependencies only in the 2.5
> site-packages ?
>
> Thanks in advance for your help.
>
> Dominique
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
forgot to hit reply all
>From wht the ole swiss cheese kinda recalls, just cd into the 2.5 main
dir from the windows command propmpt, and then you should be able to
type python /path/to/2.5/idlelib/idle.py, or whatever is on your
system.

If that's not it, then let me know, and I'll switch os's to make sure
what it was.

Also, there is a list specifically for window's python. pywin32.

From sander.sweers at gmail.com  Mon Sep  6 21:45:17 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 6 Sep 2010 21:45:17 +0200
Subject: [Tutor] exercise correct ??
In-Reply-To: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
Message-ID: <AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>

On 6 September 2010 19:32, Roelof Wobben <rwobben at hotmail.com> wrote:
> def index_of(val, seq, start=0):
> ??? """
> ????? >>> index_of(9, [1, 7, 11, 9, 10])
> ????? 3
> ????? >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
> ????? 3
> ????? >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> ????? 6
> ????? >>> index_of('y', 'happy birthday')
> ????? 4
> ????? >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
> ????? 1
> ????? >>> index_of(5, [2, 3, 4])
> ????? -1
> ????? >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
> ????? -1
> ??? """
> ??? plek = 0
> ??? if type(seq) == type([]):
> ??????? plek = seq.index(val)
> ??? elif type(seq) == type(()):
> ??????? seq = list (seq)
> ??????? plek = seq.index(val)
> ??? else :
> ??????? plek = seq.find(val)
> ??? return plek

Not sure if this is correct but why don't you check for the index
attribute? It is part of both lists and strings. Also you can use
try/except to catch a ValueError. My version below, but I dislike the
list() usage...

def index_of(val, seq, start=0):
    if hasattr(seq, 'index'):
        try:
            return seq.index(val, start)
        except ValueError:
            return -1
    else:
        try:
            return list(seq).index(val, start)
        except ValueError:
            return -1

> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> __main__.index_of
>
> Failed example:
>
> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>
> Expected:
>
> 6
>
> Got:
>
> 3
>
> But in that tuple 5 is on position 3.
>
> Is the exercise here wrong ?

Looks like it, or it's a typo.

Greets
Sander

From wprins at gmail.com  Mon Sep  6 21:55:31 2010
From: wprins at gmail.com (Walter Prins)
Date: Mon, 6 Sep 2010 20:55:31 +0100
Subject: [Tutor] exercise correct ??
In-Reply-To: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
Message-ID: <AANLkTi=2mp+1no8LUe1bFJ0XU-rVCjBxtrbSQW6QFmNT@mail.gmail.com>

Hi Roelof,

On 6 September 2010 18:32, Roelof Wobben <rwobben at hotmail.com> wrote:

>        >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>       6
>
> But in that tuple 5 is on position 3.
>
> Is the exercise here wrong ?
>
>

Not neccesarily...  I notice that the call is similar to the previous test
case, but has an extra parameter "4",  and that but that tuple that's being
searched contains other 5's.  If the extra parameter is interpreted as a
"starting index", then the next index of "5" starting at position 4, would
indeed be 6.  If my guesstimated intention of the test paramters is correct
then there's nothing wrong with the excercise/test and your implementation
of index_of needs to be enhanced to properly handle this extra parameter/new
test case.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/09337390/attachment.html>

From alan.gauld at btinternet.com  Mon Sep  6 22:02:39 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 6 Sep 2010 20:02:39 +0000 (GMT)
Subject: [Tutor] Simple Python Problem
In-Reply-To: <AANLkTi=r-Z-Mbm1WqMDNVvuxAEh_bs6q+SzPdRg12jVb@mail.gmail.com>
References: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>
	<i639gb$lsu$1@dough.gmane.org>
	<AANLkTi=r-Z-Mbm1WqMDNVvuxAEh_bs6q+SzPdRg12jVb@mail.gmail.com>
Message-ID: <735779.95614.qm@web86707.mail.ird.yahoo.com>

> > I think there is a trick in V2.7 to make it act more like v3 but someone 
> > else will need to tell you what it is... :-)

>Other than changing the input() to raw_input() for Python 2 compatibility,  

And of course you can do that using

input = raw_input

> the following statement could be added to the beginning of the program 
> to allow your Python 2 program to use the Python 3 style print function.

from __future__ import print_function
>That would help.
I wonder if we could create a module that would make v2.7 simulate v3 to 
a close degree? hmm... And is it sensible to try, should we not perhaps
just accept the difference?


Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/888f39f4/attachment.html>

From rwobben at hotmail.com  Mon Sep  6 22:28:19 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 6 Sep 2010 20:28:19 +0000
Subject: [Tutor] exercise correct ??
In-Reply-To: <AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>,
	<AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>
Message-ID: <SNT118-W25263FBB203DC0986165A2AE700@phx.gbl>



 

> Date: Mon, 6 Sep 2010 21:45:17 +0200
> Subject: Re: [Tutor] exercise correct ??
> From: sander.sweers at gmail.com
> To: rwobben at hotmail.com
> CC: tutor at python.org
> 
> On 6 September 2010 19:32, Roelof Wobben <rwobben at hotmail.com> wrote:
> > def index_of(val, seq, start=0):
> >     """
> >       >>> index_of(9, [1, 7, 11, 9, 10])
> >       3
> >       >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
> >       3
> >       >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> >       6
> >       >>> index_of('y', 'happy birthday')
> >       4
> >       >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
> >       1
> >       >>> index_of(5, [2, 3, 4])
> >       -1
> >       >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
> >       -1
> >     """
> >     plek = 0
> >     if type(seq) == type([]):
> >         plek = seq.index(val)
> >     elif type(seq) == type(()):
> >         seq = list (seq)
> >         plek = seq.index(val)
> >     else :
> >         plek = seq.find(val)
> >     return plek
> 
> Not sure if this is correct but why don't you check for the index
> attribute? It is part of both lists and strings. Also you can use
> try/except to catch a ValueError. My version below, but I dislike the
> list() usage...
> 
> def index_of(val, seq, start=0):
> if hasattr(seq, 'index'):
> try:
> return seq.index(val, start)
> except ValueError:
> return -1
> else:
> try:
> return list(seq).index(val, start)
> except ValueError:
> return -1
> 
> > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 70, in
> > __main__.index_of
> >
> > Failed example:
> >
> > index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> >
> > Expected:
> >
> > 6
> >
> > Got:
> >
> > 3
> >
> > But in that tuple 5 is on position 3.
> >
> > Is the exercise here wrong ?
> 
> Looks like it, or it's a typo.
> 
> Greets
> Sander


Hello Sander, 

 

I agree that index is a part of string and list.

But not a part of a tuple.

As far as I know index is not a part of tuple so I have to convert it to a list so I can use index.

 

Roelof
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/bab2e299/attachment.html>

From sander.sweers at gmail.com  Mon Sep  6 22:38:53 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 6 Sep 2010 22:38:53 +0200
Subject: [Tutor] exercise correct ??
In-Reply-To: <SNT118-W25263FBB203DC0986165A2AE700@phx.gbl>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
	<AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>
	<SNT118-W25263FBB203DC0986165A2AE700@phx.gbl>
Message-ID: <AANLkTikSQ_6zUK7aKLPPyBK+_oho22fzodCQJgiKxBaw@mail.gmail.com>

On 6 September 2010 22:28, Roelof Wobben <rwobben at hotmail.com> wrote:
> As far as I know index is not a part of tuple so I have to convert it to a
> list so I can use index.

As of version 2.6/3 a tuple does have index(). Not sure which version
you are using.

Greets
Sander

From wallenpb at gmail.com  Mon Sep  6 22:39:23 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Mon, 6 Sep 2010 15:39:23 -0500
Subject: [Tutor] Simple Python Problem
In-Reply-To: <735779.95614.qm@web86707.mail.ird.yahoo.com>
References: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>
	<i639gb$lsu$1@dough.gmane.org>
	<AANLkTi=r-Z-Mbm1WqMDNVvuxAEh_bs6q+SzPdRg12jVb@mail.gmail.com>
	<735779.95614.qm@web86707.mail.ird.yahoo.com>
Message-ID: <AANLkTi=P6WibW64DQpgDEV-zSce++ha_zR2DtfFe8BV_@mail.gmail.com>

>Other than changing the input() to raw_input() for Python 2 compatibility,
>
>
> And of course you can do that using
>
> input = raw_input
>
>
> > the following statement could be added to the beginning of the program
> > to allow your Python 2 program to use the Python 3 style print function.
>
> from __future__ import print_function
>
> That would help.
> I wonder if we could create a module that would make v2.7 simulate v3 to
> a close degree? hmm... And is it sensible to try, should we not perhaps
> just accept the difference?
>
> Alan G.
>
>  Ah!  I did not know that input = raw_input would work, thanks!

I am sure someone could create such.  However, to me, it would be more
sensible to just program in v3.  I have decided to code in only v3 since I
do not have any previous code base to maintain and am still very much in
learning mode.   It seems that some of the more popular external modules
such as NumPy and PyGame are also now v3 compatible.

By the way, even though I am far from proficient with Python, it has already
become a useful tool for me at work!

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/5514594a/attachment.html>

From sander.sweers at gmail.com  Mon Sep  6 23:14:38 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 6 Sep 2010 23:14:38 +0200
Subject: [Tutor] exercise correct ??
In-Reply-To: <AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
	<AANLkTimOG=-LUPdhMbYrCkh9eV9Md44dyYv30Nf1mRTh@mail.gmail.com>
Message-ID: <AANLkTimvP4WY8-a7tVEh+f_yYakvANo9MnpDgrSZ+p0f@mail.gmail.com>

On 6 September 2010 21:45, Sander Sweers <sander.sweers at gmail.com> wrote:
>> Is the exercise here wrong ?
>
> Looks like it, or it's a typo.

Now that I had a better look the test is correct. Now it is up to you
to figure out why your index_of() fails. Walter gave you a good hint.

Greets
Sander

From lists at justuber.com  Tue Sep  7 00:14:59 2010
From: lists at justuber.com (lists)
Date: Mon, 6 Sep 2010 23:14:59 +0100
Subject: [Tutor] slicing a string
Message-ID: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>

Hi guys,

Continuing my Python learning, I came across an exercise which asks me
to take a string and reverse it.

I understand that there is a function to do this i.e mytext.reverse()

I imagine that the exercise author would rather I did this the hard
way however. ;-)

Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
doesn't work (as I expected it to) but that mytext[::-1] does.

While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

Thanks again,

Chris

From sander.sweers at gmail.com  Tue Sep  7 00:22:19 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Tue, 7 Sep 2010 00:22:19 +0200
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
Message-ID: <AANLkTikxERn7QSy3FenyCCYrFpwFWA53KvJh4QAVmb9N@mail.gmail.com>

On 7 September 2010 00:14, lists <lists at justuber.com> wrote:
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

How does it not "work"? What did you expect to happen? What did it do instead?

Greets
Sander

From alan.gauld at btinternet.com  Tue Sep  7 00:28:22 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 6 Sep 2010 23:28:22 +0100
Subject: [Tutor] exercise correct ??
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>
Message-ID: <i63pu1$qrf$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote

#################
def index_of(val, seq, start=0):
    """
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
      6
    """

But I get this message :
Failed example:
index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
Expected:
6
Got:
3
#####################

> But in that tuple 5 is on position 3.
> Is the exercise here wrong ?

No because the start position is 4 so you don;t see the 5 in position 
3.

HTH,

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



From alan.gauld at btinternet.com  Tue Sep  7 00:38:19 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 6 Sep 2010 23:38:19 +0100
Subject: [Tutor] Multiple versions of python and paths problems
References: <loom.20100906T191621-218@post.gmane.org>
Message-ID: <i63qgl$sn6$1@dough.gmane.org>

"Dominique" <mydomdom at gmail.com> wrote


> So, I tried to load the normal 2.5 Idle and unload ('remove') 
> everything related
> to 2.6 from sys.path, but it's strangely not working completely.

How do you start IDLE? Is it via a desktop or start menu shortcut?
If so what is the startin folder specified as?

What happens when you run it from the command ine with no extra
parameters - what error do you get?

Do you have both versions of Python in your environment variables?
In which order?
Hint: Start a DOS session and type
SET PYTHONPATH
and
SET PATH

> Finally, I managed to run the program :
> - by launching D:\python25\python.exe -E -S in a console (which 
> seems to prevent
> python from loading the paths) - then appending the application path 
> to sys.path
> but it's really not fun working with this bloody windows console 
> where cut and
> paste is impossible...

Set the Quick Edit option for the terminal it will save you a lot of 
pain.
Cut n paste are then possible. In fact you should probably read the
Windows help on CMD too because there are a lot of settings/registry
tweaks that improves the use of the CMD prompt dramatically.
Also look at the WindowsPowerShell - it has a lot of this "out of the 
box"

But that aside you shouldn't have to do all this!

> How can I force py2.5 to go and find the dependencies only in the 
> 2.5
> site-packages ?

There are probably several ways round it, including creating a local 
startup file.

But if the paths are right it should work, and you may need to create 
a startup
DOS file to set them before executing python...

HTH,


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



From alan.gauld at btinternet.com  Tue Sep  7 00:43:29 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 6 Sep 2010 23:43:29 +0100
Subject: [Tutor] slicing a string
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
Message-ID: <i63qqb$tkk$1@dough.gmane.org>


"lists" <lists at justuber.com> wrote

> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't 
> work?

It does work.
But remember that slices give you the first item to one less
than the second index, so for a 4 letter word you need an
index of of -5...

>>> "test"[-1:-4:-1]
'tse'
>>> "test"[-1:-5:-1]
'tset'
>>>

HTH,

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



From lists at justuber.com  Tue Sep  7 00:44:24 2010
From: lists at justuber.com (lists)
Date: Mon, 6 Sep 2010 23:44:24 +0100
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTikxERn7QSy3FenyCCYrFpwFWA53KvJh4QAVmb9N@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<AANLkTikxERn7QSy3FenyCCYrFpwFWA53KvJh4QAVmb9N@mail.gmail.com>
Message-ID: <AANLkTimaRGsEc0igckn=Hd-Aq5DrpYYwF+znPTkkuB_9@mail.gmail.com>

>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>
>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>
> How does it not "work"? What did you expect to happen? What did it do instead?
>
> Greets
> Sander
>

Hi, assuming mytext is "test", word[-1:-4:-1] returns tse

My understanding of how the index works on test would be:

0  1  2  3
t   e  s   t
-4 -3 -2 -1

So I just wasn't clear on what happened to the last 't' I expected to see.

Cheer,

Chris

From lists at justuber.com  Tue Sep  7 00:45:20 2010
From: lists at justuber.com (lists)
Date: Mon, 6 Sep 2010 23:45:20 +0100
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTimaRGsEc0igckn=Hd-Aq5DrpYYwF+znPTkkuB_9@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<AANLkTikxERn7QSy3FenyCCYrFpwFWA53KvJh4QAVmb9N@mail.gmail.com>
	<AANLkTimaRGsEc0igckn=Hd-Aq5DrpYYwF+znPTkkuB_9@mail.gmail.com>
Message-ID: <AANLkTinKwgfDrfUgGX9Skx4P3pHWHGQBjfRZGF9pRjL-@mail.gmail.com>

>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>>
>> How does it not "work"? What did you expect to happen? What did it do instead?
>>
>> Greets
>> Sander
>>
>
> Hi, assuming mytext is "test", word[-1:-4:-1] returns tse
>
> My understanding of how the index works on test would be:
>
> 0 ?1 ?2 ?3
> t ? e ?s ? t
> -4 -3 -2 -1
>
> So I just wasn't clear on what happened to the last 't' I expected to see.
>
> Cheer,
>
> Chris
>

Sorry I mean mytext[-1:-4:-1] not word[-1:-4:-1] :-S

From steve at pearwood.info  Tue Sep  7 00:47:16 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Sep 2010 08:47:16 +1000
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
Message-ID: <201009070847.16928.steve@pearwood.info>

On Tue, 7 Sep 2010 08:14:59 am lists wrote:
> Hi guys,
>
> Continuing my Python learning, I came across an exercise which asks
> me to take a string and reverse it.
>
> I understand that there is a function to do this i.e mytext.reverse()

You understand wrong :)

There is a function reversed() which takes any iterable object (a list, 
a string, a tuple, a set, ...) and returns an iterator that yields the 
items in reverse order:

>>> reversed("test")
<reversed object at 0xb7e8834c>


but that's not useful in this case.


> I imagine that the exercise author would rather I did this the hard
> way however. ;-)
>
> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
> doesn't work (as I expected it to) but that mytext[::-1] does.
>
> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?

Remember that slice indexes fall *between* characters:


A slice of [-1:-4:-1] is equivalent to [3:0:-1].

>>> 'Test'[-1:-4:-1]
'tse'
>>> 'Test'[3:0:-1]
'tse'

So, what does this slice do? The slice indexes are equivalent to:

range(3, 0, -1)
=> [3, 2, 1]

Remember that the end position is excluded! Hence you reverse all the 
characters in the string *except* the first.


-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep  7 00:47:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Sep 2010 08:47:29 +1000
Subject: [Tutor] Simple Python Problem
In-Reply-To: <735779.95614.qm@web86707.mail.ird.yahoo.com>
References: <8383cdc00618c1136bcd49160aec17e0.squirrel@webmail.aber.ac.uk>
	<AANLkTi=r-Z-Mbm1WqMDNVvuxAEh_bs6q+SzPdRg12jVb@mail.gmail.com>
	<735779.95614.qm@web86707.mail.ird.yahoo.com>
Message-ID: <201009070847.29802.steve@pearwood.info>

On Tue, 7 Sep 2010 06:02:39 am ALAN GAULD wrote:
> I wonder if we could create a module that would make v2.7 simulate v3
> to a close degree? hmm... And is it sensible to try, should we not
> perhaps just accept the difference?

from __future__ import print_function, unicode_literals
from future_builtins import *


will get you part of the way, but it's probably impossible to get the 
two to be *exactly* the same.

-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep  7 00:48:27 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Sep 2010 08:48:27 +1000
Subject: [Tutor] Arguments from the command line
In-Reply-To: <AANLkTi=+Qb4n68bj1G6prfpORaNGdWDCJ1ogJDwt7bHw@mail.gmail.com>
References: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
	<AANLkTi=+Qb4n68bj1G6prfpORaNGdWDCJ1ogJDwt7bHw@mail.gmail.com>
Message-ID: <201009070848.27457.steve@pearwood.info>

On Tue, 7 Sep 2010 02:08:27 am Hugo Arts wrote:

> sys.argv is a list of all arguments from the command line. However,
> you'll rarely deal with it directly, there's various modules that
> deal with handling arguments. I believe the current one is argparse:
> http://docs.python.org/library/argparse.html#module-argparse

In my experience, getopt is a gentler introduction to argument parsing, 
because it does much less :)

optparse is another good one.

All three are available up to Python 2.7, and possibly in 3.1 as well, I 
haven't checked.


-- 
Steven D'Aprano

From andreengels at gmail.com  Tue Sep  7 00:52:58 2010
From: andreengels at gmail.com (Andre Engels)
Date: Tue, 7 Sep 2010 00:52:58 +0200
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTimaRGsEc0igckn=Hd-Aq5DrpYYwF+znPTkkuB_9@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<AANLkTikxERn7QSy3FenyCCYrFpwFWA53KvJh4QAVmb9N@mail.gmail.com>
	<AANLkTimaRGsEc0igckn=Hd-Aq5DrpYYwF+znPTkkuB_9@mail.gmail.com>
Message-ID: <AANLkTiky-48txSM8B=KzD7BLZF=1gGrUEybHg4b-kq7O@mail.gmail.com>

On Tue, Sep 7, 2010 at 12:44 AM, lists <lists at justuber.com> wrote:
>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't work?
>>
>> How does it not "work"? What did you expect to happen? What did it do instead?
>>
>> Greets
>> Sander
>>
>
> Hi, assuming mytext is "test", word[-1:-4:-1] returns tse
>
> My understanding of how the index works on test would be:
>
> 0 ?1 ?2 ?3
> t ? e ?s ? t
> -4 -3 -2 -1
>
> So I just wasn't clear on what happened to the last 't' I expected to see.


>>> "test"[0:3]
'tes'

[m:n] shows the elements from m upto but excluding n.


-- 
Andr? Engels, andreengels at gmail.com

From steve at pearwood.info  Tue Sep  7 00:55:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Sep 2010 08:55:28 +1000
Subject: [Tutor] setattr vs __setattr__
In-Reply-To: <AANLkTik8OruFPbnU3JHj-te_arvJpUuXrZLwF51vz98a@mail.gmail.com>
References: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>
	<AANLkTi=-mfoQFPM+26Ae5k2O_v163Fon7UDKJ2Kmjq++@mail.gmail.com>
	<AANLkTik8OruFPbnU3JHj-te_arvJpUuXrZLwF51vz98a@mail.gmail.com>
Message-ID: <201009070855.29046.steve@pearwood.info>

On Mon, 6 Sep 2010 09:03:30 pm Rasjid Wilcox wrote:
> I've been using
>
> for attr_name in name_list:
>     setattr(a, attr_name, getattr(b, attr_name))
>
> to copy the attributes from one type of class to another, and it is
> not quite as readable as I would like.

The one-liner in the for loop is very concise. The problem is that 
concise is often the opposite of readable. So make it less concise:


for name in name_list:
    obj = getattr(b, name)
    setattr(a, name, obj)

Does that help?

Another alternative, depending on the class, *might* be this:

a.__dict__.update(b.__dict__)

although that's a hack, and like all hacks, may not do what you expect 
for all classes.


> Actually, I've just thought 
> that the best option would be to make both classes dictionary like
> objects with automatic translation between a['foo'] and a.foo.

How does that help you copy from one class to another? As I see it, it 
just adds more noise to the class.


-- 
Steven D'Aprano

From davea at ieee.org  Tue Sep  7 01:40:44 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 06 Sep 2010 19:40:44 -0400
Subject: [Tutor] Multiple versions of python and paths problems
In-Reply-To: <loom.20100906T191621-218@post.gmane.org>
References: <loom.20100906T191621-218@post.gmane.org>
Message-ID: <4C857BFC.5080801@ieee.org>



On 2:59 PM, Dominique wrote:
> <snip>=
> but it's really not fun working with this bloody windows console where cut and
> paste is impossible...
>
>
Cut and paste work fine in a Windows DOS console.   Using Properties, 
the Options tab, turn on Quick-Edit mode.  Once you've done that, you 
can select a rectangle of text in such a console by using click/drag.  
Then you copy it to the clipboard with right click.

If you need to paste into the command line, something that's already in 
the clipboard, you can again use right click.

It's also possible to do copy or past without changing any properties -- 
just use the right-click on the title bar. to mark, then copy, or to paste.

DaveA


From augdawg09 at gmail.com  Tue Sep  7 01:46:06 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Mon, 6 Sep 2010 19:46:06 -0400
Subject: [Tutor] Arguments from the command line
In-Reply-To: <201009070848.27457.steve@pearwood.info>
References: <AANLkTim9rV54fcGgTGupF=Xe9G1BOSCmPzJ96vn52XY_@mail.gmail.com>
	<AANLkTi=+Qb4n68bj1G6prfpORaNGdWDCJ1ogJDwt7bHw@mail.gmail.com>
	<201009070848.27457.steve@pearwood.info>
Message-ID: <AANLkTiniV1Pv6xEBZYZugRCBTpTbDiRwNJS+0WzSOmLk@mail.gmail.com>

Alrighty! Thanks, everyone!


On Mon, Sep 6, 2010 at 6:48 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> On Tue, 7 Sep 2010 02:08:27 am Hugo Arts wrote:
>
> > sys.argv is a list of all arguments from the command line. However,
> > you'll rarely deal with it directly, there's various modules that
> > deal with handling arguments. I believe the current one is argparse:
> > http://docs.python.org/library/argparse.html#module-argparse
>
> In my experience, getopt is a gentler introduction to argument parsing,
> because it does much less :)
>
> optparse is another good one.
>
> All three are available up to Python 2.7, and possibly in 3.1 as well, I
> haven't checked.
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100906/69cacb60/attachment.html>

From rasjidw at gmail.com  Tue Sep  7 06:18:34 2010
From: rasjidw at gmail.com (Rasjid Wilcox)
Date: Tue, 7 Sep 2010 14:18:34 +1000
Subject: [Tutor] setattr vs __setattr__
In-Reply-To: <201009070855.29046.steve@pearwood.info>
References: <AANLkTinfpyy_V+h6-eUTQkEuq5HsRbMNUFefvYTZb2d3@mail.gmail.com>
	<AANLkTi=-mfoQFPM+26Ae5k2O_v163Fon7UDKJ2Kmjq++@mail.gmail.com>
	<AANLkTik8OruFPbnU3JHj-te_arvJpUuXrZLwF51vz98a@mail.gmail.com>
	<201009070855.29046.steve@pearwood.info>
Message-ID: <AANLkTin2D0tFvcgzy33LFQCt9DJ2Gc0cNaWbkNpQAeGh@mail.gmail.com>

On 7 September 2010 08:55, Steven D'Aprano <steve at pearwood.info> wrote:
> On Mon, 6 Sep 2010 09:03:30 pm Rasjid Wilcox wrote:
>> I've been using
>>
>> for attr_name in name_list:
>> ? ? setattr(a, attr_name, getattr(b, attr_name))
>>
>> to copy the attributes from one type of class to another, and it is
>> not quite as readable as I would like.
>
> The one-liner in the for loop is very concise. The problem is that
> concise is often the opposite of readable. So make it less concise:
>
> for name in name_list:
> ? ?obj = getattr(b, name)
> ? ?setattr(a, name, obj)
>
> Does that help?

Yes, that does help.  Such a simple and obvious thing (once someone
has pointed it out) and addresses my concern with the one-liner that
while easy to write, when looking back at it one has to look carefully
and analyse it to be certain about what is going on.  The two liner
has a few more keystrokes but is much easier on the eyes.  And easy on
the eyes is important to me - it is why I find Python 'beautiful' in a
way that most programming languages are not.

Much thanks,

Rasjid.

From rwobben at hotmail.com  Tue Sep  7 09:29:00 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 7 Sep 2010 07:29:00 +0000
Subject: [Tutor] exercise correct ??
In-Reply-To: <i63pu1$qrf$1@dough.gmane.org>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>,
	<i63pu1$qrf$1@dough.gmane.org>
Message-ID: <SNT118-W58291D2D86869B0A35A8CAAE710@phx.gbl>


Hello, 

 

Oke, the 4 is a starting point for the index.

 

Next problem.

 

The begin looks like this :

 

 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)


But in the module I get this result :

 

val = 5

seq = (1, 2, 4, 5, 6, 10, 5, 5

 

So the 4 is not avaible anymore.

 

Now I can change the header to  index(val, seq, start=0) to index (val, seq, start)

But I think that's not what the exercise wants.

 

Is there another way I can use the 4 ?

 

Roelof

 


 
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Mon, 6 Sep 2010 23:28:22 +0100
> Subject: Re: [Tutor] exercise correct ??
> 
> 
> "Roelof Wobben" <rwobben at hotmail.com> wrote
> 
> #################
> def index_of(val, seq, start=0):
> """
> >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> 6
> """
> 
> But I get this message :
> Failed example:
> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
> Expected:
> 6
> Got:
> 3
> #####################
> 
> > But in that tuple 5 is on position 3.
> > Is the exercise here wrong ?
> 
> No because the start position is 4 so you don;t see the 5 in position 
> 3.
> 
> HTH,
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/ce03c7c7/attachment.html>

From alan.gauld at btinternet.com  Tue Sep  7 09:52:38 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Tue, 7 Sep 2010 00:52:38 -0700 (PDT)
Subject: [Tutor] exercise correct ??
In-Reply-To: <SNT118-W58291D2D86869B0A35A8CAAE710@phx.gbl>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>,
	<i63pu1$qrf$1@dough.gmane.org>
	<SNT118-W58291D2D86869B0A35A8CAAE710@phx.gbl>
Message-ID: <428102.58783.qm@web86706.mail.ird.yahoo.com>



Oke, the 4 is a starting point for the index.
> 
>Next problem.
> 
>The begin looks like this :
> 
> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
>
>But in the module I get this result :
> 
>val = 5
>seq = (1, 2, 4, 5, 6, 10, 5, 5
> 
>So the 4 is not avaible anymore.
>
Yes it is. It is the start parameter.

The function definition is

def index_of(val, seq, start=0):

val is the first value, 5, seq is the tuple and start is 4.
 

Now I can change the header to  index(val, seq, start=0) to index (val, seq, 
start)
>But I think that's not what the exercise wants.
>
Why would you want to do that? It would force you to provide a start value 
for every call. The point of having a default value (=0) is so that you do not 
need to specify start every time you use the function. But eveb if you do not
use the start value it will still have a value, 0.
There is no difference, you can access it exactly like the other parameters.
Just use its name.
 
HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/09aea51a/attachment.html>

From mydomdom at gmail.com  Tue Sep  7 10:03:38 2010
From: mydomdom at gmail.com (Dominique)
Date: Tue, 7 Sep 2010 08:03:38 +0000 (UTC)
Subject: [Tutor] Multiple versions of python and paths problems
References: <loom.20100906T191621-218@post.gmane.org>
	<i63qgl$sn6$1@dough.gmane.org>
Message-ID: <loom.20100907T090812-250@post.gmane.org>

Alan Gauld <alan.gauld <at> btinternet.com> writes:


> How do you start IDLE? Is it via a desktop or start menu shortcut?
> If so what is the startin folder specified as?
Hello,
First, thanks to you David, Alan and Dave for your help.

Start with shortcut whose path is : "D:\Python25\python.exe" or
"D:\Python25\python.exe -E -S".
 
> What happens when you run it from the command ine with no extra
> parameters - what error do you get?
All paths related to python 2.6 and python 2.5 are imported (visible through
sys.path)in both cases.
The error is when launching the app which needs PIL, numpy... from 2.5 and not
2.6 (the versions imported are those of 2.6, causing the app to crash)

Note that paths are not imported only by launching D:\python25\python.exe -E -S
in a DOS CONSOLE.

> Do you have both versions of Python in your environment variables?
Yes

> In which order?

PATH is as follows (one by line):
%SystemRoot%\system32;
%SystemRoot%;
%SystemRoot%\System32\Wbem;
D:\WINDOWS\system32\WindowsPowerShell\v1.0;
D:\Program Files\TortoiseSVN\bin;
D:\Program Files\QuickTime\QTSystem\;
D:\OpenCV2.1\bin;
D:\Python26;
d:\Python26\Scripts;
D:\Python26\Lib\site-packages;
D:\Python25;
D:\Python25\Scripts;
D:\Python25\Lib\site-packages;
D:\Python25\Lib\site-packages\pyvision\releases\pyvision_0.8.1\src\;
D:\Python25\Lib\site-packages\opencv

PYTHONPATH is as follows:
D:\Python26\Lib\site-packages;
D:\Python25\Lib\site-packages;
D:\Python25\Lib\site-packages\pyvision\releases\pyvision_0.8.1\src\

Which order should I use ?
 
> Set the Quick Edit option for the terminal it will save you a lot of 
> pain.
Thanks for the tip !  It's a special cut&paste (you have to right-click on the
bar to have it work)!! 

> There are probably several ways round it, including creating a local 
> startup file.
OK 

> But if the paths are right it should work, and you may need to create 
> a startup
> DOS file to set them before executing python...
I tried without success... 
How would you do this ?

Thanks a lot for your help. As usual here!

Dominique



From rschroev_nospam_ml at fastmail.fm  Tue Sep  7 10:19:37 2010
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Tue, 07 Sep 2010 10:19:37 +0200
Subject: [Tutor] slicing a string
In-Reply-To: <i63qqb$tkk$1@dough.gmane.org>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<i63qqb$tkk$1@dough.gmane.org>
Message-ID: <i64sip$1fm$1@dough.gmane.org>

Op 2010-09-07 0:43, Alan Gauld schreef:
> 
> "lists" <lists at justuber.com> wrote
> 
>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>
>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't 
>> work?
> 
> It does work.
> But remember that slices give you the first item to one less
> than the second index, so for a 4 letter word you need an
> index of of -5...
> 
>>>> "test"[-1:-4:-1]
> 'tse'
>>>> "test"[-1:-5:-1]
> 'tset'
>>>>

But remember that you can make it simpler if you simply don't specify
the start and end points:

>>> 'hello'[::-1]
'olleh'

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven


From lists at justuber.com  Tue Sep  7 10:48:09 2010
From: lists at justuber.com (lists)
Date: Tue, 7 Sep 2010 09:48:09 +0100
Subject: [Tutor] slicing a string
In-Reply-To: <i64sip$1fm$1@dough.gmane.org>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<i63qqb$tkk$1@dough.gmane.org> <i64sip$1fm$1@dough.gmane.org>
Message-ID: <AANLkTimH6M-CVmfvhzQjYfxF-138Y9J8JrVKf6LS59kA@mail.gmail.com>

>>> Assuming that mytext is "test", I've found that mytext[-1:-4:-1]
>>> doesn't work (as I expected it to) but that mytext[::-1] does.
>>>
>>> While that's fine, I just wondered why mytext[-1:-4:-1] doesn't
>>> work?
>>
>> It does work.
>> But remember that slices give you the first item to one less
>> than the second index, so for a 4 letter word you need an
>> index of of -5...
>>
>>>>> "test"[-1:-4:-1]
>> 'tse'
>>>>> "test"[-1:-5:-1]
>> 'tset'
>>>>>
>
> But remember that you can make it simpler if you simply don't specify
> the start and end points:
>
>>>> 'hello'[::-1]
> 'olleh'
>
> --
> The saddest aspect of life right now is that science gathers knowledge
> faster than society gathers wisdom.
> ?-- Isaac Asimov
>

Thanks all :-) That makes sense now

Chris

From rwobben at hotmail.com  Tue Sep  7 11:40:25 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 7 Sep 2010 09:40:25 +0000
Subject: [Tutor] exercise correct ??
In-Reply-To: <428102.58783.qm@web86706.mail.ird.yahoo.com>
References: <SNT118-W50DAAF394F8284353265CFAE700@phx.gbl>,
	<i63pu1$qrf$1@dough.gmane.org>
	<SNT118-W58291D2D86869B0A35A8CAAE710@phx.gbl>,
	<428102.58783.qm@web86706.mail.ird.yahoo.com>
Message-ID: <SNT118-W4140A24607A2A0B1593694AE710@phx.gbl>



 


Date: Tue, 7 Sep 2010 00:52:38 -0700
From: alan.gauld at btinternet.com
Subject: Re: [Tutor] exercise correct ??
To: rwobben at hotmail.com; tutor at python.org









Oke, the 4 is a starting point for the index.
 
Next problem.
 
The begin looks like this :
 
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)

But in the module I get this result :
 
val = 5
seq = (1, 2, 4, 5, 6, 10, 5, 5
 
So the 4 is not avaible anymore.


Yes it is. It is the start parameter.

The function definition is

def index_of(val, seq, start=0):

val is the first value, 5, seq is the tuple and start is 4.
 



Now I can change the header to  index(val, seq, start=0) to index (val, seq, start)
But I think that's not what the exercise wants.


Why would you want to do that? It would force you to provide a start value 
for every call. The point of having a default value (=0) is so that you do not 
need to specify start every time you use the function. But eveb if you do not
use the start value it will still have a value, 0.
There is no difference, you can access it exactly like the other parameters.
Just use its name.
 
HTH,

Alan G.
 
Oke, 
 
Then this is the solution :
 
def index_of(val, seq, start=0):
    """
      >>> index_of(9, [1, 7, 11, 9, 10])
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
      3
      >>> index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
      6
      >>> index_of('y', 'happy birthday')
      4
      >>> index_of('banana', ['apple', 'banana', 'cherry', 'date'])
      1
      >>> index_of(5, [2, 3, 4])
      -1
      >>> index_of('b', ['apple', 'banana', 'cherry', 'date'])
      -1
    """
    try:
        plek = seq.index(val, start)
    except:
        plek = -1
    return plek 
 
Roelof


  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/bea6ed96/attachment.html>

From timmichelsen at gmx-topmail.de  Tue Sep  7 12:07:11 2010
From: timmichelsen at gmx-topmail.de (Timmie)
Date: Tue, 7 Sep 2010 10:07:11 +0000 (UTC)
Subject: [Tutor] refractoing and backward-compatibility
Message-ID: <loom.20100907T115930-619@post.gmane.org>

Hello,
I would like to refractor a module I write adding more functiosn and renaming
old ones.

In order to maintain backward compatibility with old scripts that reply on those
modules, I would like to introduce alias names for the old functions:

# refractored functions
def renamed_function():
    print 'got a new name'

# alias
old_function = renamed_function

Is this a good approach or are there better suggestions out there in the Python
community for such a purpose?

Thanks in advance for your hint,
Timmie



From steve at pearwood.info  Tue Sep  7 13:27:54 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 7 Sep 2010 21:27:54 +1000
Subject: [Tutor] refractoing and backward-compatibility
In-Reply-To: <loom.20100907T115930-619@post.gmane.org>
References: <loom.20100907T115930-619@post.gmane.org>
Message-ID: <201009072127.55237.steve@pearwood.info>

On Tue, 7 Sep 2010 08:07:11 pm Timmie wrote:
> Hello,
> I would like to refractor a module I write adding more functiosn and
> renaming old ones.
>
> In order to maintain backward compatibility with old scripts that
> reply on those modules, I would like to introduce alias names for the
> old functions:
[...]
> Is this a good approach or are there better suggestions out there in
> the Python community for such a purpose?


Sounds fine to me, although some people might disagree. 

Using aliases in this way is probably best when you only have one or two 
aliases, rather than dozens.

Another approach is to have a compatibility module -- have one module 
with the functionality, and a second module with aliases. The second 
module could be simply:

from module import old as new, ham as spam, bill as william

which creates aliases:

"new" instead of "old"
"spam" instead of "ham"
"william" instead of "bill"

Then the caller can either say


import module
module.ham()


or

import other_module
other_module.spam()



-- 
Steven D'Aprano

From smokefloat at gmail.com  Tue Sep  7 18:00:23 2010
From: smokefloat at gmail.com (David Hutto)
Date: Tue, 7 Sep 2010 12:00:23 -0400
Subject: [Tutor] Multiple versions of python and paths problems
In-Reply-To: <loom.20100907T090812-250@post.gmane.org>
References: <loom.20100906T191621-218@post.gmane.org>
	<i63qgl$sn6$1@dough.gmane.org>
	<loom.20100907T090812-250@post.gmane.org>
Message-ID: <AANLkTimTsDi7_dMW8y9VY=QaBH7aBQn7xfpuc-pOOnWn@mail.gmail.com>

On Tue, Sep 7, 2010 at 4:03 AM, Dominique <mydomdom at gmail.com> wrote:
> Alan Gauld <alan.gauld <at> btinternet.com> writes:
>
>
>> How do you start IDLE? Is it via a desktop or start menu shortcut?
>> If so what is the startin folder specified as?
> Hello,
> First, thanks to you David, Alan and Dave for your help.
>
> Start with shortcut whose path is : "D:\Python25\python.exe" or
> "D:\Python25\python.exe -E -S".
>
>> What happens when you run it from the command ine with no extra
>> parameters - what error do you get?
> All paths related to python 2.6 and python 2.5 are imported (visible through
> sys.path)in both cases.
> The error is when launching the app which needs PIL, numpy... from 2.5 and not
> 2.6 (the versions imported are those of 2.6, causing the app to crash)
>
> Note that paths are not imported only by launching D:\python25\python.exe -E -S
> in a DOS CONSOLE.
>
>> Do you have both versions of Python in your environment variables?
> Yes
>
>> In which order?
>
> PATH is as follows (one by line):
> %SystemRoot%\system32;
> %SystemRoot%;
> %SystemRoot%\System32\Wbem;
> D:\WINDOWS\system32\WindowsPowerShell\v1.0;
> D:\Program Files\TortoiseSVN\bin;
> D:\Program Files\QuickTime\QTSystem\;
> D:\OpenCV2.1\bin;
> D:\Python26;
> d:\Python26\Scripts;
> D:\Python26\Lib\site-packages;
> D:\Python25;
> D:\Python25\Scripts;
> D:\Python25\Lib\site-packages;
> D:\Python25\Lib\site-packages\pyvision\releases\pyvision_0.8.1\src\;
> D:\Python25\Lib\site-packages\opencv

>
> PYTHONPATH is as follows:
> D:\Python26\Lib\site-packages;
> D:\Python25\Lib\site-packages;
> D:\Python25\Lib\site-packages\pyvision\releases\pyvision_0.8.1\src\
>
> Which order should I use ?



If I'm still understanding the original question, if you right click
on a file, in Windows, and it says edit with idle, then idle is the
last version of python idle you've installed. If you call python from
the command prompt then it should be the first c:/pythonversionnumber
in environment variables that is called. so if you have
c:/python25;c:/python26;c:python3 then you should get 2.5 in command
prompt if you type python.

Paths, from what I know are lists, and the order is what you want to
be shown first to your program.
>
>> Set the Quick Edit option for the terminal it will save you a lot of
>> pain.
> Thanks for the tip ! ?It's a special cut&paste (you have to right-click on the
> bar to have it work)!!
>
>> There are probably several ways round it, including creating a local
>> startup file.
> OK
>
>> But if the paths are right it should work, and you may need to create
>> a startup
>> DOS file to set them before executing python...
> I tried without success...
> How would you do this ?
>
> Thanks a lot for your help. As usual here!
>
> Dominique
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From mydomdom at gmail.com  Tue Sep  7 19:06:23 2010
From: mydomdom at gmail.com (Dominique)
Date: Tue, 7 Sep 2010 17:06:23 +0000 (UTC)
Subject: [Tutor] Multiple versions of python and paths problems
References: <loom.20100906T191621-218@post.gmane.org>
	<i63qgl$sn6$1@dough.gmane.org>
	<loom.20100907T090812-250@post.gmane.org>
	<AANLkTimTsDi7_dMW8y9VY=QaBH7aBQn7xfpuc-pOOnWn@mail.gmail.com>
Message-ID: <loom.20100907T185717-303@post.gmane.org>

David Hutto <smokefloat <at> gmail.com> writes:


> 
> If I'm still understanding the original question, if you right click
> on a file, in Windows, and it says edit with idle, then idle is the
> last version of python idle you've installed. If you call python from
> the command prompt then it should be the first c:/pythonversionnumber
> in environment variables that is called. so if you have
> c:/python25;c:/python26;c:python3 then you should get 2.5 in command
> prompt if you type python.

Hi David,

No.
I have 2 python installed (2.5 and 2.6) and 2 shortcuts on the desktop (1 for
2.5 and 1 for 2.6).
I need to run an app built for 2.5.
If I launch idle for python 2.5 and then import my app, the app fails because
the packages it required are searched by python in the python 2.6 site-packages
(D:\Python26\Lib\site-packages) and not in the directory of python 2.5
(D:\Python25\Lib\site-packages).
It can be clearly seen with the tracebacks.


> Paths, from what I know are lists, and the order is what you want to
> be shown first to your program.
It seems that the order set up in the windows environ variables does not change
anything, ie if I put everything related to python 2.5 before the paths for
python 2.6, the same problem occurs.

Thanks for your help David
Dominique  


From metallourlante at gmail.com  Tue Sep  7 22:39:27 2010
From: metallourlante at gmail.com (Alex)
Date: Tue, 7 Sep 2010 22:39:27 +0200
Subject: [Tutor] Code review, plase
Message-ID: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>

Hi all.

Could someone review my code? It's the first time I develop a reusable
module and I would like to have some feedback.
If you think it's good enough I will package it for pypi.

I put the code on pastebin: http://pastebin.com/Tz367gAM

Thanks in advance.

Alex

From waynejwerner at gmail.com  Tue Sep  7 23:07:45 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 7 Sep 2010 16:07:45 -0500
Subject: [Tutor] Code review, plase
In-Reply-To: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>
References: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>
Message-ID: <AANLkTintUogDhS1q8mctUnJEL6OWakbqU27OPhx-n=5z@mail.gmail.com>

On Tue, Sep 7, 2010 at 3:39 PM, Alex <metallourlante at gmail.com> wrote:

> Hi all.
>
> Could someone review my code? It's the first time I develop a reusable
> module and I would like to have some feedback.
> If you think it's good enough I will package it for pypi.
>
> I put the code on pastebin: http://pastebin.com/Tz367gAM
>
> Thanks in advance.
>
> Alex


I mostly just glanced through it and didn't notice any gross errors. Your
comments should be standardized - I think I got them all here:
http://pastebin.com/BZSTRVWd Also, I changed line 83 to say what I think you
meant to say. I could be wrong, but I don't think something like "Job 342
exist" is what you meant.

HTH,
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/14da43ce/attachment.html>

From guerrerocarlos at gmail.com  Wed Sep  8 00:00:33 2010
From: guerrerocarlos at gmail.com (Carlos Guerrero)
Date: Tue, 7 Sep 2010 17:30:33 -0430
Subject: [Tutor] Pastebin.com fork based completely on Python (Django)
Message-ID: <AANLkTinPffFZuQWfyofakb=crLSY-PJtXs8qTPK0kW5h@mail.gmail.com>

I did a "pastebin.com" fork in Django (python web framework) if anyone
interested on join using it or improving it, can find the code at:
http://gitorious.org/aprendiendo-django/aprendiendo-django

Also see it working at http://notas.canaima.softwarelibre.gob.ve/

Best Regards

-- 
Atte:
Carlos A. Guerrero M.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100907/68b1420e/attachment-0001.html>

From qeg20 at cam.ac.uk  Tue Sep  7 23:07:35 2010
From: qeg20 at cam.ac.uk (Quinton Goddard)
Date: Tue, 7 Sep 2010 22:07:35 +0100
Subject: [Tutor] Python command calls the wrong version!
Message-ID: <07983E26-239A-45F9-B07E-CF63BA61FAFF@cam.ac.uk>

Dear Python Tutors,

I am new to Python, having perviously used IDL for all my scripts. I was hoping to use Python and so I have just downloaded and installed  version 2.6 using the mac installer. That all went fine.

I then opened up X11, all fine.

Then I typed in >python

and got this message

python: execv: /Applications/scisoft/i386/Packages/Python-2.5.4/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: No such file or directory

Waaaa!!! why is my python command trying to call a version which does not exist? I appear to have broken Python? I am sire this is a really easy thing to fix but I do not know enough about hows these programmes work to figure it out for myself.

Any help would be greatly appreciated!

Many thanks, Quinn 






From steve at pearwood.info  Wed Sep  8 00:20:21 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 8 Sep 2010 08:20:21 +1000
Subject: [Tutor] Code review, plase
In-Reply-To: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>
References: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>
Message-ID: <201009080820.21892.steve@pearwood.info>

On Wed, 8 Sep 2010 06:39:27 am Alex wrote:
> Hi all.
>
> Could someone review my code? It's the first time I develop a
> reusable module and I would like to have some feedback.
> If you think it's good enough I will package it for pypi.
>
> I put the code on pastebin: http://pastebin.com/Tz367gAM

Let's start with some little things... you talk about "the Unix CronTab" 
command, but there's no such thing, at least on Linux:

[steve at sylar ~]$ CronTab
bash: CronTab: command not found

It would be very unusual for a Unix command to be written in CamelCase. 
The command is actually "crontab".

In the _remove_crontab method, you say "*All* the information contained 
in the crontab file are permanently lost", but that's grammatically 
incorrect -- "information" is a mass noun, i.e. neither singular nor 
plural. So in standard English, you would say "all the information in 
the file is permanently lost", not "are lost", in the same way that you 
would say "the sugar is on the table" or "the grass is green".

http://en.wikipedia.org/wiki/Mass_noun

You overuse leading-underscore method names. Use them only for private 
methods. You use them for public methods, and even give an example of 
how to remove the entire file:

>>> #Remove the entire crontab file
>>> crontab._remove_crontab()

When you're telling people to use this command, that's a good sign that 
it is public not private!

In PRESETS, what's "mothly" mean? *wink*

What happens if I do this?

ct1 = micron.CronTab()
ct2 = micron.CronTab()
ct1.add_job('daily', 'echo "BOOM!"')
ct2.add_job('daily', 'echo "No BOOM today"')

Do they fight? What happens?



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Wed Sep  8 00:34:36 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 7 Sep 2010 23:34:36 +0100
Subject: [Tutor] Multiple versions of python and paths problems
References: <loom.20100906T191621-218@post.gmane.org><i63qgl$sn6$1@dough.gmane.org>
	<loom.20100907T090812-250@post.gmane.org>
Message-ID: <i66eln$7an$1@dough.gmane.org>


"Dominique" <mydomdom at gmail.com> wrote

>> How do you start IDLE? Is it via a desktop or start menu shortcut?
>> If so what is the startin folder specified as?

You omitted to answer the bit about the startin folder.
You will see this if you open the shortcut properties.

> The error is when launching the app which needs PIL, numpy... from 
> 2.5 and not
> 2.6 (the versions imported are those of 2.6, causing the app to 
> crash)
>
>> In which order?
>
> PYTHONPATH is as follows:
> D:\Python26\Lib\site-packages;
> D:\Python25\Lib\site-packages;
> D:\Python25\Lib\site-packages\pyvision\releases\pyvision_0.8.1\src\
>
> Which order should I use ?

You need to put 2.5 ahead of 2.6.
Python will look in the folders in the order given and stop
when it finds what its looking for. In your case that means
it looks in 2.6 first.

>> Set the Quick Edit option for the terminal it will save you a lot 
>> of
>> pain.
> Thanks for the tip !  It's a special cut&paste (you have to 
> right-click on the
> bar to have it work)!!

It is unusual but if you set quick edit you don;t need to use the 
title bar.
Select with the mouse.
Hit enter to copy
Use right-click to paste within the DOS box (no menu required)
Or use normal Ctrl-V to pasdte in other windows(like email say)

You can use the title bar menu too for slightly more control.

The help screens will give you lots more shortcuts like command
history recall and search, use of tab for command/file completion etc 
.

>> But if the paths are right it should work, and you may need to 
>> create
>> a startup DOS file to set them before executing python...
> I tried without success...
> How would you do this ?

Just create a .bat file     (python2.5.bat say) with

ECHO OFF
SET PATH  <full path to python 2.5 here>
SET PYTHONPATH  <only the python 2.5 lib folders here>
python %1 %2 %3 %4 %5 %6 %7 %8 %9

Should be adequate.

And do the same for v2.6. Then run the batch files (create shortcuts 
if you like)
as needed.

HTH,


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



From evert.rol at gmail.com  Wed Sep  8 08:38:29 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 8 Sep 2010 08:38:29 +0200
Subject: [Tutor] Python command calls the wrong version!
In-Reply-To: <07983E26-239A-45F9-B07E-CF63BA61FAFF@cam.ac.uk>
References: <07983E26-239A-45F9-B07E-CF63BA61FAFF@cam.ac.uk>
Message-ID: <ADCB376B-FD68-4305-A3CC-7CD8F357A3FF@gmail.com>

> Dear Python Tutors,
> 
> I am new to Python, having perviously used IDL for all my scripts. I was hoping to use Python and so I have just downloaded and installed  version 2.6 using the mac installer. That all went fine.
> 
> I then opened up X11, all fine.
> 
> Then I typed in >python
> 
> and got this message
> 
> python: execv: /Applications/scisoft/i386/Packages/Python-2.5.4/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: No such file or directory
> 
> Waaaa!!! why is my python command trying to call a version which does not exist? I appear to have broken Python? I am sire this is a really easy thing to fix but I do not know enough about hows these programmes work to figure it out for myself.

Most likely your path has been screwed up by the installation of scisoft. From the fact that it now can't find this Python 2.5, it appears you've later removed scisoft, but never changed your path back (check your .bashrc (or .cshrc, depending on your shell).
Also check your PATH:
$> echo $PATH
and perhaps even
$> which python

to see what you get back. If that points to some awkwardly located python, there's your problem.


Btw, if you trying to replace IDL with Python (I assume RSI IDL), you may be better off using macports, because you'll want various Python libraries & modules on your Mac (eg numpy, scipy, matplotlib). And, in fact, you don't really need X11, although that may depend on the GUI toolkit you're using (TKinter works without, pygtk needs X11 & GTK, the latter also available through macports); you can use start Python from the Terminal.


  Evert


From alan.gauld at btinternet.com  Wed Sep  8 10:45:45 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 8 Sep 2010 09:45:45 +0100
Subject: [Tutor] Python command calls the wrong version!
References: <07983E26-239A-45F9-B07E-CF63BA61FAFF@cam.ac.uk>
	<ADCB376B-FD68-4305-A3CC-7CD8F357A3FF@gmail.com>
Message-ID: <i67ifl$ns5$1@dough.gmane.org>


>> I am new to Python, having perviously used IDL for all my scripts.
> I was hoping to use Python and so I have just downloaded and 
> installed
> version 2.6 using the mac installer. That all went fine.
>>
>> I then opened up X11, all fine.

Why did you open X11?
If you used the Mac installer(*) it should run as a standard Mac 
program,
no need for X?

What happens if you type Python into the standard MacOS Terminal
application?

Running X adds a whole bunch of extra path and environment issues
to resolve, it might be easier to get it running in the vanilla MacOS 
first.


(*) BTW Which Mac installer? - there are at least 3 that I know of!

Just a thought.

Alan G.



From dineshbvadhia at hotmail.com  Wed Sep  8 14:24:47 2010
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Wed, 8 Sep 2010 05:24:47 -0700
Subject: [Tutor] pickling codecs
Message-ID: <COL103-DS24E42548E0C08C483A717A3720@phx.gbl>

I use codecs to retain consistent unicode/utf-8 encoding and decoding for reading/writing to files.  Should the codecs be applied when using the pickle/unpickle function?  For example, the standard syntax is:

# pickle object
f = open(object, 'wb')
pickle.dump(object, f, 2)
 
# unpickle object
f = open(object, 'rb')
object= pickle.load(f)
 
or should it be:

# pickle object
f = codecs.open(object, 'wb', 'utf-8')
pickle.dump(object, f, 2)


# unpickle object
f = codecs.open(object, 'rb', 'utf-8')
object= pickle.load(f)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/6e866af4/attachment.html>

From metallourlante at gmail.com  Wed Sep  8 14:28:26 2010
From: metallourlante at gmail.com (Alex)
Date: Wed, 8 Sep 2010 14:28:26 +0200
Subject: [Tutor] Code review, plase
In-Reply-To: <201009080820.21892.steve@pearwood.info>
References: <AANLkTi=fnWH3r=Svs_8cHCJ8wQiQWfQsQz9P0Bhu8sG0@mail.gmail.com>
	<201009080820.21892.steve@pearwood.info>
Message-ID: <AANLkTi=tV6WzQ2H2E=QNZK_VYfxmdJ63STkK5qN1jVtS@mail.gmail.com>

On Wed, Sep 8, 2010 at 12:20 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Wed, 8 Sep 2010 06:39:27 am Alex wrote:
>> Hi all.
>>
>> Could someone review my code? It's the first time I develop a
>> reusable module and I would like to have some feedback.
>> If you think it's good enough I will package it for pypi.
>>
>> I put the code on pastebin: http://pastebin.com/Tz367gAM
>
> Let's start with some little things... you talk about "the Unix CronTab"
> command, but there's no such thing, at least on Linux:
>
> [steve at sylar ~]$ CronTab
> bash: CronTab: command not found

Absolutely right I'll update the docstring

> In the _remove_crontab method, you say "*All* the information contained
> in the crontab file are permanently lost", but that's grammatically
> incorrect -- "information" is a mass noun, i.e. neither singular nor
> plural. So in standard English, you would say "all the information in
> the file is permanently lost", not "are lost", in the same way that you
> would say "the sugar is on the table" or "the grass is green".

Argh! I should go back to grammar school :-) English is not my first langage

> ct1 = micron.CronTab()
> ct2 = micron.CronTab()
> ct1.add_job('daily', 'echo "BOOM!"')
> ct2.add_job('daily', 'echo "No BOOM today"')

> Do they fight? What happens?

They will not be duplicated because the class will generate a unique
job_id incrementing the last id used. Since the module is just a
wrapper for the crontab command any other clashing will be managed by
the cron daemon. I will add an example to document this behaviour.

Thanks for your helpful comments.

Alex

From webtourist at gmail.com  Wed Sep  8 16:28:01 2010
From: webtourist at gmail.com (Robert)
Date: Wed, 8 Sep 2010 10:28:01 -0400
Subject: [Tutor] Pastebin.com fork based completely on Python (Django)
In-Reply-To: <AANLkTinPffFZuQWfyofakb=crLSY-PJtXs8qTPK0kW5h@mail.gmail.com>
References: <AANLkTinPffFZuQWfyofakb=crLSY-PJtXs8qTPK0kW5h@mail.gmail.com>
Message-ID: <AANLkTikKh6Ei1Mbr7N5jM7n17_Dqhek6cX2HXzG355qn@mail.gmail.com>

Does not *look* "Pythonic" - have a look at this : http://paste.pocoo.org/


On Tue, Sep 7, 2010 at 6:00 PM, Carlos Guerrero
<guerrerocarlos at gmail.com> wrote:
> I did a "pastebin.com" fork in Django

From rwobben at hotmail.com  Wed Sep  8 17:22:44 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 8 Sep 2010 15:22:44 +0000
Subject: [Tutor] sort problem
Message-ID: <SNT118-W61C118543119569290B921AE720@phx.gbl>


Hello, 

 

I have this :

 

def sort_sequence(seq):
    """
      >>> sort_sequence([3, 4, 6, 7, 8, 2])
      [2, 3, 4, 6, 7, 8]
      >>> sort_sequence((3, 4, 6, 7, 8, 2))
      (2, 3, 4, 6, 7, 8)
      >>> sort_sequence("nothappy")
      'ahnoppty'
    """
   if type(seq) == type([]):
        seq.sort()
    elif type(seq)== type(()):
        seq = tuple(sorted(seq))
    else:
        seq2 = list(seq)
        seq2.sort()
        print seq2
        seq.join(seq2)
    return seq

 

The problem is that if I want to sort the characters in a string, the list exist of the sorted characters but as soon as I convert them to a string I get the old string.

 

What went wrong ?

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/99fdb9ba/attachment.html>

From evert.rol at gmail.com  Wed Sep  8 17:26:58 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 8 Sep 2010 17:26:58 +0200
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W61C118543119569290B921AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>
Message-ID: <1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>

> I have this :
>  
> def sort_sequence(seq):
>     """
>       >>> sort_sequence([3, 4, 6, 7, 8, 2])
>       [2, 3, 4, 6, 7, 8]
>       >>> sort_sequence((3, 4, 6, 7, 8, 2))
>       (2, 3, 4, 6, 7, 8)
>       >>> sort_sequence("nothappy")
>       'ahnoppty'
>     """
>    if type(seq) == type([]):
>         seq.sort()
>     elif type(seq)== type(()):
>         seq = tuple(sorted(seq))
>     else:
>         seq2 = list(seq)
>         seq2.sort()
>         print seq2
>         seq.join(seq2)
>     return seq
>  
> The problem is that if I want to sort the characters in a string, the list exist of the sorted characters but as soon as I convert them to a string I get the old string.

Carefully read the documentation for str.join: http://docs.python.org/library/stdtypes.html#str.join

How does it work, what does it return, etc. Then fix the corresponding line in your code.
As a hint: str.join does work quite different than list.sort; I assume you're confusing their syntaxes.

Good luck,

  Evert


>  
> What went wrong ?
>  
> Roelof
>  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From rwobben at hotmail.com  Wed Sep  8 17:50:32 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 8 Sep 2010 15:50:32 +0000
Subject: [Tutor] sort problem
In-Reply-To: <1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>
Message-ID: <SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>



 

> Subject: Re: [Tutor] sort problem
> From: evert.rol at gmail.com
> Date: Wed, 8 Sep 2010 17:26:58 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com
> 
> > I have this :
> > 
> > def sort_sequence(seq):
> > """
> > >>> sort_sequence([3, 4, 6, 7, 8, 2])
> > [2, 3, 4, 6, 7, 8]
> > >>> sort_sequence((3, 4, 6, 7, 8, 2))
> > (2, 3, 4, 6, 7, 8)
> > >>> sort_sequence("nothappy")
> > 'ahnoppty'
> > """
> > if type(seq) == type([]):
> > seq.sort()
> > elif type(seq)== type(()):
> > seq = tuple(sorted(seq))
> > else:
> > seq2 = list(seq)
> > seq2.sort()
> > print seq2
> > seq.join(seq2)
> > return seq
> > 
> > The problem is that if I want to sort the characters in a string, the list exist of the sorted characters but as soon as I convert them to a string I get the old string.
> 
> Carefully read the documentation for str.join: http://docs.python.org/library/stdtypes.html#str.join
> 
> How does it work, what does it return, etc. Then fix the corresponding line in your code.
> As a hint: str.join does work quite different than list.sort; I assume you're confusing their syntaxes.
> 
> Good luck,
> 
> Evert
> 


str.join(iterable)?
 

How it works.

It puts all the elements of iterable into one string named str.

 

So it returns a string. 

 

Str is here seq  and the iterable is the list made by list.sort so seq2

 

So I don't see the error in that line.

 

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/f51b8019/attachment-0001.html>

From fal at libero.it  Wed Sep  8 18:17:13 2010
From: fal at libero.it (Francesco Loffredo)
Date: Wed, 08 Sep 2010 18:17:13 +0200
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>
Message-ID: <4C87B709.2030707@libero.it>

On 08/09/2010 17.50, Roelof Wobben wrote:
>
>
>  > Subject: Re: [Tutor] sort problem
>  > From: evert.rol at gmail.com
>  > Date: Wed, 8 Sep 2010 17:26:58 +0200
>  > CC: tutor at python.org
>  > To: rwobben at hotmail.com
>...
>  > > seq2 = list(seq)
>  > > seq2.sort()
>  > > print seq2
>  > > seq.join(seq2)
>  > > return seq
>  > >
>  > > The problem is that if I want to sort the characters in a string,
> the list exist of the sorted characters but as soon as I convert them to
> a string I get the old string.
Are you sure that you really get your old string? I would expect 
something like:
seq = "cba"
seq2 = ["a", "b", "c"]

seq.join(seq2) => "acbabcbac"

that is, all the characters from seq2 separated by copies of seq.

Evert gave you a good advice:

>  > Carefully read the documentation for str.join:
> http://docs.python.org/library/stdtypes.html#str.join
>  >
>  > How does it work, what does it return, etc. Then fix the
> corresponding line in your code.
>  > As a hint: str.join does work quite different than list.sort; I
> assume you're confusing their syntaxes.
>  >
>  > Good luck,
>  >
>  > Evert
>  >
>
> str.join(/iterable/)? <#str.join>
>
> How it works.
> It puts all the elements of iterable into one string named str.
>
> So it returns a string.
>
> Str is here seq and the iterable is the list made by list.sort so seq2
>
> So I don't see the error in that line.

What does join use as a separator between the elements it joins?


> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3119 -  Data di rilascio: 09/07/10 08:34:00

From gregbair at gmail.com  Wed Sep  8 18:38:03 2010
From: gregbair at gmail.com (Greg)
Date: Wed, 8 Sep 2010 12:38:03 -0400
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>
Message-ID: <AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>

On Wed, Sep 8, 2010 at 11:50 AM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
> > Subject: Re: [Tutor] sort problem
> > From: evert.rol at gmail.com
> > Date: Wed, 8 Sep 2010 17:26:58 +0200
> > CC: tutor at python.org
> > To: rwobben at hotmail.com
>
> >
> > > I have this :
> > >
> > > def sort_sequence(seq):
> > > """
> > > >>> sort_sequence([3, 4, 6, 7, 8, 2])
> > > [2, 3, 4, 6, 7, 8]
> > > >>> sort_sequence((3, 4, 6, 7, 8, 2))
> > > (2, 3, 4, 6, 7, 8)
> > > >>> sort_sequence("nothappy")
> > > 'ahnoppty'
> > > """
> > > if type(seq) == type([]):
> > > seq.sort()
> > > elif type(seq)== type(()):
> > > seq = tuple(sorted(seq))
> > > else:
> > > seq2 = list(seq)
> > > seq2.sort()
> > > print seq2
> > > seq.join(seq2)
> > > return seq
> > >
> > > The problem is that if I want to sort the characters in a string, the
> list exist of the sorted characters but as soon as I convert them to a
> string I get the old string.
> >
> > Carefully read the documentation for str.join:
> http://docs.python.org/library/stdtypes.html#str.join
> >
> > How does it work, what does it return, etc. Then fix the corresponding
> line in your code.
> > As a hint: str.join does work quite different than list.sort; I assume
> you're confusing their syntaxes.
> >
> > Good luck,
> >
> > Evert
> >
>
> str.join(*iterable*)? <#12af20c2e150d2eb_str.join>
> How it works.
> It puts all the elements of iterable into one string named str.
>
> So it returns a string.
>
> Str is here seq  and the iterable is the list made by list.sort so seq2
>
> So I don't see the error in that line.
>
>
> Roelof
>
>

The error is that you misunderstand the usage of str.join.  It doesn't do it
in place, i.e. it doesn't change the actual string, so you have to have a
variable to capture the response.

The biggest thing, though, is that in str.join, str is not the string to
store the joined iterator in, it's the separator for the string.  so, in
your case, where you have

seq.join(seq2)

You really want

seq = "".join(seq2)

where "" is the separator to join seq2 on (an empty string in this case)

HTH.

-- 
Greg Bair
gregbair at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/526db5f3/attachment.html>

From rwobben at hotmail.com  Wed Sep  8 19:12:05 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 8 Sep 2010 17:12:05 +0000
Subject: [Tutor] sort problem
In-Reply-To: <AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>,
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>,
	<AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>
Message-ID: <SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>



 


Date: Wed, 8 Sep 2010 12:38:03 -0400
From: gregbair at gmail.com
To: tutor at python.org
Subject: Re: [Tutor] sort problem




On Wed, Sep 8, 2010 at 11:50 AM, Roelof Wobben <rwobben at hotmail.com> wrote:



 
> Subject: Re: [Tutor] sort problem
> From: evert.rol at gmail.com
> Date: Wed, 8 Sep 2010 17:26:58 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com

> 
> > I have this :
> > 
> > def sort_sequence(seq):
> > """
> > >>> sort_sequence([3, 4, 6, 7, 8, 2])
> > [2, 3, 4, 6, 7, 8]
> > >>> sort_sequence((3, 4, 6, 7, 8, 2))
> > (2, 3, 4, 6, 7, 8)
> > >>> sort_sequence("nothappy")
> > 'ahnoppty'
> > """
> > if type(seq) == type([]):
> > seq.sort()
> > elif type(seq)== type(()):
> > seq = tuple(sorted(seq))
> > else:
> > seq2 = list(seq)
> > seq2.sort()
> > print seq2
> > seq.join(seq2)
> > return seq
> > 
> > The problem is that if I want to sort the characters in a string, the list exist of the sorted characters but as soon as I convert them to a string I get the old string.
> 
> Carefully read the documentation for str.join: http://docs.python.org/library/stdtypes.html#str.join
> 
> How does it work, what does it return, etc. Then fix the corresponding line in your code.
> As a hint: str.join does work quite different than list.sort; I assume you're confusing their syntaxes.
> 
> Good luck,
> 
> Evert
> 


str.join(iterable)? 
How it works.
It puts all the elements of iterable into one string named str.
 
So it returns a string. 
 
Str is here seq  and the iterable is the list made by list.sort so seq2
 
So I don't see the error in that line.
 
 
Roelof
 


The error is that you misunderstand the usage of str.join.  It doesn't do it in place, i.e. it doesn't change the actual string, so you have to have a variable to capture the response.


The biggest thing, though, is that in str.join, str is not the string to store the joined iterator in, it's the separator for the string.  so, in your case, where you have


seq.join(seq2)


You really want


seq = "".join(seq2)


where "" is the separator to join seq2 on (an empty string in this case)

HTH.

-- 
Greg Bair
gregbair at gmail.com"
 
Oke, 
 
If I understand it right with join I can put two strings into 1 string.
 
Roelof
 

_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/7913c236/attachment.html>

From bgailer at gmail.com  Wed Sep  8 19:26:00 2010
From: bgailer at gmail.com (bob gailer)
Date: Wed, 08 Sep 2010 13:26:00 -0400
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>,
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>,
	<AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>
	<SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
Message-ID: <4C87C728.2040901@gmail.com>

  On 9/8/2010 1:12 PM, Roelof Wobben wrote:
>
> If I understand it right

You don't.

What does "put two strings into 1 string" mean. Provide an example.

What does the documentation say about join? What part of that do you not 
understand?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/53551f4e/attachment-0001.html>

From alan.gauld at btinternet.com  Wed Sep  8 19:40:29 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 8 Sep 2010 18:40:29 +0100
Subject: [Tutor] sort problem
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>
Message-ID: <i68hqa$51n$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote

> > Carefully read the documentation for str.join: 
> > http://docs.python.org/library/stdtypes.html#str.join
> >
> >How does it work, what does it return, etc. Then fix the 
> >corresponding line in your code.
>
>
> str.join(iterable)?
>
>It puts all the elements of iterable into one string named str.

Thats not what the documentation says...

> So it returns a string.

Thats true.,

When trying to understand how a function works, or debug these kinds 
of
errors use the >>> prompt to experiment. It's the definitive way of 
seeing what
Python will do.

For example try:

>>> "123".join([5,6,7])

Can you see what Python has done?

Use the >>> prompt it is one of the most powerful tools you have.

HTH,

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



From carter.danforth at gmail.com  Wed Sep  8 19:43:42 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Wed, 8 Sep 2010 13:43:42 -0400
Subject: [Tutor] how to create a persistent dictionary w/ cpickle?
Message-ID: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>

Hi, I'm trying to a create a basic addressbook for practice. I'm using a
dictionary with cpickle, though I'm not sure how to persistently store each
instance in the dictionary. Below is the code I have so far.

If I run it once and add a contact and the details, it's fine. p.load(f)
shows the details next time I run it, but if I add another contact, and run
it again, the previous key:value doesn't show. It gets replaced by the new
one.

How can I fix this so that it adds the new key:value to the dictionary
instead of replacing the existing one? Appreciate any help, thanks.

import cPickle as p
addressbook = 'addressbook.data'
f = file(addressbook, 'r+')

class address:
    def __init__(self, name, tel, email):
        self.name = name
        self.tel = tel
        self.email = email

        ab = {self.name : self.tel}

        f = file(addressbook, 'r+')
        p.dump(ab, f)

print p.load(f)
x = raw_input()

if x == 'add':
    name = raw_input('\nName: ')
    tel = raw_input('Tel: ')
    email = raw_input('Email: ')

    contact = address(name, tel, email)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/0f8588ad/attachment.html>

From fal at libero.it  Wed Sep  8 19:59:53 2010
From: fal at libero.it (Francesco Loffredo)
Date: Wed, 08 Sep 2010 19:59:53 +0200
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>,
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>,
	<AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>
	<SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
Message-ID: <4C87CF19.9010108@libero.it>

On 08/09/2010 19.12, Roelof Wobben wrote:
> ...
> Oke,
> If I understand it right with join I can put two strings into 1 string.
> Roelof
Not quite. With join you can put together in one string all the elements 
of a list of strings. While you do so, you can also put another string 
as a "wall" between each element of the list. Let's make a little example:

separator = "Roelof"
list = ["Wobben", "Python", "Learner"]
print separator.join(list)

... what you will get? Guess before you try.


Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3119 -  Data di rilascio: 09/07/10 08:34:00

From fal at libero.it  Wed Sep  8 20:10:28 2010
From: fal at libero.it (Francesco Loffredo)
Date: Wed, 08 Sep 2010 20:10:28 +0200
Subject: [Tutor] sort problem
In-Reply-To: <SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>,
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>,
	<AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>
	<SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>
Message-ID: <4C87D194.90500@libero.it>

On 08/09/2010 19.12, Francesco Loffredo wrote:
> ...
> a little example:
>
> separator = "Roelof"
> list = ["Wobben", "Python", "Learner"]
> print separator.join(list)
>
> ... what you will get? Guess before you try.

There's more, I forgot to add:

print separator

This is important, this method *returns* a *NEW* string, it does not 
modify the providing string (here separator)! This means you must save 
the result somewhere, if you want to use it later:

together = separator.join(list)

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3119 -  Data di rilascio: 09/07/10 08:34:00

From rwobben at hotmail.com  Wed Sep  8 20:16:48 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 8 Sep 2010 18:16:48 +0000
Subject: [Tutor] sort problem
In-Reply-To: <4C87D194.90500@libero.it>
References: <SNT118-W61C118543119569290B921AE720@phx.gbl>, ,
	<1E707CB1-83ED-4DD5-B5A2-3C545736CE58@gmail.com>, ,
	<SNT118-W17C90F97036E5627F5C6B9AE720@phx.gbl>, ,
	<AANLkTinNWD6ojbtArW8qMvRhLGLid6bK9eeqWL3Gxj_M@mail.gmail.com>,
	<SNT118-W383A15F36DE9A2F7AA25D6AE720@phx.gbl>,
	<4C87D194.90500@libero.it>
Message-ID: <SNT118-W38910E9D007987957BCAE1AE720@phx.gbl>



 
Date: Wed, 8 Sep 2010 20:10:28 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] sort problem

On 08/09/2010 19.12, Francesco Loffredo wrote:
> ...
> a little example:
>
> separator = "Roelof"
> list = ["Wobben", "Python", "Learner"]
> print separator.join(list)
>
> ... what you will get? Guess before you try.
 
There's more, I forgot to add:
 
print separator
 
This is important, this method *returns* a *NEW* string, it does not 
modify the providing string (here separator)! This means you must save 
the result somewhere, if you want to use it later:
 
together = separator.join(list)
 
Francesco


_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: 

http://mail.python.org/mailman/listinfo/tutor

 

Oke, 

 

I now see what everyone try to teach me.

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/6c2bbf2b/attachment.html>

From g.nius.ck at gmail.com  Wed Sep  8 22:59:57 2010
From: g.nius.ck at gmail.com (Chris King)
Date: Wed, 08 Sep 2010 16:59:57 -0400
Subject: [Tutor] Mutable Properties
Message-ID: <4C87F94D.9030601@gmail.com>

  Dear Tutors,
     I noticed that when you use a property to represent a mutable 
value, I you try to use its methods, it will directly change the value 
returned. I know this happens because I'm not really assigning it to 
something new, but changing whats already there, which won't fire off 
the set method. I was wondering if there was a way around this.
Sincerely,
     Me

From steve at pearwood.info  Wed Sep  8 23:22:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 9 Sep 2010 07:22:53 +1000
Subject: [Tutor] Mutable Properties
In-Reply-To: <4C87F94D.9030601@gmail.com>
References: <4C87F94D.9030601@gmail.com>
Message-ID: <201009090722.53624.steve@pearwood.info>

On Thu, 9 Sep 2010 06:59:57 am Chris King wrote:
>   Dear Tutors,
>      I noticed that when you use a property to represent a mutable
> value, I you try to use its methods, it will directly change the
> value returned. I know this happens because I'm not really assigning
> it to something new, but changing whats already there, which won't
> fire off the set method. I was wondering if there was a way around
> this.

You're going to need to give an example of:

(1) what you do;
(2) what you want to happen; and
(3) what actually happens.

The simplest example I can think of is:

class K(object):
    def __init__(self):
        self._private = []
    def _getter(self):
        return self._private
    def _setter(self, value):
        self._private = list(value)
    seq = property(_getter, _setter)


And in use:

>>> k = K()
>>> k.seq
[]
>>> k.seq.append(1)
>>> k.seq
[1]

Works fine.


-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep  8 23:50:13 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 9 Sep 2010 07:50:13 +1000
Subject: [Tutor] how to create a persistent dictionary w/ cpickle?
In-Reply-To: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>
References: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>
Message-ID: <201009090750.14230.steve@pearwood.info>

On Thu, 9 Sep 2010 03:43:42 am Carter Danforth wrote:
> Hi, I'm trying to a create a basic addressbook for practice. I'm
> using a dictionary with cpickle, though I'm not sure how to
> persistently store each instance in the dictionary. Below is the code
> I have so far.
>
> If I run it once and add a contact and the details, it's fine.
> p.load(f) shows the details next time I run it, but if I add another
> contact, and run it again, the previous key:value doesn't show. It
> gets replaced by the new one.

Where do you think you are *adding* a new contact? You don't. You 
*replace* the existing contact with a brand new one, every time.

The problem has nothing to do with pickle, or storing "each instance in 
the dictionary". Pickle is already storing each instance in the 
dictionary. The problem is that you never *add* anything to the address 
book, you *replace* it each time, so there is never more than two 
instances in the dictionary (one key, one value).

You don't have an address BOOK, you only have a single address.


> How can I fix this so that it adds the new key:value to the
> dictionary instead of replacing the existing one? Appreciate any
> help, thanks.

I would dump the entire address class for now and just go for something 
nice and minimal. Get that working first, and then, *if necessary*, 
wrap it in a class. This is Python, not Java -- we use whatever works, 
and don't force everything to be a class when it doesn't have to be.

What's the simplest address record you might have? How about a name 
linked to a telephone number and email?

address_book = {name: (tel, email), another_name: (tel, email), ...}

So, here's the basic algorithm:

(1) Look for the address-book. If it doesn't exist, create an empty 
dictionary, and pickle it as the address-book.

(2) Read the address-book from the pickle file. It will be a dictionary, 
possibly empty.

(3) Add an address to the dictionary. Don't create a new dictionary:

>>> addresses = {}  # creates a new, empty address book
>>> addresses["Fred"] = ("1234 5678", "fred at example.com")
>>> addresses["Betty"] = ("2468 1357", "betty at nowhere.com")
>>> addresses  # not empty any more
{'Betty': ('2468 1357', 'betty at nowhere.com'), 'Fred': ('1234 
5678', 'fred at example.com')}

(3) Save the dictionary to the pickle file.


Once you have those steps happening manually, then wrap it into a class 
so they happen automatically.


Some more comments on your code:


> import cPickle as p

Now that's just lazy. While laziness in a programmer in a good thing, 
this is taking it to extremes!!! You use pickle twice, three times if 
you count the import. Is it really such a burden on you to 
type "cPickle" (or "pickle") two more times, that you need to rename 
it "p"?

Excessive use of one-character names is one of the worst programming 
habits you can have. Don't do this.


> addressbook = 'addressbook.data'

Misleading variable name. "addressbook" isn't an addressbook at all, 
it's a filename.

> f = file(addressbook, 'r+')

You shouldn't keep the file open for large periods of time. On Windows, 
it may mean that it will be locked from any other program accessing it 
during that time, and it risks data corruption if your program crashes 
or the power goes out.

Open and close the file just when you need it.


> class address:

A minor point: it is the convention in Python that (most) classes start 
with a capital letter. So Address would be the class, leaving address 
available for an instance of the class:

address = Address()


>     def __init__(self, name, tel, email):
>         self.name = name
>         self.tel = tel
>         self.email = email
>         ab = {self.name : self.tel}
>         f = file(addressbook, 'r+')
>         p.dump(ab, f)
>
> print p.load(f)
> x = raw_input()
>
> if x == 'add':
>     name = raw_input('\nName: ')

To get a blank line before the prompt, it might be nicer to do this:

print
name = raw_input('Name: ')

That's a matter of personal preference though.


>     tel = raw_input('Tel: ')
>     email = raw_input('Email: ')
>     contact = address(name, tel, email)




Hope this helps,



-- 
Steven D'Aprano

From davea at ieee.org  Thu Sep  9 00:14:45 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 08 Sep 2010 18:14:45 -0400
Subject: [Tutor] how to create a persistent dictionary w/ cpickle?
In-Reply-To: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>
References: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>
Message-ID: <4C880AD5.5040104@ieee.org>

  On 2:59 PM, Carter Danforth wrote:
> Hi, I'm trying to a create a basic addressbook for practice. I'm using a
> dictionary with cpickle, though I'm not sure how to persistently store each
> instance in the dictionary. Below is the code I have so far.
>
> If I run it once and add a contact and the details, it's fine. p.load(f)
> shows the details next time I run it, but if I add another contact, and run
> it again, the previous key:value doesn't show. It gets replaced by the new
> one.
>
> How can I fix this so that it adds the new key:value to the dictionary
> instead of replacing the existing one? Appreciate any help, thanks.
>
> import cPickle as p
> addressbook = 'addressbook.data'
> f = file(addressbook, 'r+')
>
> class address:
>      def __init__(self, name, tel, email):
>          self.name = name
>          self.tel = tel
>          self.email = email
>
>          ab = {self.name : self.tel}
>
>          f = file(addressbook, 'r+')
>          p.dump(ab, f)
>
> print p.load(f)
> x = raw_input()
>
> if x == 'add':
>      name = raw_input('\nName: ')
>      tel = raw_input('Tel: ')
>      email = raw_input('Email: ')
>
>      contact = address(name, tel, email)
>
I have no clue what you're trying to do with that address object;  it's 
confusing initialization with persistence, and you create such an 
object, but never actually use it.  I would remove any reference to the 
address book from that object.  I'd also rename it to Address, since 
class names are supposed to be uppercase (PEP8)

But anyway, in your flow, you do a p.load(), but never save the result.  
Every time you save to the addressbook file, you start over with just 
the one entry.

One way to fix this is to save the p.load() result as a variable, 
presumably of type dictionary, then add the 'contact' to that 
dictionary, and at the end of the script, save that variable with 
p.dump(addresses, f)

addresses =   p.load(f)

interact with user --
            addresses[name] = Address(name, tel, email)

p.dump(addresses, f)

I also don' t know how you get away with running your script the first 
time, since it blows up if there's no existing pickle file.

DaveA


From alan.gauld at btinternet.com  Thu Sep  9 02:17:12 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 9 Sep 2010 01:17:12 +0100
Subject: [Tutor] how to create a persistent dictionary w/ cpickle?
References: <AANLkTi=ZvDxMfKHH8mf=VQ4X8fUDQX239UBS0G+ziOy6@mail.gmail.com>
Message-ID: <i69925$6rk$1@dough.gmane.org>


"Carter Danforth" <carter.danforth at gmail.com> wrote

> Hi, I'm trying to a create a basic addressbook for practice. I'm 
> using a
> dictionary with cpickle, though I'm not sure how to persistently 
> store each
> instance in the dictionary. Below is the code I have so far.

If you use a dictionary it makes more sense to use shelve rather than 
pickle for storage.
Shelve uses pickle under the hood but it makes a file look like a 
dictionary so you
don't need to load all the data and store it all again as you would 
with pickle.

Unfioortunately your code appears to be truncated, however...

> import cPickle as p
> addressbook = 'addressbook.data'
> f = file(addressbook, 'r+')

I think you should use a binary file for pickle so the mode should be 
'rb' not 'r+'

HTH,

Alan G 



From sandipb at foss-community.com  Thu Sep  9 07:49:39 2010
From: sandipb at foss-community.com (Sandip Bhattacharya)
Date: Thu, 9 Sep 2010 11:19:39 +0530
Subject: [Tutor] slicing a string
In-Reply-To: <i64sip$1fm$1@dough.gmane.org>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<i63qqb$tkk$1@dough.gmane.org> <i64sip$1fm$1@dough.gmane.org>
Message-ID: <AANLkTinnzizKw4Uadk6PDYpEczJJYra_OTxAAC7d8SNp@mail.gmail.com>

On Tue, Sep 7, 2010 at 1:49 PM, Roel Schroeven
<rschroev_nospam_ml at fastmail.fm> wrote:
>
> But remember that you can make it simpler if you simply don't specify
> the start and end points:
>
>>>> 'hello'[::-1]
> 'olleh'
>

While I know that idiom works, I haven't really found an explanation
as to *why* it works that way.

For a string S:
* Using  range, you need range(len(S),-1,-1) to give you the indexes
for the string in reverse.
* For slices, if you dont specify the start and end indices, they are
supposed to be filled in by 0 and len(S) respectively.
  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
0 here, and then go to -1 (last char) and then into an infinite loop?
  - Especially, when S[0:len(S):1] works that way?

- Sandip

From evert.rol at gmail.com  Thu Sep  9 08:04:04 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 9 Sep 2010 08:04:04 +0200
Subject: [Tutor] slicing a string
In-Reply-To: <AANLkTinnzizKw4Uadk6PDYpEczJJYra_OTxAAC7d8SNp@mail.gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<i63qqb$tkk$1@dough.gmane.org> <i64sip$1fm$1@dough.gmane.org>
	<AANLkTinnzizKw4Uadk6PDYpEczJJYra_OTxAAC7d8SNp@mail.gmail.com>
Message-ID: <DBA494E3-37EE-4035-A4E4-616241BFE5F8@gmail.com>

>> But remember that you can make it simpler if you simply don't specify
>> the start and end points:
>> 
>>>>> 'hello'[::-1]
>> 'olleh'
>> 
> 
> While I know that idiom works, I haven't really found an explanation
> as to *why* it works that way.
> 
> For a string S:
> * Using  range, you need range(len(S),-1,-1) to give you the indexes
> for the string in reverse.
> * For slices, if you dont specify the start and end indices, they are
> supposed to be filled in by 0 and len(S) respectively.
>  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
> 0 here, and then go to -1 (last char) and then into an infinite loop?

I guess because Python "is smart", and works the way you want/expect it to.
Read http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange , note 5 (about one "page" down), which explicitly says "If i or j are omitted or None, they become ?end? values (which end depends on the sign of k)", where the important bit for this discussion is actually between parentheses.

And to quote part of the Zen of Python:
"
Special cases aren't special enough to break the rules.
Although practicality beats purity.
"

Reversing the automatic end values is very practical when the step index < 0.


>  - Especially, when S[0:len(S):1] works that way?
> 
> - Sandip
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From sandipb at foss-community.com  Thu Sep  9 08:19:46 2010
From: sandipb at foss-community.com (Sandip Bhattacharya)
Date: Thu, 9 Sep 2010 11:49:46 +0530
Subject: [Tutor] slicing a string
In-Reply-To: <DBA494E3-37EE-4035-A4E4-616241BFE5F8@gmail.com>
References: <AANLkTi=3Ve1eC=LGYiJG64qfO2rweQ=7rA3OaxG_4nvT@mail.gmail.com>
	<i63qqb$tkk$1@dough.gmane.org> <i64sip$1fm$1@dough.gmane.org>
	<AANLkTinnzizKw4Uadk6PDYpEczJJYra_OTxAAC7d8SNp@mail.gmail.com>
	<DBA494E3-37EE-4035-A4E4-616241BFE5F8@gmail.com>
Message-ID: <AANLkTim+KPva5KPX2kq7v3EYFA68jL=dm5y87PYrkUdx@mail.gmail.com>

On Thu, Sep 9, 2010 at 11:34 AM, Evert Rol <evert.rol at gmail.com> wrote:
> Read
> http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange
> , note 5 (about one "page" down), which explicitly says "If i or j are
> omitted or None, they become ?end? values (which end depends on the
> sign of k)", where the important bit for this discussion is actually
> between parentheses.

Great! That is exactly what I needed to know. The reference I learnt
extended slices from, probably didn't include this subtlety.

Thanks,
 Sandip

From rwobben at hotmail.com  Thu Sep  9 10:51:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 9 Sep 2010 08:51:46 +0000
Subject: [Tutor] recursive problem
Message-ID: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>


Hello, 

 

I have this :

 

def recursive_count(target, nested_num_list):
    """
      >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
      4
      >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
      2
      >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
      0
      >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
      6
    """
    for element in nested_num_list:
        if type(element) == type([]):
           test = recursive_count(target, element)
        print element, target
        if element == target :
           count = count + 1
    return count

 

if __name__ == "__main__":
    import doctest
    doctest.testmod()

 

 

Now I get this message :

 

UnboundLocalError: local variable 'count' referenced before assignment

 

But if I do this :

 

def recursive_count(target, nested_num_list):
    """
      >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
      4
      >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
      2
      >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
      0
      >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
      6
    """
  count = 0 

  for element in nested_num_list:
        if type(element) == type([]):
           test = recursive_count(target, element)
        print element, target
        if element == target :
           count = count + 1
    return count

 

if __name__ == "__main__":
    import doctest
    doctest.testmod()

 

The count will always be 0 if a nested list is being found.

 

What's the python way to solve this 

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/fa1a1dc8/attachment.html>

From anand.shashwat at gmail.com  Thu Sep  9 11:38:10 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Thu, 9 Sep 2010 15:08:10 +0530
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
Message-ID: <AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>

On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

>  Hello,
>
> I have this :
>
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>     for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
>
> Now I get this message :
>
> UnboundLocalError: local variable 'count' referenced before assignment
>

It is because you are doing count = count + 1
But where is count defined.


>
> But if I do this :
>
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>   count = 0
>   for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
> The count will always be 0 if a nested list is being found.
>
> What's the python way to solve this
>

I am not sure what do you want to achieve by this ?
What is the problem statement ?


>
> Roelof
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/092878a1/attachment.html>

From rwobben at hotmail.com  Thu Sep  9 11:41:39 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 9 Sep 2010 09:41:39 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
Message-ID: <SNT118-W53335D70668E9A3514A773AE730@phx.gbl>



 


From: anand.shashwat at gmail.com
Date: Thu, 9 Sep 2010 15:08:10 +0530
Subject: Re: [Tutor] recursive problem
To: rwobben at hotmail.com
CC: tutor at python.org




On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com> wrote:


Hello, 
 
I have this :
 
def recursive_count(target, nested_num_list):
    """
      >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
      4
      >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
      2
      >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
      0
      >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
      6
    """
    for element in nested_num_list:
        if type(element) == type([]):
           test = recursive_count(target, element)
        print element, target
        if element == target :
           count = count + 1
    return count
 
if __name__ == "__main__":
    import doctest
    doctest.testmod()
 
 
Now I get this message :
 
UnboundLocalError: local variable 'count' referenced before assignment


It is because you are doing count = count + 1
But where is count defined.
 


 
But if I do this :
 
def recursive_count(target, nested_num_list):
    """
      >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
      4
      >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
      2
      >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
      0
      >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
      6
    """
  count = 0 
  for element in nested_num_list:
        if type(element) == type([]):
           test = recursive_count(target, element)
        print element, target
        if element == target :
           count = count + 1
    return count
 
if __name__ == "__main__":
    import doctest
    doctest.testmod()
 
The count will always be 0 if a nested list is being found.
 
What's the python way to solve this 


I am not sure what do you want to achieve by this ?
What is the problem statement ?
 
The problem statement is that I must count how many times the target is in the nested_list.
So I thougt that every nested list the function is called again so this list is also iterated.
 
Roelof
  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/3cef90a6/attachment.html>

From anand.shashwat at gmail.com  Thu Sep  9 13:59:43 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Thu, 9 Sep 2010 17:29:43 +0530
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
Message-ID: <AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>

On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
> ------------------------------
> From: anand.shashwat at gmail.com
> Date: Thu, 9 Sep 2010 15:08:10 +0530
> Subject: Re: [Tutor] recursive problem
> To: rwobben at hotmail.com
> CC: tutor at python.org
>
>
>
> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
> Hello,
>
> I have this :
>
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>     for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
>
> Now I get this message :
>
> UnboundLocalError: local variable 'count' referenced before assignment
>
>
> It is because you are doing count = count + 1
> But where is count defined.
>
>
>
> But if I do this :
>
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>   count = 0
>   for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>
> The count will always be 0 if a nested list is being found.
>
> What's the python way to solve this
>
>
> I am not sure what do you want to achieve by this ?
> What is the problem statement ?
>
> The problem statement is that I must count how many times the target is in
> the nested_list.
> So I thougt that every nested list the function is called again so this
> list is also iterated.
>

Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
2, 1,13, 2, 8, 2, 6 ]
Now count for n; flatten.count(n)



-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/76befe61/attachment.html>

From wprins at gmail.com  Thu Sep  9 14:26:58 2010
From: wprins at gmail.com (Walter Prins)
Date: Thu, 9 Sep 2010 13:26:58 +0100
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
	<AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
Message-ID: <AANLkTi=-xDFB-iPo7EuwaLL-Cg3NH4MUx22TNz_1g6xE@mail.gmail.com>

On 9 September 2010 12:59, Shashwat Anand <anand.shashwat at gmail.com> wrote:

>
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
> 2, 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
>
>
This is fine except that the excercise probably has to do with introducing
recursion and scoping, which is unfortunately defeated by this solution.

Roelof, look at what you do with the result of the recursive call  which you
currently assign to test and otherwise ignore -- you want to add this to
count and/or return it...

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/326dd36a/attachment.html>

From joel.goldstick at gmail.com  Thu Sep  9 14:33:09 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 9 Sep 2010 08:33:09 -0400
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
	<AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
Message-ID: <AANLkTimqict3EO+3Q0gQOuzviHDink-TTnjO87HqpLtS@mail.gmail.com>

On Thu, Sep 9, 2010 at 7:59 AM, Shashwat Anand <anand.shashwat at gmail.com>wrote:

>
>
> On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>>
>>
>> ------------------------------
>> From: anand.shashwat at gmail.com
>> Date: Thu, 9 Sep 2010 15:08:10 +0530
>> Subject: Re: [Tutor] recursive problem
>> To: rwobben at hotmail.com
>> CC: tutor at python.org
>>
>>
>>
>> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com>wrote:
>>
>> Hello,
>>
>> I have this :
>>
>> def recursive_count(target, nested_num_list):
>>     """
>>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>>       4
>>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>>       2
>>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>>       0
>>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>>       6
>>     """
>>     for element in nested_num_list:
>>         if type(element) == type([]):
>>            test = recursive_count(target, element)
>>         print element, target
>>         if element == target :
>>            count = count + 1
>>     return count
>>
>> if __name__ == "__main__":
>>     import doctest
>>     doctest.testmod()
>>
>>
What you are trying to do is walk through the list.  If you get a value and
not another list, check if it is the value you are counting.  If it is,
added it to your count.
When you are done walking, return  your count.  If you get another list,
walk through the list

> So here is my stab at the code
>>
>>  14   count =
0
# set your count to 0
 15     for element in
nested_num_list:                                         # walk through each
element
 16         if type(element) == type([]):
 17             count += recursive_count(target, element)                  #
since its another list start anew and add the count result to what you
already have
 18         elif element ==
target:                                                   # its a value, so
check if its YOUR value, and if it is, increment your counter
 19                 count += 1
 20                 #print element, count
 21     return
count                                                                     #
must be done.  You get here each time you walk thru a list
 22



>
>> Now I get this message :
>>
>> UnboundLocalError: local variable 'count' referenced before assignment
>>
>>
>> It is because you are doing count = count + 1
>> But where is count defined.
>>
>>
>>
>> But if I do this :
>>
>> def recursive_count(target, nested_num_list):
>>     """
>>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>>       4
>>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>>       2
>>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>>       0
>>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>>       6
>>     """
>>   count = 0
>>   for element in nested_num_list:
>>         if type(element) == type([]):
>>            test = recursive_count(target, element)
>>         print element, target
>>         if element == target :
>>            count = count + 1
>>     return count
>>
>> if __name__ == "__main__":
>>     import doctest
>>     doctest.testmod()
>>
>> The count will always be 0 if a nested list is being found.
>>
>> What's the python way to solve this
>>
>>
>> I am not sure what do you want to achieve by this ?
>> What is the problem statement ?
>>
>> The problem statement is that I must count how many times the target is in
>> the nested_list.
>> So I thougt that every nested list the function is called again so this
>> list is also iterated.
>>
>
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9,
> 2, 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
>
>
>
> --
> ~l0nwlf
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/9732aa65/attachment-0001.html>

From rabidpoobear at gmail.com  Thu Sep  9 16:26:17 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 9 Sep 2010 09:26:17 -0500
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTimqict3EO+3Q0gQOuzviHDink-TTnjO87HqpLtS@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
	<AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
	<AANLkTimqict3EO+3Q0gQOuzviHDink-TTnjO87HqpLtS@mail.gmail.com>
Message-ID: <B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>

Shouldn't there be a way to do this without type checking? Duck typing!

Sent from my iPhone

On Sep 9, 2010, at 7:33 AM, Joel Goldstick <joel.goldstick at gmail.com> wrote:

> 
> 
> On Thu, Sep 9, 2010 at 7:59 AM, Shashwat Anand <anand.shashwat at gmail.com> wrote:
> 
> 
> On Thu, Sep 9, 2010 at 3:11 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
> 
>  
> From: anand.shashwat at gmail.com
> Date: Thu, 9 Sep 2010 15:08:10 +0530
> Subject: Re: [Tutor] recursive problem
> To: rwobben at hotmail.com
> CC: tutor at python.org
> 
> 
> 
> On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
> Hello, 
>  
> I have this :
>  
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>     for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>  
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
> 
> What you are trying to do is walk through the list.  If you get a value and not another list, check if it is the value you are counting.  If it is, added it to your count.
> When you are done walking, return  your count.  If you get another list, walk through the list 
> So here is my stab at the code 
>  14   count = 0                                                                           # set your count to 0
>  15     for element in nested_num_list:                                         # walk through each element
>  16         if type(element) == type([]):
>  17             count += recursive_count(target, element)                  # since its another list start anew and add the count result to what you already have
>  18         elif element == target:                                                   # its a value, so check if its YOUR value, and if it is, increment your counter
>  19                 count += 1
>  20                 #print element, count
>  21     return count                                                                     # must be done.  You get here each time you walk thru a list
>  22 
> 
>  
>  
> Now I get this message :
>  
> UnboundLocalError: local variable 'count' referenced before assignment
> 
> It is because you are doing count = count + 1
> But where is count defined.
>  
>  
> But if I do this :
>  
> def recursive_count(target, nested_num_list):
>     """
>       >>> recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
>       4
>       >>> recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
>       2
>       >>> recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
>       0
>       >>> recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
>       6
>     """
>   count = 0 
>   for element in nested_num_list:
>         if type(element) == type([]):
>            test = recursive_count(target, element)
>         print element, target
>         if element == target :
>            count = count + 1
>     return count
>  
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
>  
> The count will always be 0 if a nested list is being found.
>  
> What's the python way to solve this 
> 
> I am not sure what do you want to achieve by this ?
> What is the problem statement ?
>  
> The problem statement is that I must count how many times the target is in the nested_list.
> So I thougt that every nested list the function is called again so this list is also iterated.
> 
> Let's say n, l = 2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]
> Simply Flatten the list l, which will be then be; flatten(l) = [ 2, [2, 9, 2, 1,13, 2, 8, 2, 6 ]
> Now count for n; flatten.count(n)
> 
> 
> 
> -- 
> ~l0nwlf
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Joel Goldstick
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/0935cbab/attachment.html>

From joel.goldstick at gmail.com  Thu Sep  9 17:05:22 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 9 Sep 2010 11:05:22 -0400
Subject: [Tutor] recursive problem
In-Reply-To: <B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>
	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>
	<AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>
	<AANLkTimqict3EO+3Q0gQOuzviHDink-TTnjO87HqpLtS@mail.gmail.com>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
Message-ID: <AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>

On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
<rabidpoobear at gmail.com>wrote:

> Shouldn't there be a way to do this without type checking? Duck typing!
>
> Your post got me thinking.  Maybe better to test if the object can return
an iter method.  If it throws an error, then look at its value.  If it
doesn't, then its a list or a tuple
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/1b426713/attachment.html>

From fal at libero.it  Thu Sep  9 17:29:31 2010
From: fal at libero.it (Francesco Loffredo)
Date: Thu, 09 Sep 2010 17:29:31 +0200
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>	<AANLkTimK2Ve7t7baYODTks2sWesUWsCiWp-zuuoe1KSN@mail.gmail.com>	<SNT118-W53335D70668E9A3514A773AE730@phx.gbl>	<AANLkTinA9TOJGSSxGo2bfg2V8pP4Y47u44Oq5bN5L61d@mail.gmail.com>	<AANLkTimqict3EO+3Q0gQOuzviHDink-TTnjO87HqpLtS@mail.gmail.com>	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
Message-ID: <4C88FD5B.90202@libero.it>

On 09/09/2010 17.05, Joel Goldstick wrote:
>
>
> On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
> <rabidpoobear at gmail.com <mailto:rabidpoobear at gmail.com>> wrote:
>
>     Shouldn't there be a way to do this without type checking? Duck typing!
>
> Your post got me thinking.  Maybe better to test if the object can
> return an iter method.  If it throws an error, then look at its value.
> If it doesn't, then its a list or a tuple

... Oh, my ...

I think type checking is simpler. Maybe not that duckly, but...

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3121 -  Data di rilascio: 09/08/10 08:07:00

From steve at pearwood.info  Thu Sep  9 18:07:11 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 10 Sep 2010 02:07:11 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
Message-ID: <201009100207.12024.steve@pearwood.info>

On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
>
> <rabidpoobear at gmail.com>wrote:
> > Shouldn't there be a way to do this without type checking? Duck
> > typing!
> >
> > Your post got me thinking.  Maybe better to test if the object can
> > return
> an iter method.  If it throws an error, then look at its value.  If
> it doesn't, then its a list or a tuple


It's not clear what you mean by "return an iter method". Taken 
literally, that would imply the object is a function. I think you 
mean "*has* an iter method" -- except that's not right either:

>>> [].iter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'iter'


Perhaps you mean an object which can be passed to iter(), but lots of 
objects can do that, not just lists and tuples:

>>> iter("not a list or tuple")
<str_iterator object at 0xb7d3520c>
>>> iter({1: None, 2: "a", 4: 5})
<dict_keyiterator object at 0xb7d3420c>





-- 
Steven D'Aprano

From joel.goldstick at gmail.com  Thu Sep  9 18:41:40 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 9 Sep 2010 12:41:40 -0400
Subject: [Tutor] recursive problem
In-Reply-To: <201009100207.12024.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
	<201009100207.12024.steve@pearwood.info>
Message-ID: <AANLkTinKk9h5u+M22Sc9A_bezkM4L44TAb5JkHR=pv-n@mail.gmail.com>

On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> > On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
> >
> > <rabidpoobear at gmail.com>wrote:
> > > Shouldn't there be a way to do this without type checking? Duck
> > > typing!
> > >
> > > Your post got me thinking.  Maybe better to test if the object can
> > > return
> > an iter method.  If it throws an error, then look at its value.  If
> > it doesn't, then its a list or a tuple
>
>
> It's not clear what you mean by "return an iter method". Taken
> literally, that would imply the object is a function. I think you
> mean "*has* an iter method" -- except that's not right either:
>
> >>> [].iter
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'list' object has no attribute 'iter'
>
>
> Perhaps you mean an object which can be passed to iter(), but lots of
> objects can do that, not just lists and tuples:
>
> >>> iter("not a list or tuple")
> <str_iterator object at 0xb7d3520c>
> >>> iter({1: None, 2: "a", 4: 5})
> <dict_keyiterator object at 0xb7d3420c>
>
>
> I was googling, and found that if an object has an __iter__ method it will
> return it.  If not it will throw an error.  You are right about more than
> lists and tuples being iterable.  But, in this thread, it was brought up
> that checking type may not be pythonic.  If you wanted to use the same code
> to find values in a nested list of any objects, you could dispense with the
> type checking and just see if it is iterable.
>

I'm new to python.  Am I off base?

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



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/ad3a22b7/attachment.html>

From rabidpoobear at gmail.com  Thu Sep  9 19:59:46 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 9 Sep 2010 12:59:46 -0500
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTinKk9h5u+M22Sc9A_bezkM4L44TAb5JkHR=pv-n@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
	<201009100207.12024.steve@pearwood.info>
	<AANLkTinKk9h5u+M22Sc9A_bezkM4L44TAb5JkHR=pv-n@mail.gmail.com>
Message-ID: <35308F2B-F3F8-4F86-B868-FD149FE5740A@gmail.com>

Nope Joel, that's what I meant. Remember EAFP over LBYL! I'm not sure the best way to make sure the object is iterable though.

Sent from my iPhone

On Sep 9, 2010, at 11:41 AM, Joel Goldstick <joel.goldstick at gmail.com> wrote:

> 
> 
> On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> > On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
> >
> > <rabidpoobear at gmail.com>wrote:
> > > Shouldn't there be a way to do this without type checking? Duck
> > > typing!
> > >
> > > Your post got me thinking.  Maybe better to test if the object can
> > > return
> > an iter method.  If it throws an error, then look at its value.  If
> > it doesn't, then its a list or a tuple
> 
> 
> It's not clear what you mean by "return an iter method". Taken
> literally, that would imply the object is a function. I think you
> mean "*has* an iter method" -- except that's not right either:
> 
> >>> [].iter
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'list' object has no attribute 'iter'
> 
> 
> Perhaps you mean an object which can be passed to iter(), but lots of
> objects can do that, not just lists and tuples:
> 
> >>> iter("not a list or tuple")
> <str_iterator object at 0xb7d3520c>
> >>> iter({1: None, 2: "a", 4: 5})
> <dict_keyiterator object at 0xb7d3420c>
> 
> 
> I was googling, and found that if an object has an __iter__ method it will return it.  If not it will throw an error.  You are right about more than lists and tuples being iterable.  But, in this thread, it was brought up that checking type may not be pythonic.  If you wanted to use the same code to find values in a nested list of any objects, you could dispense with the type checking and just see if it is iterable.
> 
> I'm new to python.  Am I off base? 
> 
> 
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -- 
> Joel Goldstick
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/73e3c886/attachment.html>

From igor.python at gmail.com  Thu Sep  9 21:34:49 2010
From: igor.python at gmail.com (Igor Choromanski)
Date: Thu, 9 Sep 2010 13:34:49 -0600
Subject: [Tutor] Python social network / cms components?
Message-ID: <AANLkTikzMH76=du0sQ-xPEu4U16FJyx9VPfv2tm=YBY9@mail.gmail.com>

Hi,

After much research, I've come up with a list of what I think might be
the best way of putting together a Python based social network/cms,
but have some questions about how some of these components fit
together.

Before I ask about the particular components, here are some of the key
features of the site to be built:

- a modern almost desktop-like gui
- future ability to host an advanced html5 sub-application
(ex.http://www.lucidchart.com)
- high scalability both for functionality and user load
- user ability to password protect and permission manage content on
per item/group basis
- typical social network features
- ability to build a scaled down mobile version in the future

Here's the list of tools I'm considering using:

Google App Engine
Python
Django
Pinax
Pyjamas
wxPython

And the questions:

1. Google App Engine -- this is an attempt to cut to the chase as many
pieces of the puzzle seem to be in place.
Question: Am I limiting my options with this choice? Example:
datastore not being relational? Should I wait
for SQL support under the Business version?

2. Python -- I considered 'drupal' at first, but in the end decided
that being dependent on modules that may or
may not exist tomorrow + limitations of its templating system are a
no-no. Learning its API, too, would be useless elsewhere
whereas Python seems like a swiss army knife of languages -- good for
almost anything.
Question: v.2.5.2 is required by GAE, but python.org recommends 2.5.5.
Which do I install?

3. Django -- v.0.96 is built into GAE. You seem to be able to upgrade it.
Questions: Any reason not to upgrade to the latest version? Ways to
get around the lack of HTML5 support?

4. Pinax (http://pinaxproject.com) Rides on top of Django and appears
to provide most of the social network functionality
anyone would want.
Question:  Reasons NOT to use it? Alternatives?

5. Pyjamas and wxPython -- this is the part that gets a little
confusing. The basic idea behind these is the ability
to build a GUI. I've considered Silverlight and Flash, before the
GAE/Python route, but a few working versions of
HTML5 apps convinced me that enough of it ALREADY runs on the latest
batch of browsers to chose the HTML5/Javascript
route instead.
Question: How do I extend/supplement Python/Django to build an
app-like HTML5 interface? Are Pyjamas and wxPython
the way to go? Or should I change my thinking completely?

Answers to some/any of these questions would be of great help. Please
excuse my ignorance if any of this doesn't make much sense.
My last venture into web programming was a decent sized LAMP website
some 5-6 years ago.  On the desktop side of things,
my programming experience boils down to very high level scripting
languages that I keep on learning to accomplish very specific
tasks :)

Thank you all,
- igor

From lists at justuber.com  Thu Sep  9 22:51:38 2010
From: lists at justuber.com (lists)
Date: Thu, 9 Sep 2010 21:51:38 +0100
Subject: [Tutor] Random list exercise
Message-ID: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>

Hi tutors,

Still on my Python learning journey! I've just competed an exercise
which asks the student to "Create a program that creates a list of
words in random order. This program should print all the words and not
repeat any." I've printed the list for my own needs. The list
randwords aims to answer the specific request of the exercise author.

If anyone has the inclination and a minute to spare, please run your
eyes over my answer. It works, but is it an OK way to approach the
exercise?

Thanks again :-D

Chris

import random

#LIST
words = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven"]
randwords = []

while words: #has entries in it
    wordslen = len(words) #get the length of the list
    index = random.randint(0, wordslen -1) #get a random index
    chosenword = words[index]
    randwords.append(chosenword) #append the random word to a new list
    del words[index] #del the word from the old list

for word in randwords:
    print word # print them

From joel.goldstick at gmail.com  Thu Sep  9 23:42:54 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 9 Sep 2010 17:42:54 -0400
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
Message-ID: <AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>

On Thu, Sep 9, 2010 at 4:51 PM, lists <lists at justuber.com> wrote:

> Hi tutors,
>
> Still on my Python learning journey! I've just competed an exercise
> which asks the student to "Create a program that creates a list of
> words in random order. This program should print all the words and not
> repeat any." I've printed the list for my own needs. The list
> randwords aims to answer the specific request of the exercise author.
>
> If anyone has the inclination and a minute to spare, please run your
> eyes over my answer. It works, but is it an OK way to approach the
> exercise?
>
> Thanks again :-D
>
> Chris
>
> import random
>
> #LIST
> words = ["one", "two", "three", "four", "five", "six", "seven",
> "eight", "nine", "ten", "eleven"]
> randwords = []
>
> while words: #has entries in it
>    wordslen = len(words) #get the length of the list
>    index = random.randint(0, wordslen -1) #get a random index
>    chosenword = words[index]
>    randwords.append(chosenword) #append the random word to a new list
>    del words[index] #del the word from the old list
>
> for word in randwords:
>    print word # print them
>

Several small and not so small points:

1. you assign wordslen each pass through your loop.  While it doesn't matter
in a small loop, it wastes time on the order of the size of your list.
Instead move wordslen = len(...  above your while loop.  Any time you put
code in a loop that doesn't change in each iteration, you should move it out
of the loop.

2. since you only use chosenword once in your loop, you could remove
chosenword = words[index] line and replace chosenword in the append(... with
words[index]

3. your list doesn't contain any duplicate words.  Since  your program is
supposed to catch this, you should add a duplicate to see if it works.
(No!)

4. I think your line del words[index] is supposed to help out with item 3
but it doesn't.  It just removes the word you just used selected.

5. And finally, I think you want to print

Just minor points.  nice job -- getting there
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/851a2093/attachment.html>

From joel.goldstick at gmail.com  Fri Sep 10 00:02:32 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 9 Sep 2010 18:02:32 -0400
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
Message-ID: <AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>

On Thu, Sep 9, 2010 at 5:42 PM, Joel Goldstick <joel.goldstick at gmail.com>wrote:

>
>
> On Thu, Sep 9, 2010 at 4:51 PM, lists <lists at justuber.com> wrote:
>
>> Hi tutors,
>>
>> Still on my Python learning journey! I've just competed an exercise
>> which asks the student to "Create a program that creates a list of
>> words in random order. This program should print all the words and not
>> repeat any." I've printed the list for my own needs. The list
>> randwords aims to answer the specific request of the exercise author.
>>
>> If anyone has the inclination and a minute to spare, please run your
>> eyes over my answer. It works, but is it an OK way to approach the
>> exercise?
>>
>> Thanks again :-D
>>
>> Chris
>>
>> import random
>>
>> #LIST
>> words = ["one", "two", "three", "four", "five", "six", "seven",
>> "eight", "nine", "ten", "eleven"]
>> randwords = []
>>
>> while words: #has entries in it
>>    wordslen = len(words) #get the length of the list
>>    index = random.randint(0, wordslen -1) #get a random index
>>    chosenword = words[index]
>>    randwords.append(chosenword) #append the random word to a new list
>>    del words[index] #del the word from the old list
>>
>> for word in randwords:
>>    print word # print them
>>
>
> Several small and not so small points:
>
> 1. you assign wordslen each pass through your loop.  While it doesn't
> matter in a small loop, it wastes time on the order of the size of your
> list.  Instead move wordslen = len(...  above your while loop.  Any time you
> put code in a loop that doesn't change in each iteration, you should move it
> out of the loop.
>
> 2. since you only use chosenword once in your loop, you could remove
> chosenword = words[index] line and replace chosenword in the append(... with
> words[index]
>
> 3. your list doesn't contain any duplicate words.  Since  your program is
> supposed to catch this, you should add a duplicate to see if it works.
> (No!)
>
> 4. I think your line del words[index] is supposed to help out with item 3
> but it doesn't.  It just removes the word you just used selected.
>
> 5. And finally, I think you want to print
>
> Just minor points.  nice job -- getting there
> --
> Joel Goldstick
>
>

I looked into this a little more, and although I'm ok with my comments, I
did some experimenting and looked into the stuff in random.  I came up with
this.  It may not be helpful since you may be learning about loops and
randint, but this works:

import random

#LIST
words = ["one", "two", "three", "four", "five", "six", "seven",
                    "eight", "four", "nine", "ten", "eleven"]

word_set = list(set(words))    # this removes duplicates since set contains
one of each value.  Then convert back to a list
print "original words: ", words    # just wanted to see my original list
print "removed duplicates with set:", word_set   # this shows that I don't
have duplicates
random.shuffle(word_set)  # this shuffles the list in place.  Now word_set
is shuffled (randomized!)
print "randomized: ", word_set   # see!



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/e3ec4c77/attachment.html>

From lists at justuber.com  Fri Sep 10 00:04:01 2010
From: lists at justuber.com (lists)
Date: Thu, 9 Sep 2010 23:04:01 +0100
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
Message-ID: <AANLkTinx3J8oHCwswbAn+u3_dSTbCZoMS6RYsfD-EoDy@mail.gmail.com>

>
>
> On Thu, Sep 9, 2010 at 4:51 PM, lists <lists at justuber.com> wrote:
>>
>> Hi tutors,
>>
>> Still on my Python learning journey! I've just competed an exercise
>> which asks the student to "Create a program that creates a list of
>> words in random order. This program should print all the words and not
>> repeat any." I've printed the list for my own needs. The list
>> randwords aims to answer the specific request of the exercise author.
>>
>> If anyone has the inclination and a minute to spare, please run your
>> eyes over my answer. It works, but is it an OK way to approach the
>> exercise?
>>
>> Thanks again :-D
>>
>> Chris
>>
>> import random
>>
>> #LIST
>> words = ["one", "two", "three", "four", "five", "six", "seven",
>> "eight", "nine", "ten", "eleven"]
>> randwords = []
>>
>> while words: #has entries in it
>> ? ?wordslen = len(words) #get the length of the list
>> ? ?index = random.randint(0, wordslen -1) #get a random index
>> ? ?chosenword = words[index]
>> ? ?randwords.append(chosenword) #append the random word to a new list
>> ? ?del words[index] #del the word from the old list
>>
>> for word in randwords:
>> ? ?print word # print them
>
> Several small and not so small points:
>
> 1. you assign wordslen each pass through your loop.? While it doesn't matter
> in a small loop, it wastes time on the order of the size of your list.
> Instead move wordslen = len(...? above your while loop.? Any time you put
> code in a loop that doesn't change in each iteration, you should move it out
> of the loop.
>
> 2. since you only use chosenword once in your loop, you could remove
> chosenword = words[index] line and replace chosenword in the append(... with
> words[index]
>
> 3. your list doesn't contain any duplicate words.? Since? your program is
> supposed to catch this, you should add a duplicate to see if it works.
> (No!)
>
> 4. I think your line del words[index] is supposed to help out with item 3
> but it doesn't.? It just removes the word you just used selected.
>
> 5. And finally, I think you want to print
>
> Just minor points.? nice job -- getting there
> --
> Joel Goldstick
>

Ah, back to the drawing boards! I'll fix and post back!

Chris

From lists at justuber.com  Fri Sep 10 00:22:14 2010
From: lists at justuber.com (lists)
Date: Thu, 9 Sep 2010 23:22:14 +0100
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
Message-ID: <AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>

>>>
>>> Hi tutors,
>>>
>>> Still on my Python learning journey! I've just competed an exercise
>>> which asks the student to "Create a program that creates a list of
>>> words in random order. This program should print all the words and not
>>> repeat any." I've printed the list for my own needs. The list
>>> randwords aims to answer the specific request of the exercise author.
>>>
>>> If anyone has the inclination and a minute to spare, please run your
>>> eyes over my answer. It works, but is it an OK way to approach the
>>> exercise?
>>>
>>> Thanks again :-D
>>>
>>> Chris
>>>
>>> import random
>>>
>>> #LIST
>>> words = ["one", "two", "three", "four", "five", "six", "seven",
>>> "eight", "nine", "ten", "eleven"]
>>> randwords = []
>>>
>>> while words: #has entries in it
>>> ? ?wordslen = len(words) #get the length of the list
>>> ? ?index = random.randint(0, wordslen -1) #get a random index
>>> ? ?chosenword = words[index]
>>> ? ?randwords.append(chosenword) #append the random word to a new list
>>> ? ?del words[index] #del the word from the old list
>>>
>>> for word in randwords:
>>> ? ?print word # print them
>>
>> Several small and not so small points:
>>
>> 1. you assign wordslen each pass through your loop.? While it doesn't
>> matter in a small loop, it wastes time on the order of the size of your
>> list.? Instead move wordslen = len(...? above your while loop.? Any time you
>> put code in a loop that doesn't change in each iteration, you should move it
>> out of the loop.
>>
>> 2. since you only use chosenword once in your loop, you could remove
>> chosenword = words[index] line and replace chosenword in the append(... with
>> words[index]
>>
>> 3. your list doesn't contain any duplicate words.? Since? your program is
>> supposed to catch this, you should add a duplicate to see if it works.
>> (No!)
>>
>> 4. I think your line del words[index] is supposed to help out with item 3
>> but it doesn't.? It just removes the word you just used selected.
>>
>> 5. And finally, I think you want to print
>>
>> Just minor points.? nice job -- getting there
>> --
>> Joel Goldstick
>>
>
>
> I looked into this a little more, and although I'm ok with my comments, I
> did some experimenting and looked into the stuff in random.? I came up with
> this.? It may not be helpful since you may be learning about loops and
> randint, but this works:
>
> import random
>
> #LIST
> words = ["one", "two", "three", "four", "five", "six", "seven",
> ??????????????????? "eight", "four", "nine", "ten", "eleven"]
>
> word_set = list(set(words))??? # this removes duplicates since set contains
> one of each value.? Then convert back to a list
> print "original words: ", words??? # just wanted to see my original list
> print "removed duplicates with set:", word_set?? # this shows that I don't
> have duplicates
> random.shuffle(word_set)? # this shuffles the list in place.? Now word_set
> is shuffled (randomized!)
> print "randomized: ", word_set?? # see!
>
>

Hey Joel,

I've not done sets yet.

I guess part of the problem when you're a noob like myself is that
there is always going to be a more efficient way of doing something
(but just that I haven't learnt it yet) :-D

Looking at the original code again, I think that the wordslen =
len(words) bit might have to stay in the loop. The value of wordslen
changes at each iteration of the loop you see.

The reason I'm removing one entry from the words list at each
iteration is to ensure that all of the words are included in randwords
(although again, this probably isn't the best way to do it!).

I think I may need to add something like if words[index] not in
randwords: to make sure that the word isn't already in the list I want
to jumble up' and print perhaps?

Thanks

Chris

Chris

From lists at justuber.com  Fri Sep 10 00:39:30 2010
From: lists at justuber.com (lists)
Date: Thu, 9 Sep 2010 23:39:30 +0100
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>
Message-ID: <AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>

>>> Several small and not so small points:
>>>
>>> 1. you assign wordslen each pass through your loop.? While it doesn't
>>> matter in a small loop, it wastes time on the order of the size of your
>>> list.? Instead move wordslen = len(...? above your while loop.? Any time you
>>> put code in a loop that doesn't change in each iteration, you should move it
>>> out of the loop.
>>>
>>> 2. since you only use chosenword once in your loop, you could remove
>>> chosenword = words[index] line and replace chosenword in the append(... with
>>> words[index]
>>>
>>> 3. your list doesn't contain any duplicate words.? Since? your program is
>>> supposed to catch this, you should add a duplicate to see if it works.
>>> (No!)
>>>
>>> 4. I think your line del words[index] is supposed to help out with item 3
>>> but it doesn't.? It just removes the word you just used selected.
>>>
>>> 5. And finally, I think you want to print
>>>
>>> Just minor points.? nice job -- getting there
>>> --
>>> Joel Goldstick

This seems to work Joel,

It removes the extraneous assignment of chosenword and gets rid of
duplicate entries from the word list.

while words: #has entries in it
    wordslen = len(words) #get the length of the list
    index = random.randint(0, wordslen -1) #get a random index
    if words[index] not in randwords: #as long as the word isn't
already in the new list
        randwords.append(words[index]) #append the random word to a new list
        del words[index] #del the word from the old list
    else:
        del words[index] #remove the duplicate word from the source list

From g.nius.ck at gmail.com  Fri Sep 10 03:55:05 2010
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 9 Sep 2010 21:55:05 -0400
Subject: [Tutor] Mutable Properties
In-Reply-To: <201009092242.13164.steve@pearwood.info>
References: <4C87F94D.9030601@gmail.com>
	<201009090722.53624.steve@pearwood.info>
	<4C883CD0.2070002@gmail.com>
	<201009092242.13164.steve@pearwood.info>
Message-ID: <AANLkTi=Yr+yZaYDvbGhAbpDSbJpgNnSuxxUk9vp+_uOg@mail.gmail.com>

sorry, accidentally hit reply instead of reply to all

On Thu, Sep 9, 2010 at 8:42 AM, Steven D'Aprano <steve at pearwood.info> wrote:

> Please don't reply privately to me unless you mean to ask me something
> private or personal.
>
> If you send your reply to the tutor list, I'll respond there.
>
>
> Regards,
>
>
>
> --
> Steven D'Aprano
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/ac5469ca/attachment.html>

From g.nius.ck at gmail.com  Fri Sep 10 03:59:08 2010
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 9 Sep 2010 21:59:08 -0400
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>
	<AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>
	<AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
Message-ID: <AANLkTik3ud_cyXRTtZ2x6e9sR642UH5hJqqzZdqCEr3X@mail.gmail.com>

forgot to send it to the list

On Thu, Sep 9, 2010 at 9:58 PM, Christopher King <g.nius.ck at gmail.com>wrote:

> you could try random.shuffle and save a lot of time, it takes a mutable
> sequence (like a list) and shuffles it
>
>
> On Thu, Sep 9, 2010 at 6:39 PM, lists <lists at justuber.com> wrote:
>
>> >>> Several small and not so small points:
>> >>>
>> >>> 1. you assign wordslen each pass through your loop.  While it doesn't
>> >>> matter in a small loop, it wastes time on the order of the size of
>> your
>> >>> list.  Instead move wordslen = len(...  above your while loop.  Any
>> time you
>> >>> put code in a loop that doesn't change in each iteration, you should
>> move it
>> >>> out of the loop.
>> >>>
>> >>> 2. since you only use chosenword once in your loop, you could remove
>> >>> chosenword = words[index] line and replace chosenword in the
>> append(... with
>> >>> words[index]
>> >>>
>> >>> 3. your list doesn't contain any duplicate words.  Since  your program
>> is
>> >>> supposed to catch this, you should add a duplicate to see if it works.
>> >>> (No!)
>> >>>
>> >>> 4. I think your line del words[index] is supposed to help out with
>> item 3
>> >>> but it doesn't.  It just removes the word you just used selected.
>> >>>
>> >>> 5. And finally, I think you want to print
>> >>>
>> >>> Just minor points.  nice job -- getting there
>> >>> --
>> >>> Joel Goldstick
>>
>> This seems to work Joel,
>>
>> It removes the extraneous assignment of chosenword and gets rid of
>> duplicate entries from the word list.
>>
>> while words: #has entries in it
>>    wordslen = len(words) #get the length of the list
>>    index = random.randint(0, wordslen -1) #get a random index
>>     if words[index] not in randwords: #as long as the word isn't
>> already in the new list
>>        randwords.append(words[index]) #append the random word to a new
>> list
>>         del words[index] #del the word from the old list
>>     else:
>>        del words[index] #remove the duplicate word from the source list
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100909/a9f5becd/attachment.html>

From fomcl at yahoo.com  Fri Sep 10 11:23:07 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 10 Sep 2010 02:23:07 -0700 (PDT)
Subject: [Tutor] design question
Message-ID: <445813.72562.qm@web110715.mail.gq1.yahoo.com>

Hi,

I've made a small data entry program where a picture of a hand-written, scanned 
form is shown next to several text entries. The design has been largely 'bottom 
up', although of course I started with a rough sketch. I started with the 
following classes: Menu (responsible for the widget creation), Autocomplete (a 
subclass of the tkinter text entry widget which I've found on the internet, I 
wanted to keep this intact), Convert (responsible for the conversion/cropping of 
the images, which is somewhat tedious) and Events (here's the pain spot: this 
has become a mixed bag). Originally, the Events class was supposed to contain 
all the commands behind the widgets, but it has slowly gotten more 
responsibilities. Notably, all methods that deal with reading/writing the data 
also live here. The program is about 500 lines of code now, including blanks.

I'd like to rewrite to entire program so that (1) all classes have just one 
responsibility (2) classes connect to as little other classes (so it becomes 
easy to e.g. change to another widget set). I'd love to hear some thoughts or 
advice on the new design from you (I hope my description wasn't too short). Is 
there a specific design pattern that could be used?

One specific, additional question: the program has a title bar that shows 
something like "processing file X (1 of 3; 33%)". My colleague suggested to use 
the Iterator pattern (gang of four) for this. Is this (a) overkill (b) a simple 
opportunity to apply this pattern? 


Thank you in advance for your advice!

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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/0d6bbd96/attachment.html>

From lists at justuber.com  Fri Sep 10 11:23:40 2010
From: lists at justuber.com (lists)
Date: Fri, 10 Sep 2010 10:23:40 +0100
Subject: [Tutor]  Random list exercise
In-Reply-To: <AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>
	<AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>
	<AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
	<AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
Message-ID: <AANLkTi=rngQugP7=pM0-GUNd--YtOK08LGL0EUP5i7r5@mail.gmail.com>

Ooops, I forgot to send to the list too!

---------- Forwarded message ----------
From: lists <lists at justuber.com>
Date: Fri, Sep 10, 2010 at 10:22 AM
Subject: Re: [Tutor] Random list exercise
To: Christopher King <g.nius.ck at gmail.com>


> you could try random.shuffle and save a lot of time, it takes a mutable
> sequence (like a list) and shuffles it

Hey there,

For the few exercises I've been doing, I think the author has been
attempting to make the reader do things 'the difficult way' so that
the reader understands how things work. Hopefully the next few
chapters will introduce me to doing things the easier way lol :-D

random.shuffle is cool though. I'm really impressed on the sheer
volume of functions that Python provides to make a programmer's life
easier!

Chris

From rwobben at hotmail.com  Fri Sep 10 13:14:45 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 10 Sep 2010 11:14:45 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <EEE4E5B1-1460-4550-B0D8-9C033EB95FD9@gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
	<201009100207.12024.steve@pearwood.info>
	<AANLkTinKk9h5u+M22Sc9A_bezkM4L44TAb5JkHR=pv-n@mail.gmail.com>
	<35308F2B-F3F8-4F86-B868-FD149FE5740A@gmail.com>
	<SNT118-W2524FC712327C4B5542BFFAE730@phx.gbl>
	<30609F44-EF1F-421A-AF56-066E60CEE3F1@gmail.com>
	<SNT118-W9C039AA6DAE8FCDBCA222AE730@phx.gbl>,
	<EEE4E5B1-1460-4550-B0D8-9C033EB95FD9@gmail.com>
Message-ID: <SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>


Hello , 

 

So my book teach me the wrong principle.

But can everything programmed on Eafp.

 

If you dont know if something is a list, a tuple or a string, you can get a lot of nested try except think.

 

Roelof


 


Subject: Re: [Tutor] recursive problem
From: rabidpoobear at gmail.com
Date: Thu, 9 Sep 2010 15:32:44 -0500
To: rwobben at hotmail.com


No you misunderstood me. Eafp is a python design principle. lbyl is common in older languages. Please reply all in the future so our discussion takes place on the list instead of just between us.

Sent from my iPhone

On Sep 9, 2010, at 1:31 PM, Roelof Wobben <rwobben at hotmail.com> wrote:




Oke, 
 
So If I understand you right LBYL is more the python way.
Wierd that the book im following (Thinking like a computer scientist) is more EAFP.
 
Roelof

 


Subject: Re: [Tutor] recursive problem
From: rabidpoobear at gmail.com
Date: Thu, 9 Sep 2010 13:24:06 -0500
To: rwobben at hotmail.com


It's easier to ask for forgiveness than permission vs. Look before you leap. An example of LBYL would be checking the type of a variable before you use it. EAFP would be just using the variable, and if something goes wrong, handle the exception. It's a core tenet of python software design and goes hand in hand w/ duck typing and other principles.

Sent from my iPhone

On Sep 9, 2010, at 1:16 PM, Roelof Wobben <rwobben at hotmail.com> wrote:





 Sorry. 
 
Im also new to Python and programming.
 
What does EAFP and LBYL mean ?
 
Roelof
 


From: rabidpoobear at gmail.com
Date: Thu, 9 Sep 2010 12:59:46 -0500
To: joel.goldstick at gmail.com
CC: tutor at python.org
Subject: Re: [Tutor] recursive problem


Nope Joel, that's what I meant. Remember EAFP over LBYL! I'm not sure the best way to make sure the object is iterable though.

Sent from my iPhone

On Sep 9, 2010, at 11:41 AM, Joel Goldstick <joel.goldstick at gmail.com> wrote:







On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano <steve at pearwood.info> wrote:




On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
> On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart
>
> <rabidpoobear at gmail.com>wrote:
> > Shouldn't there be a way to do this without type checking? Duck
> > typing!
> >
> > Your post got me thinking.  Maybe better to test if the object can
> > return
> an iter method.  If it throws an error, then look at its value.  If
> it doesn't, then its a list or a tuple


It's not clear what you mean by "return an iter method". Taken
literally, that would imply the object is a function. I think you
mean "*has* an iter method" -- except that's not right either:

>>> [].iter
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'iter'


Perhaps you mean an object which can be passed to iter(), but lots of
objects can do that, not just lists and tuples:

>>> iter("not a list or tuple")
<str_iterator object at 0xb7d3520c>
>>> iter({1: None, 2: "a", 4: 5})
<dict_keyiterator object at 0xb7d3420c>


I was googling, and found that if an object has an __iter__ method it will return it.  If not it will throw an error.  You are right about more than lists and tuples being iterable.  But, in this thread, it was brought up that checking type may not be pythonic.  If you wanted to use the same code to find values in a nested list of any objects, you could dispense with the type checking and just see if it is iterable.


I'm new to python.  Am I off base? 



--
Steven D'Aprano



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


-- 
Joel Goldstick



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

_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/4da368c4/attachment.html>

From ewaldhorn at gmail.com  Fri Sep 10 13:30:23 2010
From: ewaldhorn at gmail.com (Ewald Horn)
Date: Fri, 10 Sep 2010 13:30:23 +0200
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<B68A8D6E-0056-42E2-A618-E2CCFAFC7B99@gmail.com>
	<AANLkTin1uw5FGaep3j5BBt7y=Tp=v00AfutmX9RSJpeF@mail.gmail.com>
	<201009100207.12024.steve@pearwood.info>
	<AANLkTinKk9h5u+M22Sc9A_bezkM4L44TAb5JkHR=pv-n@mail.gmail.com>
	<35308F2B-F3F8-4F86-B868-FD149FE5740A@gmail.com>
	<SNT118-W2524FC712327C4B5542BFFAE730@phx.gbl>
	<30609F44-EF1F-421A-AF56-066E60CEE3F1@gmail.com>
	<SNT118-W9C039AA6DAE8FCDBCA222AE730@phx.gbl>
	<EEE4E5B1-1460-4550-B0D8-9C033EB95FD9@gmail.com>
	<SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>
Message-ID: <AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>

On 10 September 2010 13:14, Roelof Wobben <rwobben at hotmail.com> wrote:

>  Hello ,
>
> So my book teach me the wrong principle.
> But can everything programmed on Eafp.
>
> If you dont know if something is a list, a tuple or a string, you can get a
> lot of nested try except think.
>
> Roelof
>

Hi Roelof,

I don't think EAFP is wrong, and neither is LBYL, it all depends on the
circumstances. Python makes it easy to use EAFP, especially compared to
languages like Java or C++. While EAFP is great, it's not always the best
way to proceed. Sometimes you want programs to be very robust and secure,
this is where LBYL comes in - it is quite often used in online transaction
processing and other areas where absolute certainty is more important than
any other consideration.

EAFP tends to use less code and is faster to use, while LBYL principles
makes your program more bulletproof.  For now, I suggest you stick to the
EAFP principles, it's not wrong and it's one of the reasons I like Python so
much - it allows you to focus on solving a particular problem and does not
expect you to jump through a number of hoops to just get something simple
done.

And, before you ask, you can indeed follow LBYL principles in Python if you
want to, but you only have to do it if you really want to, not because the
compiler forces you to.

Consider these principles to be tools in your toolkit, sometimes you need a
hammer, other times a saw, each tool (principle) is suited to a particular
situation. Go ahead and try both, you will find one works better in a given
scenario than the other.

Regards
Ewald
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/c5397524/attachment.html>

From michael at trollope.org  Fri Sep 10 15:09:00 2010
From: michael at trollope.org (Michael Powe)
Date: Fri, 10 Sep 2010 09:09:00 -0400
Subject: [Tutor] Exception Handling and Stack traces
Message-ID: <20100910130900.GA3330@cecilia>

Hello,

I can't work out how to suppress stacktrace printing when exceptions
are thrown.

I want the thrown exception to pass a message on the console, just
like Java does when I catch an exception and print e.getMessage().

I tried some of the examples of controlling traceback through the
traceback module.

I have to admit, this is one of the cases where I wonder why it has to
be made so bloody complicated.  The other day, I read an article by
Guido in which he was proposing to remove 'map' and 'filter' from the
language because he though the developer shouldn't have to think too
much about using them.  But the exception handling is so non-intuitive
that the time saved from not having to think about using 'map' is
spent instead on trying to figure out how to promote a message to the
commandline when a method fails.

It seems that exceptions automatically are thrown up, so even if I put
a 'try/except' clause in a method; when that method fails, the
exception will still be thrown up to the top of the call chain.  So,
there seems to be no reason whatever to catch an exception in any
method except the top caller (i.e., 'main').  

Example:

def getData(auth) :
	# create opener with auth headers here
	try :
		data = opener.open(url)
	except urllib2.URLError("Badly formed URL") :
		formatted_lines = traceback.format_exc().splitlines()
		print formatted_lines[0]
		print formatted_lines[-1]
		sys.exit(1)
	return data

This method is called by another method, printOutput(), which
processes the return data (XML from web service).

That method is called in main:

[printOutput(w) for w in weeks]

All I want to see is that if the exception is thrown in getData(), the
message is printed to stdout and the script exits.  Instead, I get the
stacktrace printed back down from main, I don't get the exception
handled in getData (i.e., the error message and exit).

Now, I'm sure somebody is going to explain to me why it's so
unreasonable to think that I ought to be able to get an error message
from e.getMessage() and a stacktrace from e.printStacktrace() and that
I ought to be able to choose between the two.  Because, it seems that
python is determined that I should have a stacktrace whether I want
one or not.

Sorry, I'm more than a little annoyed because even the example of
using the traceback module from the python docs does not provide the
handling that it is supposed to; and I really think this level of
complexity for handling exceptions cleanly is just unwarranted.  I
need to be able to give this script to someone who will want to be
able to read the error output without having to be a Python programmer
experienced in reading stack traces.  e.g. a "Badly formed URL"
message that tells them they set up the parameters for connecting to
the web service incorrectly.

Hopefully, you can get past the rant and help me solve this problem.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA

"The secret to strong security: less reliance on secrets."
-- Whitfield Diffie
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/d5297987/attachment-0001.pgp>

From knacktus at googlemail.com  Fri Sep 10 15:38:13 2010
From: knacktus at googlemail.com (Knacktus)
Date: Fri, 10 Sep 2010 15:38:13 +0200
Subject: [Tutor] design question
In-Reply-To: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
Message-ID: <4C8A34C5.8060100@googlemail.com>

Am 10.09.2010 11:23, schrieb Albert-Jan Roskam:
> Hi,
>
> I've made a small data entry program where a picture of a hand-written,
> scanned form is shown next to several text entries. The design has been
> largely 'bottom up', although of course I started with a rough sketch. I
> started with the following classes: Menu (responsible for the widget
> creation), Autocomplete (a subclass of the tkinter text entry widget
> which I've found on the internet, I wanted to keep this intact), Convert
> (responsible for the conversion/cropping of the images, which is
> somewhat tedious) and Events (here's the pain spot: this has become a
> mixed bag). Originally, the Events class was supposed to contain all the
> commands behind the widgets, but it has slowly gotten more
> responsibilities. Notably, all methods that deal with reading/writing
> the data also live here. The program is about 500 lines of code now,
> including blanks.
It's difficult to judge from the outside. It sounds to me like a good 
idea to create separate classes or modules for reading and writing.
>
> I'd like to rewrite to entire program so that (1) all classes have just
> one responsibility (2) classes connect to as little other classes (so it
> becomes easy to e.g. change to another widget set). I'd love to hear
> some thoughts or advice on the new design from you (I hope my
> description wasn't too short). Is there a specific design pattern that
> could be used?
>
> One specific, additional question: the program has a title bar that
> shows something like "processing file X (1 of 3; 33%)". My colleague
> suggested to use the Iterator pattern (gang of four) for this. Is this
> (a) overkill (b) a simple opportunity to apply this pattern?
For what exactly do you want to use the pattern?
The iterator pattern is easy to implement in Python. And the usage of 
iterators is even more easy (you can use them in loops without calling 
the next() method explicitly). Lists among others are iterator types. 
You can create your own with generator functions or of course implement 
the iterator-protocol. See here:

http://docs.python.org/library/stdtypes.html#iterator-types

Generally iterator types and generators are great features of Python. 
For a more concrete advice you'd need to explain a bit further what you 
need to do.

HTH

Jan

From evert.rol at gmail.com  Fri Sep 10 15:50:57 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 10 Sep 2010 15:50:57 +0200
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <20100910130900.GA3330@cecilia>
References: <20100910130900.GA3330@cecilia>
Message-ID: <A7E1BD04-B285-4A6D-B00B-B37D1E06E2E9@gmail.com>

> I can't work out how to suppress stacktrace printing when exceptions
> are thrown.
> 
> I want the thrown exception to pass a message on the console, just
> like Java does when I catch an exception and print e.getMessage().
> 
> I tried some of the examples of controlling traceback through the
> traceback module.
> 
> I have to admit, this is one of the cases where I wonder why it has to
> be made so bloody complicated.  The other day, I read an article by
> Guido in which he was proposing to remove 'map' and 'filter' from the
> language because he though the developer shouldn't have to think too
> much about using them.  But the exception handling is so non-intuitive
> that the time saved from not having to think about using 'map' is
> spent instead on trying to figure out how to promote a message to the
> commandline when a method fails.
> 
> It seems that exceptions automatically are thrown up, so even if I put
> a 'try/except' clause in a method; when that method fails, the
> exception will still be thrown up to the top of the call chain.  So,
> there seems to be no reason whatever to catch an exception in any
> method except the top caller (i.e., 'main').  
> 
> Example:
> 
> def getData(auth) :
> 	# create opener with auth headers here
> 	try :
> 		data = opener.open(url)
> 	except urllib2.URLError("Badly formed URL") :
> 		formatted_lines = traceback.format_exc().splitlines()
> 		print formatted_lines[0]
> 		print formatted_lines[-1]
> 		sys.exit(1)
> 	return data

This is a bit of a guess, but as far as I know, you can catch exceptions like that. 
Try:

try:
    data = opener.open(url)
except urllib2.URLError as msg:
    print msg
    sys.exit(1)

If you're using an older version of Python, you'll need:

try:
    data = opener.open(url)
except urllib2.URLError, msg:
    print msg
    sys.exit(1)

In your example, you are *creating* an exception (but doing nothing with it; I have no idea what happens if you have a line like "except <Exception instance>". Perhaps it tries to compare one on one with that instance, but if it compares by id, that will not work).
In this way, you're not catching the exception. So, it will be pass your except clause, and just do what it always does: print the whole exception's traceback. Which is probably what you're seeing.


  Evert



> 
> This method is called by another method, printOutput(), which
> processes the return data (XML from web service).
> 
> That method is called in main:
> 
> [printOutput(w) for w in weeks]
> 
> All I want to see is that if the exception is thrown in getData(), the
> message is printed to stdout and the script exits.  Instead, I get the
> stacktrace printed back down from main, I don't get the exception
> handled in getData (i.e., the error message and exit).
> 
> Now, I'm sure somebody is going to explain to me why it's so
> unreasonable to think that I ought to be able to get an error message
> from e.getMessage() and a stacktrace from e.printStacktrace() and that
> I ought to be able to choose between the two.  Because, it seems that
> python is determined that I should have a stacktrace whether I want
> one or not.
> 
> Sorry, I'm more than a little annoyed because even the example of
> using the traceback module from the python docs does not provide the
> handling that it is supposed to; and I really think this level of
> complexity for handling exceptions cleanly is just unwarranted.  I
> need to be able to give this script to someone who will want to be
> able to read the error output without having to be a Python programmer
> experienced in reading stack traces.  e.g. a "Badly formed URL"
> message that tells them they set up the parameters for connecting to
> the web service incorrectly.
> 
> Hopefully, you can get past the rant and help me solve this problem.
> 
> Thanks.
> 
> mp
> 
> -- 
> Michael Powe		michael at trollope.org		Naugatuck CT USA
> 
> "The secret to strong security: less reliance on secrets."
> -- Whitfield Diffie
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From __peter__ at web.de  Fri Sep 10 15:56:51 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 10 Sep 2010 15:56:51 +0200
Subject: [Tutor] Exception Handling and Stack traces
References: <20100910130900.GA3330@cecilia>
Message-ID: <i6ddd0$e32$1@dough.gmane.org>

Michael Powe wrote:

> I can't work out how to suppress stacktrace printing when exceptions
> are thrown.

[snip rant]

It might have been a good idea to read a tutorial like

http://docs.python.org/tutorial/errors.html#handling-exceptions

or ask before you got annoyed enough to write that rant ;)

To catch an exception you have to put the class into the except clause, not 
an instance. Basic example, using 2.6 syntax:

WRONG:

>>> try:
...     1/0
... except ZeroDivisionError("whatever"):
...     print "caught"
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

CORRECT:

>>> try:
...     1/0
... except ZeroDivisionError as e:
...     print "caught", e
...
caught integer division or modulo by zero

Peter


From fomcl at yahoo.com  Fri Sep 10 16:11:37 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 10 Sep 2010 07:11:37 -0700 (PDT)
Subject: [Tutor] design question
In-Reply-To: <4C8A34C5.8060100@googlemail.com>
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
	<4C8A34C5.8060100@googlemail.com>
Message-ID: <763847.51052.qm@web110703.mail.gq1.yahoo.com>

Hi Jan,

Here's a screendump of my program: http://nl.tinypic.com/r/2qtlojc/7 . This 
might make my description a little bit clearer. The beautiful sunset will in 
reality be a dull, handwritten form. ;-)

Regarding the iterator pattern, I was referring to this: 
http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#iterators-and-generators

Inside my program I have to keep a list of all the image files that are 
scheduled for data entry. The main purpose is to be able to read in the image 
files one by one. Another one of the purposes of this list is to show some 
information on the title bar. Currently, my program only has a 'next' button and 
the fact that implementing a 'previous' button is causing problems suggests to 
me that I have to look for a more fundamentally better solution.

 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: Knacktus <knacktus at googlemail.com>
To: tutor at python.org
Sent: Fri, September 10, 2010 3:38:13 PM
Subject: Re: [Tutor] design question

Am 10.09.2010 11:23, schrieb Albert-Jan Roskam:
> Hi,
> 
> I've made a small data entry program where a picture of a hand-written,
> scanned form is shown next to several text entries. The design has been
> largely 'bottom up', although of course I started with a rough sketch. I
> started with the following classes: Menu (responsible for the widget
> creation), Autocomplete (a subclass of the tkinter text entry widget
> which I've found on the internet, I wanted to keep this intact), Convert
> (responsible for the conversion/cropping of the images, which is
> somewhat tedious) and Events (here's the pain spot: this has become a
> mixed bag). Originally, the Events class was supposed to contain all the
> commands behind the widgets, but it has slowly gotten more
> responsibilities. Notably, all methods that deal with reading/writing
> the data also live here. The program is about 500 lines of code now,
> including blanks.
It's difficult to judge from the outside. It sounds to me like a good idea to 
create separate classes or modules for reading and writing.
> 
> I'd like to rewrite to entire program so that (1) all classes have just
> one responsibility (2) classes connect to as little other classes (so it
> becomes easy to e.g. change to another widget set). I'd love to hear
> some thoughts or advice on the new design from you (I hope my
> description wasn't too short). Is there a specific design pattern that
> could be used?
> 
> One specific, additional question: the program has a title bar that
> shows something like "processing file X (1 of 3; 33%)". My colleague
> suggested to use the Iterator pattern (gang of four) for this. Is this
> (a) overkill (b) a simple opportunity to apply this pattern?
For what exactly do you want to use the pattern?
The iterator pattern is easy to implement in Python. And the usage of iterators 
is even more easy (you can use them in loops without calling the next() method 
explicitly). Lists among others are iterator types. You can create your own with 
generator functions or of course implement the iterator-protocol. See here:

http://docs.python.org/library/stdtypes.html#iterator-types

Generally iterator types and generators are great features of Python. For a more 
concrete advice you'd need to explain a bit further what you need to do.

HTH

Jan
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/a767555b/attachment-0001.html>

From michael at trollope.org  Fri Sep 10 16:28:36 2010
From: michael at trollope.org (Michael Powe)
Date: Fri, 10 Sep 2010 10:28:36 -0400
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <i6ddd0$e32$1@dough.gmane.org>
References: <20100910130900.GA3330@cecilia> <i6ddd0$e32$1@dough.gmane.org>
Message-ID: <20100910142836.GB3330@cecilia>

On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote:
> Michael Powe wrote:
> 
> > I can't work out how to suppress stacktrace printing when exceptions
> > are thrown.
> 
> [snip rant]
> 
> It might have been a good idea to read a tutorial like
> 
> http://docs.python.org/tutorial/errors.html#handling-exceptions
 
> or ask before you got annoyed enough to write that rant ;)

Hello,

Thanks for the reply.  Stupid me, I just read a half dozen articles on
the web about python exception handling, including some at
docs.python.  At no point is the 'as' clause discussed as being
required.

Note that in section 8.3 of that article, the statement is made that
if the exception matches the the exception type in the following
format, the statements within the except clause are executed.

except URLError :
	   # do something

That in fact, seems to me to be incorrect.  It is not my experience
(e.g., print statements are not executed in the example I gave and the
sys.exit() is not called).

I'll follow up on your suggestions.  I appreciate the help.

Thanks.

mp
 
> To catch an exception you have to put the class into the except clause, not 
> an instance. Basic example, using 2.6 syntax:
> 
> WRONG:
> 
> >>> try:
> ...     1/0
> ... except ZeroDivisionError("whatever"):
> ...     print "caught"
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
> ZeroDivisionError: integer division or modulo by zero
> 
> CORRECT:
> 
> >>> try:
> ...     1/0
> ... except ZeroDivisionError as e:
> ...     print "caught", e
> ...
> caught integer division or modulo by zero
> 
> Peter
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"...we built a new continent in cyberspace where we could go live and be
free. And the nice thing is that, because we built it, we didn't have
to steal it from aboriginal peoples. It was completely empty, and we
invite everyone to live there with us. No immigration restrictions.
There's room for everyone in the world. Come live in the free world
and be free. That's our idea."  -- Richard Stallman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/a8331a0f/attachment.pgp>

From evert.rol at gmail.com  Fri Sep 10 16:33:04 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 10 Sep 2010 16:33:04 +0200
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <20100910142836.GB3330@cecilia>
References: <20100910130900.GA3330@cecilia> <i6ddd0$e32$1@dough.gmane.org>
	<20100910142836.GB3330@cecilia>
Message-ID: <AAAAB8B4-4593-4AC5-8509-BABC7488D8D5@gmail.com>

>>> I can't work out how to suppress stacktrace printing when exceptions
>>> are thrown.
>> 
>> [snip rant]
>> 
>> It might have been a good idea to read a tutorial like
>> 
>> http://docs.python.org/tutorial/errors.html#handling-exceptions
> 
>> or ask before you got annoyed enough to write that rant ;)
> 
> Hello,
> 
> Thanks for the reply.  Stupid me, I just read a half dozen articles on
> the web about python exception handling, including some at
> docs.python.  At no point is the 'as' clause discussed as being
> required.

Because 'as' didn't use to be there. That is more recent.

The real difference is between using an 'instance' and a class in the except clause. You used the former, you need the latter.


> Note that in section 8.3 of that article, the statement is made that
> if the exception matches the the exception type in the following
> format, the statements within the except clause are executed.
> 
> except URLError :
> 	   # do something
> 
> That in fact, seems to me to be incorrect.  It is not my experience
> (e.g., print statements are not executed in the example I gave and the
> sys.exit() is not called).

Have you tried this? In your example, you have 

	except urllib2.URLError("Badly formed URL") :

which is quite a different thing; and I'm quite sure it's like that in the docs.
If you have tried the above ("except URLError"), I'm curious about an example.

Cheers,

  Evert



> 
> I'll follow up on your suggestions.  I appreciate the help.
> 
> Thanks.
> 
> mp
> 
>> To catch an exception you have to put the class into the except clause, not 
>> an instance. Basic example, using 2.6 syntax:
>> 
>> WRONG:
>> 
>>>>> try:
>> ...     1/0
>> ... except ZeroDivisionError("whatever"):
>> ...     print "caught"
>> ...
>> Traceback (most recent call last):
>>  File "<stdin>", line 2, in <module>
>> ZeroDivisionError: integer division or modulo by zero
>> 
>> CORRECT:
>> 
>>>>> try:
>> ...     1/0
>> ... except ZeroDivisionError as e:
>> ...     print "caught", e
>> ...
>> caught integer division or modulo by zero
>> 
>> Peter


From michael at trollope.org  Fri Sep 10 16:34:44 2010
From: michael at trollope.org (Michael Powe)
Date: Fri, 10 Sep 2010 10:34:44 -0400
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <A7E1BD04-B285-4A6D-B00B-B37D1E06E2E9@gmail.com>
References: <20100910130900.GA3330@cecilia>
	<A7E1BD04-B285-4A6D-B00B-B37D1E06E2E9@gmail.com>
Message-ID: <20100910143444.GC3330@cecilia>

On Fri, Sep 10, 2010 at 03:50:57PM +0200, Evert Rol wrote:

> This is a bit of a guess, but as far as I know, you can catch exceptions like that. 
> Try:
 
> try:
>     data = opener.open(url)
> except urllib2.URLError as msg:
>     print msg
>     sys.exit(1)
 
> If you're using an older version of Python, you'll need:
> 
> try:
>     data = opener.open(url)
> except urllib2.URLError, msg:
>     print msg
>     sys.exit(1)
 
> In your example, you are *creating* an exception (but doing nothing
> with it; I have no idea what happens if you have a line like "except
> <Exception instance>". Perhaps it tries to compare one on one with
> that instance, but if it compares by id, that will not work).  In
> this way, you're not catching the exception. So, it will be pass
> your except clause, and just do what it always does: print the whole
> exception's traceback. Which is probably what you're seeing.

Hello,

Thanks for the reply.  As I indicated in the other message I just
wrote, the format I used is one I took straight from the
documentation. Of course, there may be assumptions in the documented
examples that I am not aware of.

It looks like you and Peter have pulled me out of the ditch and for
that I am grateful.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
It could have been an organically based disturbance of the brain --
perhaps a tumor or a metabolic deficiency -- but after a thorough
neurological exam it was determined that Byron was simply a jerk.  
-- Jeff Jahnke, runner-up, Bulwer-Lytton contest
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/8eaf8d0f/attachment.pgp>

From huyslogic at gmail.com  Fri Sep 10 16:35:48 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Fri, 10 Sep 2010 10:35:48 -0400
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
Message-ID: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>

I am reading the decorator section within Expert Python Programming and I am
very confused in the first example, of a method that was done before
decorators. It reads:

class WhatFor(object):
    def it(cls):
        print 'work with %s' % cls
    it = classmethod(it)
    def uncommon():
        print 'I could be a global function'
    uncommon = staticmethod(uncommon)

But I can't seem to understand the above. Under what circumstance would
staticmethod be useful? I am just deriving that you are not passing self.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/c7ae38a3/attachment.html>

From __peter__ at web.de  Fri Sep 10 16:42:35 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 10 Sep 2010 16:42:35 +0200
Subject: [Tutor] Exception Handling and Stack traces
References: <20100910130900.GA3330@cecilia> <i6ddd0$e32$1@dough.gmane.org>
	<20100910142836.GB3330@cecilia>
Message-ID: <i6dg2o$rin$1@dough.gmane.org>

Michael Powe wrote:

> On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote:
>> Michael Powe wrote:
>> 
>> > I can't work out how to suppress stacktrace printing when exceptions
>> > are thrown.
>> 
>> [snip rant]
>> 
>> It might have been a good idea to read a tutorial like
>> 
>> http://docs.python.org/tutorial/errors.html#handling-exceptions
>  
>> or ask before you got annoyed enough to write that rant ;)
> 
> Hello,
> 
> Thanks for the reply.  Stupid me, I just read a half dozen articles on
> the web about python exception handling, including some at
> docs.python.  At no point is the 'as' clause discussed as being
> required.

>> WRONG:
>> 
>> >>> try:
>> ...     1/0
>> ... except ZeroDivisionError("whatever"):
>> ...     print "caught"
>> ...
>> Traceback (most recent call last):
>>   File "<stdin>", line 2, in <module>
>> ZeroDivisionError: integer division or modulo by zero
>> 
>> CORRECT:
>> 
>> >>> try:
>> ...     1/0
>> ... except ZeroDivisionError as e:
>> ...     print "caught", e
>> ...
>> caught integer division or modulo by zero

> Note that in section 8.3 of that article, the statement is made that
> if the exception matches the the exception type in the following
> format, the statements within the except clause are executed.
> 
> except URLError :
> # do something
> 
> That in fact, seems to me to be incorrect.  It is not my experience
> (e.g., print statements are not executed in the example I gave and the
> sys.exit() is not called).

Sorry, the as-clause is *not* necessary. The relevant difference between the 
correct and the wrong approach is that you must not instantiate the 
exception:

WRONG:

>>> try:
...     1/0
... except ZeroDivisionError("whatever"):
...     print "caught"
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

CORRECT:

>>> try:
...     1/0
... except ZeroDivisionError:
...     print "caught"
...
caught

I just put in the as-clause to show an easy way to print the exception. I 
did not anticipate that it would obscure the message.

Peter


From rwobben at hotmail.com  Fri Sep 10 17:13:20 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 10 Sep 2010 15:13:20 +0000
Subject: [Tutor] exceptions problem
Message-ID: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>


Hello, 

 

I have this problem :

 

Write a function named readposint that prompts the user for a positive integer and then checks the input to confirm that it meets the requirements. A sample session might look like this:

>>> num = readposint()
Please enter a positive integer: yes
yes is not a positive integer.  Try again.
Please enter a positive integer: 3.14
3.14 is not a positive integer.  Try again.
Please enter a positive integer: -6
-6 is not a positive integer.  Try again.
Please enter a positive integer: 42
>>> num
42
>>> num2 = readposint("Now enter another one: ")
Now enter another one: 31
>>> num2
31
>>>
Now I thought this would work:def readposint(): 
    x = raw_input("Please enter a positive integer :")
    try:
        x = int(x) and x > 0 
    except:
        print x , "is not a positive integer.  Try again."
        return False
    return Truey = readposint()
print y
while y == False:
    readposint()
print "You have entered : ", yBut the x > 10 is never checked.Must I use two try except now ? Roelof    		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/16513e5a/attachment-0001.html>

From davea at ieee.org  Fri Sep 10 17:52:32 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 10 Sep 2010 11:52:32 -0400
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
Message-ID: <4C8A5440.9090303@ieee.org>

  On 2:59 PM, Roelof Wobben wrote:
> <snip>
> Now I thought this would work:def readposint():
>      x = raw_input("Please enter a positive integer :")
>      try:
>          x = int(x) and x>  0
>      except:
>          print x , "is not a positive integer.  Try again."
>          return False
>      return Truey = readposint()
> prin<snip>

There's no exception triggered by the valid expression
    x = int(x) and x > 0

when x is negative.  That's a perfectly valid expression, as long as the 
string is valid numeric.  It doesn't set x to  what you might expect, 
though - try it with x = "3".

Leave the try statement around the int(x), which can indeed throw an 
exception.  But you need a separate  if statement to test whether x is 
greater than zero.

DaveA


From fal at libero.it  Fri Sep 10 18:07:13 2010
From: fal at libero.it (Francesco Loffredo)
Date: Fri, 10 Sep 2010 18:07:13 +0200
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
Message-ID: <4C8A57B1.9000302@libero.it>

Oops, I sent this to Roelof... Ok, I must amend it anyway...

On 10/09/2010 17.13, Roelof Wobben wrote:
> ...
> def readposint():
>         x = raw_input("Please enter a positive integer :")
>         try:
>                 x = int(x) and x>  0
>         except:
>                 print x , "is not a positive integer.    Try again."
>                 return False
>         return True
>
> y = readposint()
> print y
> while y == False:
>         readposint()
> print "You have entered : ", y
>
> But the x>  10 is never checked.
>
> Must I use two try except now ?
Your first problem has nothing to do with exception handling.
The culprit is Line 4:
>                 x = int(x) and x>  0
I suppose that you forgot a second equal sign between x and int(x). If 
it were
>                x == int(x) and x > 0
it would have worked as expected. But this would not trigger any 
exception, if X is a number. So let's add one:
 >                if not (x == int(x) and x > 0): raise(ValueError)

Hope that helps,

> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3124 -  Data di rilascio: 09/09/10 08:34:00

From rwobben at hotmail.com  Fri Sep 10 18:12:08 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 10 Sep 2010 16:12:08 +0000
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8A57B1.9000302@libero.it>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>,
	<4C8A57B1.9000302@libero.it>
Message-ID: <SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>



 
Date: Fri, 10 Sep 2010 18:07:13 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] exceptions problem

Oops, I sent this to Roelof... Ok, I must amend it anyway...
 
On 10/09/2010 17.13, Roelof Wobben wrote:
> ...
> def readposint():
>         x = raw_input("Please enter a positive integer :")
>         try:
>                 x = int(x) and x>  0
>         except:
>                 print x , "is not a positive integer.    Try again."
>                 return False
>         return True
>
> y = readposint()
> print y
> while y == False:
>         readposint()
> print "You have entered : ", y
>
> But the x>  10 is never checked.
>
> Must I use two try except now ?
Your first problem has nothing to do with exception handling.
The culprit is Line 4:
>                 x = int(x) and x>  0
I suppose that you forgot a second equal sign between x and int(x). If 
it were
>                x == int(x) and x > 0
it would have worked as expected. But this would not trigger any 
exception, if X is a number. So let's add one:
 >                if not (x == int(x) and x > 0): raise(ValueError)
 
Hope that helps,
 
> Roelof
FrancescoHello Francesco,I change it to this :def readposint(): 
    x = raw_input("Please enter a positive integer :")
    try:
       if not (x == int(x) and x < 0): raise(ValueError) 
    except:
        print x , "is not a positive integer.  Try again."
        return False
    return Truey = readposint()
print y
while y == False:
    readposint()
print "You have entered : ", yBut -9 and 2 are both true.Roelof
 
_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/4c6c5121/attachment.html>

From rwobben at hotmail.com  Fri Sep 10 19:58:36 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 10 Sep 2010 17:58:36 +0000
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>, ,
	<4C8A57B1.9000302@libero.it>,
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>
Message-ID: <SNT118-W51F59E79B400B308FD52ABAE740@phx.gbl>



 


From: rwobben at hotmail.com
To: tutor at python.org
Date: Fri, 10 Sep 2010 16:12:08 +0000
Subject: Re: [Tutor] exceptions problem





 
Date: Fri, 10 Sep 2010 18:07:13 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] exceptions problem

Oops, I sent this to Roelof... Ok, I must amend it anyway...
 
On 10/09/2010 17.13, Roelof Wobben wrote:
> ...
> def readposint():
>         x = raw_input("Please enter a positive integer :")
>         try:
>                 x = int(x) and x>  0
>         except:
>                 print x , "is not a positive integer.    Try again."
>                 return False
>         return True
>
> y = readposint()
> print y
> while y == False:
>         readposint()
> print "You have entered : ", y
>
> But the x>  10 is never checked.
>
> Must I use two try except now ?
Your first problem has nothing to do with exception handling.
The culprit is Line 4:
>                 x = int(x) and x>  0
I suppose that you forgot a second equal sign between x and int(x). If 
it were
>                x == int(x) and x > 0
it would have worked as expected. But this would not trigger any 
exception, if X is a number. So let's add one:
 >                if not (x == int(x) and x > 0): raise(ValueError)
 
Hope that helps,
 
> Roelof
FrancescoHello Francesco,I change it to this :def readposint(): 
    x = raw_input("Please enter a positive integer :")
    try:
       if not (x == int(x) and x < 0): raise(ValueError) 
    except:
        print x , "is not a positive integer.  Try again."
        return False
    return Truey = readposint()
print y
while y == False:
    readposint()
print "You have entered : ", yBut -9 and 2 are both true.RoelofBecause I want to understand why this happens I wrote this test programm :def readposint(): 
    x = raw_input("Please enter a positive integer :")
    print x 
    if x == int(x) :
        print "01-True"
    else:
        print "01-False"
        print int(x)
    if x > 0 :
        print "02-True"
    else:
        print "02-False"
    return y = readposint()
print y
while y == False:
    readposint()
print "You have entered : ", y But I see wierd output :When x = 3 I get this output :Please enter a positive integer :3301-False302-TrueNoneYou have entered : None
 

That's wierd. 3 is a integer so 01 must be True and 3 is bigger then 0 so that one must be false.

 

Can someone explain me why this happens ?

 

Roelof

 


 
_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 
_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/16506211/attachment.html>

From ranceh at gmail.com  Fri Sep 10 20:00:15 2010
From: ranceh at gmail.com (Rance Hall)
Date: Fri, 10 Sep 2010 13:00:15 -0500
Subject: [Tutor] hashlib problems
Message-ID: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>

Im wanting to use the builtin hashlib functions to encrypt passwords
before storing them in a database.

According to documentation on the python.org site it should be as simple as

import hashlib

hashname = hashlib.sha234  (or whatever other hash method you want
like md5 or whatever)

hashname.update(b"test")  the b is for byte since the documentation
states that hashlib does not accept strings

hashname.hexdigest() or digest() will give you the hash encrypted
value.  (hexdigest will encode the output in hex for use in email and
string db storage)


My problem is that hashname.update results in a:

AttributeError:  'built_in_function_or_method' object has no attribute 'update'

I get this error in python 2 and python 3

I get it on multiple operating systems, so I dont understand whats
going wrong.  Either there is a bug in the module hashlib, or the
module changed and the docs don't keep up.

Either way I can not encrypt the password of my project for new users
till I figure out whats going on.

Your help much appreciated.

Rance

From goodhei8 at gmail.com  Fri Sep 10 20:09:20 2010
From: goodhei8 at gmail.com (goodhei8 at gmail.com)
Date: Fri, 10 Sep 2010 14:09:20 -0400
Subject: [Tutor] smtp connection problem --- socket error 10061
Message-ID: <4C8A7450.9020406@gmail.com>

  I could not connect with gmail smtp server in Vista 32( worked ok in 
XP 32). Both vista and xp have same anti-virus software.

>>> smtplib.SMTP("smtp.gmail.com",587)

Traceback (most recent call last):
   File "<pyshell#1>", line 1, in <module>
     smtplib.SMTP("smtp.gmail.com",587)
   File "C:\Program Files\Python25\lib\smtplib.py", line 244, in __init__
     (code, msg) = self.connect(host, port)
   File "C:\Program Files\Python25\lib\smtplib.py", line 310, in connect
     raise socket.error, msg
error: (10061, 'Connection refused')

I am using IPV4 for my vista wireless connection. No improvement with 
firewall disabled.

Any one has this problem? any solution?

Thanks a lot.

Jack


From fal at libero.it  Fri Sep 10 20:23:09 2010
From: fal at libero.it (Francesco Loffredo)
Date: Fri, 10 Sep 2010 20:23:09 +0200
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>,
	<4C8A57B1.9000302@libero.it>
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>
Message-ID: <4C8A778D.4080601@libero.it>

On 10/09/2010 18.12, Roelof Wobben wrote:
> ...
> def readposint():
>         x = raw_input("Please enter a positive integer :")
>         try:
>               if not (x == int(x) and x<  0): raise(ValueError)
>         except:
>                 print x , "is not a positive integer.    Try again."
>                 return False
>         return True
>
> y = readposint()
> print y
> while y == False:
>         readposint()
> print "You have entered : ", y
>
> But -9 and 2 are both true.
My fault, I didn't notice that after raw_input, whatever you enter is a 
STRING, not an integer! So, without any exception thrown, the comparison
x == int(x) is always False. Let's make it better:
    if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)


Then, if the input value x is indeed a positive integer, you should 
return x, not True or False. Try returning -1 if the exception is 
thrown, in line 7, and returning x in line 8. Then, you should change 
also line 12... ok, here's to you:

def readposint():
     x = raw_input("Please enter a positive integer :")
     try:
         if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
     except:
         print x , "is not a positive integer.    Try again."
         return -1
     return x

y = readposint()
print y
while y == -1:
     readposint()
print "You have entered : ", y

>
> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3124 -  Data di rilascio: 09/09/10 08:34:00

From __peter__ at web.de  Fri Sep 10 20:40:27 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 10 Sep 2010 20:40:27 +0200
Subject: [Tutor] hashlib problems
References: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
Message-ID: <i6du0n$rg7$1@dough.gmane.org>

Rance Hall wrote:

> Im wanting to use the builtin hashlib functions to encrypt passwords
> before storing them in a database.
> 
> According to documentation on the python.org site it should be as simple
> as
> 
> import hashlib
> 
> hashname = hashlib.sha234  (or whatever other hash method you want
> like md5 or whatever)
> 
> hashname.update(b"test")  the b is for byte since the documentation
> states that hashlib does not accept strings
> 
> hashname.hexdigest() or digest() will give you the hash encrypted
> value.  (hexdigest will encode the output in hex for use in email and
> string db storage)
> 
> 
> My problem is that hashname.update results in a:
> 
> AttributeError:  'built_in_function_or_method' object has no attribute
> 'update'
> 
> I get this error in python 2 and python 3
> 
> I get it on multiple operating systems, so I dont understand whats
> going wrong.  Either there is a bug in the module hashlib, or the
> module changed and the docs don't keep up.

Neither
 
> Either way I can not encrypt the password of my project for new users
> till I figure out whats going on.

hashlib.sha224 is indeed a function:

>>> f = hashlib.sha224
>>> f
<built-in function openssl_sha224>

You have to invoke it to get a hash object:

>>> g = f()
>>> g
<sha224 HASH object @ 0x229dbf0>

Complete working example:

>>> import hashlib
>>> h = hashlib.sha224() # note the parens
>>> h.update(b"test")
>>> h.hexdigest()
'90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809'

Look here for another one:

http://docs.python.org/dev/py3k/library/hashlib.html

Peter


From michael at trollope.org  Fri Sep 10 20:47:13 2010
From: michael at trollope.org (Michael Powe)
Date: Fri, 10 Sep 2010 14:47:13 -0400
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <i6dg2o$rin$1@dough.gmane.org>
References: <20100910130900.GA3330@cecilia> <i6ddd0$e32$1@dough.gmane.org>
	<20100910142836.GB3330@cecilia> <i6dg2o$rin$1@dough.gmane.org>
Message-ID: <20100910184713.GD3330@cecilia>

On Fri, Sep 10, 2010 at 04:42:35PM +0200, Peter Otten wrote:
> Michael Powe wrote:
 
> > On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote:
> >> Michael Powe wrote:

> >> > I can't work out how to suppress stacktrace printing when exceptions
> >> > are thrown.
 
> >> WRONG:
> >> 
> >> >>> try:
> >> ...     1/0
> >> ... except ZeroDivisionError("whatever"):
> >> ...     print "caught"
> >> ...
> >> Traceback (most recent call last):
> >>   File "<stdin>", line 2, in <module>
> >> ZeroDivisionError: integer division or modulo by zero
> >> 
> >> CORRECT:
> >> 
> >> >>> try:
> >> ...     1/0
> >> ... except ZeroDivisionError as e:
> >> ...     print "caught", e
> >> ...
> >> caught integer division or modulo by zero
 
> > Note that in section 8.3 of that article, the statement is made that
> > if the exception matches the the exception type in the following
> > format, the statements within the except clause are executed.
> > 
> > except URLError :
> > # do something
> > 
> > That in fact, seems to me to be incorrect.  It is not my experience
> > (e.g., print statements are not executed in the example I gave and the
> > sys.exit() is not called).
 
> Sorry, the as-clause is *not* necessary. The relevant difference between the 
> correct and the wrong approach is that you must not instantiate the 
> exception:
 
> WRONG:
> 
> >>> try:
> ...     1/0
> ... except ZeroDivisionError("whatever"):
> ...     print "caught"
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
> ZeroDivisionError: integer division or modulo by zero
 
> CORRECT:
> 
> >>> try:
> ...     1/0
> ... except ZeroDivisionError:
> ...     print "caught"
> ...
> caught
> 
> I just put in the as-clause to show an easy way to print the exception. I 
> did not anticipate that it would obscure the message.

Hello,

No problem, I am working on getting this sorted out.  The
documentation seems to be written as reminder for people who already
know how this stuff works, rather than as a clear explanation for
anybody working with it.

Eventually, I arrived at a workable conclusion by wrapping only the
call in main and using your suggested 'as' clause.  This successfully
suppresses the traceback and gives a useable error message.  Although,
in the case of URLError, 'getaddrinfo failed' may not actually mean
much to the end user, it'll have to do.

I don't like the fact that I cannot locate my thrown exception at the
point of throwing -- i.e., I don't necessarily mind catching the
exception in main but I would like to be able to print out exactly
where the exception occurred.  This is more useful when
troubleshooting. However, an entire stacktrace is unacceptably
verbose.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA


It's easier to fight for one's principles than to live up to them.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/a98cc8e4/attachment.pgp>

From rwobben at hotmail.com  Fri Sep 10 20:48:05 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 10 Sep 2010 18:48:05 +0000
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8A778D.4080601@libero.it>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>, ,
	<4C8A57B1.9000302@libero.it>,
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>,
	<4C8A778D.4080601@libero.it>
Message-ID: <SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>



 
Date: Fri, 10 Sep 2010 20:23:09 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] exceptions problem

On 10/09/2010 18.12, Roelof Wobben wrote:
> ...
> def readposint():
>         x = raw_input("Please enter a positive integer :")
>         try:
>               if not (x == int(x) and x<  0): raise(ValueError)
>         except:
>                 print x , "is not a positive integer.    Try again."
>                 return False
>         return True
>
> y = readposint()
> print y
> while y == False:
>         readposint()
> print "You have entered : ", y
>
> But -9 and 2 are both true.
My fault, I didn't notice that after raw_input, whatever you enter is a 
STRING, not an integer! So, without any exception thrown, the comparison
x == int(x) is always False. Let's make it better:
    if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
 
 
Then, if the input value x is indeed a positive integer, you should 
return x, not True or False. Try returning -1 if the exception is 
thrown, in line 7, and returning x in line 8. Then, you should change 
also line 12... ok, here's to you:
 
def readposint():
     x = raw_input("Please enter a positive integer :")
     try:
         if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
     except:
         print x , "is not a positive integer.    Try again."
         return -1
     return x
 
y = readposint()
print y
while y == -1:
     readposint()
print "You have entered : ", y
 
>
> Roelof
FrancescoThank you.I never thought that you can use a float and a integer to look if the number is a integer.Roelof
 
_______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/aba5ddac/attachment.html>

From michael at trollope.org  Fri Sep 10 21:10:13 2010
From: michael at trollope.org (Michael Powe)
Date: Fri, 10 Sep 2010 15:10:13 -0400
Subject: [Tutor] Trapping HTTP Authentication Failure
Message-ID: <20100910191013.GE3330@cecilia>

Hello,

My script to call a web service authenticates.  I would like to be
able to trap an exception if the authentication fails.  The script
loops over a list of dates and I don't want it to retry for every
element in the list.  This could take a long time and be very annoying
when, after the long wait, a stacktrace spews out of the last attempt.
The assumption is that if it fails, it is not a transient network or
some other issue but that the credentials themselves are faulty.

Now, the authentication header is sent with the initial request, so it
does not look to me like the standard process of request, get a 401
and then re-request with credentials is relevant.  However, clearly
the opener issues a number of retries after the initial failure.

But, I don't see a mechanism in urllib2 for taking notice of a failure
and acting on it.

Can somebody point me toward a solution?

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA

"And I'd be a Libertarian, if they weren't all a bunch of tax-dodging
professional whiners." -- Berke Breathed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/ca068022/attachment-0001.pgp>

From davea at ieee.org  Fri Sep 10 21:10:20 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 10 Sep 2010 15:10:20 -0400
Subject: [Tutor] hashlib problems
In-Reply-To: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
References: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
Message-ID: <4C8A829C.5020301@ieee.org>



On 2:59 PM, Rance Hall wrote:
> Im wanting to use the builtin hashlib functions to encrypt passwords
> before storing them in a database.
>
> According to documentation on the python.org site it should be as simple as
>
> import hashlib
>
> hashname = hashlib.sha234  (or whatever other hash method you want
> like md5 or whatever)
>
You forgot the parentheses.  You also picked one that doesn't exist, so 
switch to sha256() or sha384().
> hashname.update(b"test")  the b is for byte since the documentation
> states that hashlib does not accept strings
>
> hashname.hexdigest() or digest() will give you the hash encrypted
> value.  (hexdigest will encode the output in hex for use in email and
> string db storage)
>
>
> My problem is that hashname.update results in a:
>
> AttributeError:  'built_in_function_or_method' object has no attribute 'update'
>
> I get this error in python 2 and python 3
>
> I get it on multiple operating systems, so I dont understand whats
> going wrong.  Either there is a bug in the module hashlib, or the
> module changed and the docs don't keep up.
>
> Either way I can not encrypt the password of my project for new users
> till I figure out whats going on.
>
> Your help much appreciated.
>
> Rance
>

From g.nius.ck at gmail.com  Fri Sep 10 21:19:43 2010
From: g.nius.ck at gmail.com (Chris King)
Date: Fri, 10 Sep 2010 15:19:43 -0400
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>	<AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>	<AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
	<AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
Message-ID: <4C8A84CF.7000004@gmail.com>

  On 9/10/2010 5:22 AM, lists wrote:
>> you could try random.shuffle and save a lot of time, it takes a mutable
>> sequence (like a list) and shuffles it
> Hey there,
>
> For the few exercises I've been doing, I think the author has been
> attempting to make the reader do things 'the difficult way' so that
> the reader understands how things work. Hopefully the next few
> chapters will introduce me to doing things the easier way lol :-D
>
> random.shuffle is cool though. I'm really impressed on the sheer
> volume of functions that Python provides to make a programmer's life
> easier!
>
> Chris
that is pythons biggest feature. they even have modules they will talk 
and translate sound to a string, as easily as raw_input and print. You 
have to download it thou.

From g.nius.ck at gmail.com  Fri Sep 10 21:22:19 2010
From: g.nius.ck at gmail.com (Chris King)
Date: Fri, 10 Sep 2010 15:22:19 -0400
Subject: [Tutor] Random list exercise
In-Reply-To: <AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>	<AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>	<AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
	<AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
Message-ID: <4C8A856B.20405@gmail.com>

  On 9/10/2010 5:22 AM, lists wrote:
>> you could try random.shuffle and save a lot of time, it takes a mutable
>> sequence (like a list) and shuffles it
> Hey there,
>
> For the few exercises I've been doing, I think the author has been
> attempting to make the reader do things 'the difficult way' so that
> the reader understands how things work. Hopefully the next few
> chapters will introduce me to doing things the easier way lol :-D
>
> random.shuffle is cool though. I'm really impressed on the sheer
> volume of functions that Python provides to make a programmer's life
> easier!
>
> Chris
also when you reply, make sure you reply to all the tutors, not just me

From lists at justuber.com  Fri Sep 10 21:56:07 2010
From: lists at justuber.com (lists)
Date: Fri, 10 Sep 2010 20:56:07 +0100
Subject: [Tutor] Random list exercise
In-Reply-To: <4C8A856B.20405@gmail.com>
References: <AANLkTimBV-huwV+mZJBrE2pP3Zk6GHwywWpz=wN0M5r+@mail.gmail.com>
	<AANLkTinqj8a+-RfmQWadCM6+HiT-ApbuBRSrNmh04CTx@mail.gmail.com>
	<AANLkTinQmvjP4VGUVv4gJNFE4r5WsS8uzNyieuoDHteP@mail.gmail.com>
	<AANLkTikAwNjOOtCjefdcUTTT4dp1--rBFWqxFDhNrv-h@mail.gmail.com>
	<AANLkTikF97X0Bj_OMpqiApVNseotp6QfWSze76=1XcWS@mail.gmail.com>
	<AANLkTimkCcZ8h9Yy4dDcy1NPSdqRFLLJsUM+mu9q3-TL@mail.gmail.com>
	<AANLkTin96AAG3j3wBYXbnr5Lf7vUNnhdWFmQUg2U+44Q@mail.gmail.com>
	<4C8A856B.20405@gmail.com>
Message-ID: <AANLkTimFX88uL-C1Hxgy=3hQD-JiGVSG5Brf7JX9djdn@mail.gmail.com>

> ?On 9/10/2010 5:22 AM, lists wrote:
>>>
>>> you could try random.shuffle and save a lot of time, it takes a mutable
>>> sequence (like a list) and shuffles it
>>
>> Hey there,
>>
>> For the few exercises I've been doing, I think the author has been
>> attempting to make the reader do things 'the difficult way' so that
>> the reader understands how things work. Hopefully the next few
>> chapters will introduce me to doing things the easier way lol :-D
>>
>> random.shuffle is cool though. I'm really impressed on the sheer
>> volume of functions that Python provides to make a programmer's life
>> easier!
>>
>> Chris
>
> also when you reply, make sure you reply to all the tutors, not just me
>

Hi Chris,

I forgot like you did earlier ;-) I did then take the email and send
it to the list so everyone got it.

Chris

From rabidpoobear at gmail.com  Fri Sep 10 22:12:57 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 10 Sep 2010 15:12:57 -0500
Subject: [Tutor] hashlib problems
In-Reply-To: <4C8A829C.5020301@ieee.org>
References: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
	<4C8A829C.5020301@ieee.org>
Message-ID: <D2CC526C-E8CA-4473-8BB9-0F5047A65AE8@gmail.com>

In general, you shouldn't even hint at the possibility of there being a bug in the code unless you have test cases and a patch handy. Especially something as widely used as hashlib. It  gives An air of arrogance about your post, whether you intend it or not.
I think your issue got resolved already, just thought it might help to have a bit of an explication about hacker culture.
See Eric raymond's how to ask questions the smart way for much more information.  Sad as it is, your initial impressions will actually govern how likely you are to get replies.

Food for thought!

Sent from my iPhone

On Sep 10, 2010, at 2:10 PM, Dave Angel <davea at ieee.org> wrote:

> 
> 
> On 2:59 PM, Rance Hall wrote:
>> Im wanting to use the builtin hashlib functions to encrypt passwords
>> before storing them in a database.
>> 
>> According to documentation on the python.org site it should be as simple as
>> 
>> import hashlib
>> 
>> hashname = hashlib.sha234  (or whatever other hash method you want
>> like md5 or whatever)
>> 
> You forgot the parentheses.  You also picked one that doesn't exist, so switch to sha256() or sha384().
>> hashname.update(b"test")  the b is for byte since the documentation
>> states that hashlib does not accept strings
>> 
>> hashname.hexdigest() or digest() will give you the hash encrypted
>> value.  (hexdigest will encode the output in hex for use in email and
>> string db storage)
>> 
>> 
>> My problem is that hashname.update results in a:
>> 
>> AttributeError:  'built_in_function_or_method' object has no attribute 'update'
>> 
>> I get this error in python 2 and python 3
>> 
>> I get it on multiple operating systems, so I dont understand whats
>> going wrong.  Either there is a bug in the module hashlib, or the
>> module changed and the docs don't keep up.
>> 
>> Either way I can not encrypt the password of my project for new users
>> till I figure out whats going on.
>> 
>> Your help much appreciated.
>> 
>> Rance
>> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From ranceh at gmail.com  Fri Sep 10 22:54:39 2010
From: ranceh at gmail.com (Rance Hall)
Date: Fri, 10 Sep 2010 15:54:39 -0500
Subject: [Tutor] hashlib problems
In-Reply-To: <D2CC526C-E8CA-4473-8BB9-0F5047A65AE8@gmail.com>
References: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
	<4C8A829C.5020301@ieee.org>
	<D2CC526C-E8CA-4473-8BB9-0F5047A65AE8@gmail.com>
Message-ID: <AANLkTin1Z7=hOhtomjc_mHmxMDo8Wbjav_tUYeYZM28T@mail.gmail.com>

On Fri, Sep 10, 2010 at 3:12 PM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:
> In general, you shouldn't even hint at the possibility of there being a bug in the code unless you have test cases and a patch handy. Especially something as widely used as hashlib. It ?gives An air of arrogance about your post, whether you intend it or not.
> I think your issue got resolved already, just thought it might help to have a bit of an explication about hacker culture.
> See Eric raymond's how to ask questions the smart way for much more information. ?Sad as it is, your initial impressions will actually govern how likely you are to get replies.
>
> Food for thought!

Luke and the rest of the list:

I know it can be perceived as arrogant to suggest a bug and not have
at least some effort behind the statement.  Given the response of the
missing parentheses I can certainly understand why you would think
that about some new comer to the list.

What you didn't know (and what I didn't say because it wasn't relative
to the question) was what I had done on my own to figure it out.  You
need to know that I'm also mildly dyslexic and sometimes miss or
transpose things when I read them.  Going back and re-reading the
documentation again but this time knowing what to look for, I can
indeed see that I missed the "()"s.  It turns out I missed them in
several places.

But reading and re-reading that same document over the course of two
days did not reveal the problem.  I was as confident as I could be
that I was reading the documentation correctly and was following
proper syntax.

I will apologize for the tone and using the word "bug" without
sufficient evidence, and I will be more thorough in the future.

Once I get past a few basic questions I hope that my contributions to
the list can overcome this little hiccup.

Rance

From ranceh at gmail.com  Fri Sep 10 23:36:39 2010
From: ranceh at gmail.com (Rance Hall)
Date: Fri, 10 Sep 2010 16:36:39 -0500
Subject: [Tutor] changing list index start
Message-ID: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>

I'm using the following function style I found on the net to create
menus for a command line python script:

def mainmenu():
    # the main menu
    todolist()
    mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
Items','Employee','Exit']
    mainmenucalls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
todomenu, empmenu, quit]
    for i,option in enumerate(mainmenuoptions):
        print('%s. %s' % (i, option))
    mainchoice = int(input('\nYour Choice? '))
    clearscreen(osname)
    mainmenucalls[mainchoice]()
    return

It works well, but the first item is the list is item 0.  This is
normal in most computing situations, but because this index is part of
the output It would be nice if the first item in the list is item 1.

php provided a way to change this, but I can find no documentation
that says python can do this as well.

I'm sure that python can do this, but I'm unable to find a definitive
answer with google.

Would someone please enlighten me?

From rabidpoobear at gmail.com  Sat Sep 11 00:06:14 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 10 Sep 2010 17:06:14 -0500
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
Message-ID: <A393C268-D4CA-47D4-B959-4D4C3B0A48C8@gmail.com>

Yeah, just add 1 to it.  When printing just do index+1 and when inputting the user's choice, subtract 1 and use it as the array index.

Sent from my iPhone

On Sep 10, 2010, at 4:36 PM, Rance Hall <ranceh at gmail.com> wrote:

> I'm using the following function style I found on the net to create
> menus for a command line python script:
> 
> def mainmenu():
>    # the main menu
>    todolist()
>    mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
> Items','Employee','Exit']
>    mainmenucalls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
> todomenu, empmenu, quit]
>    for i,option in enumerate(mainmenuoptions):
>        print('%s. %s' % (i, option))
>    mainchoice = int(input('\nYour Choice? '))
>    clearscreen(osname)
>    mainmenucalls[mainchoice]()
>    return
> 
> It works well, but the first item is the list is item 0.  This is
> normal in most computing situations, but because this index is part of
> the output It would be nice if the first item in the list is item 1.
> 
> php provided a way to change this, but I can find no documentation
> that says python can do this as well.
> 
> I'm sure that python can do this, but I'm unable to find a definitive
> answer with google.
> 
> Would someone please enlighten me?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From lie.1296 at gmail.com  Sat Sep 11 01:14:57 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 11 Sep 2010 09:14:57 +1000
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
Message-ID: <i6ee5h$rnu$1@dough.gmane.org>

On 09/11/10 07:36, Rance Hall wrote:
> I'm using the following function style I found on the net to create
> menus for a command line python script:
> 
<snip>
> It works well, but the first item is the list is item 0.  This is
> normal in most computing situations, but because this index is part of
> the output It would be nice if the first item in the list is item 1.

In most cases in Python, you would almost never need to reference the
list's index directly since python makes it easy to use iterators;
however in your particular case, which is a valid exception, enumerate()
takes an optional second argument `start` which defines the number that
enumerate start to count with, i.e. you can do:

for i, option in enumerate(mainmenuoptions, 1):
    print('%s. %s' % (i, option))

> php provided a way to change this, but I can find no documentation
> that says python can do this as well.


From evert.rol at gmail.com  Sat Sep 11 01:28:26 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 11 Sep 2010 01:28:26 +0200
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <20100910191013.GE3330@cecilia>
References: <20100910191013.GE3330@cecilia>
Message-ID: <AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>

> My script to call a web service authenticates.  

Sorry, but where is the (full) script? I missed an attachment or (preferably) a link.


> I would like to be
> able to trap an exception if the authentication fails.  The script
> loops over a list of dates and I don't want it to retry for every
> element in the list.  This could take a long time and be very annoying
> when, after the long wait, a stacktrace spews out of the last attempt.
> The assumption is that if it fails, it is not a transient network or
> some other issue but that the credentials themselves are faulty.
> 
> Now, the authentication header is sent with the initial request, so it
> does not look to me like the standard process of request, get a 401
> and then re-request with credentials is relevant.  However, clearly
> the opener issues a number of retries after the initial failure.
> 
> But, I don't see a mechanism in urllib2 for taking notice of a failure
> and acting on it.
> 
> Can somebody point me toward a solution?
> 
> Thanks.
> 
> mp


From evert.rol at gmail.com  Sat Sep 11 01:39:50 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 11 Sep 2010 01:39:50 +0200
Subject: [Tutor] smtp connection problem --- socket error 10061
In-Reply-To: <4C8A7450.9020406@gmail.com>
References: <4C8A7450.9020406@gmail.com>
Message-ID: <B27387E5-DCA4-4DEA-BDF5-55A1C1DC011B@gmail.com>

> I could not connect with gmail smtp server in Vista 32( worked ok in XP 32). Both vista and xp have same anti-virus software.
> 
>>>> smtplib.SMTP("smtp.gmail.com",587)
> 
> Traceback (most recent call last):
>  File "<pyshell#1>", line 1, in <module>
>    smtplib.SMTP("smtp.gmail.com",587)
>  File "C:\Program Files\Python25\lib\smtplib.py", line 244, in __init__
>    (code, msg) = self.connect(host, port)
>  File "C:\Program Files\Python25\lib\smtplib.py", line 310, in connect
>    raise socket.error, msg
> error: (10061, 'Connection refused')
> 
> I am using IPV4 for my vista wireless connection. No improvement with firewall disabled.
> 
> Any one has this problem? any solution?

Do things work when you use SSL or TLS (through SMTP_SSL or using starttls, respectively)? Perhaps Vista is more strict in checking for this when connecting through a secure port (465 for SSL, 587 for TLS).

It's just a very simple guess, because I have no access to any Windows system.



From bgailer at gmail.com  Sat Sep 11 01:56:41 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 10 Sep 2010 19:56:41 -0400
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>, ,
	<4C8A57B1.9000302@libero.it>,
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>,
	<4C8A778D.4080601@libero.it>
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
Message-ID: <4C8AC5B9.8070807@gmail.com>

  On 9/10/2010 2:48 PM, Roelof Wobben wrote:
>
>
> Date: Fri, 10 Sep 2010 20:23:09 +0200
> From: fal at libero.it
> To: tutor at python.org
> Subject: Re: [Tutor] exceptions problem
>
> On 10/09/2010 18.12, Roelof Wobben wrote:
> >  ...
> >  def readposint():
> >          x = raw_input("Please enter a positive integer :")
> >          try:
> >                if not (x == int(x) and x<   0): raise(ValueError)
> >          except:
> >                  print x , "is not a positive integer.    Try again."
> >                  return False
> >          return True
> >
> >  y = readposint()
> >  print y
> >  while y == False:
> >          readposint()
> >  print "You have entered : ", y
> >
> >  But -9 and 2 are both true.
> My fault, I didn't notice that after raw_input, whatever you enter is a
> STRING, not an integer! So, without any exception thrown, the comparison
> x == int(x) is always False. Let's make it better:
>      if (int(x)<0 or (float(x) - int(x)>  0)): raise(ValueError)
>
>
> Then, if the input value x is indeed a positive integer, you should
> return x, not True or False. Try returning -1 if the exception is
> thrown, in line 7, and returning x in line 8. Then, you should change
> also line 12... ok, here's to you:
>
> def readposint():
>       x = raw_input("Please enter a positive integer :")
>       try:
>           if (int(x)<0 or (float(x) - int(x)>  0)): raise(ValueError)
>       except:
>           print x , "is not a positive integer.    Try again."
>           return -1
>       return x
>
> y = readposint()
> print y
> while y == -1:
>       readposint()
> print "You have entered : ", y
>
> >
> >  Roelof
> Francesco
> Thank you.
> I never thought that you can use a float and a integer to look if the number is a integer.

You can't.


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100910/6ced123f/attachment-0001.html>

From goodhei8 at gmail.com  Sat Sep 11 03:57:42 2010
From: goodhei8 at gmail.com (goodhei8 at gmail.com)
Date: Fri, 10 Sep 2010 21:57:42 -0400
Subject: [Tutor] smtp connection problem --- socket error 10061
In-Reply-To: <B27387E5-DCA4-4DEA-BDF5-55A1C1DC011B@gmail.com>
References: <4C8A7450.9020406@gmail.com>
	<B27387E5-DCA4-4DEA-BDF5-55A1C1DC011B@gmail.com>
Message-ID: <4C8AE216.8070403@gmail.com>

  smtp_ssl does not work for python 2.5.

can not even connect. not mention about starttls.

On 2010/9/10 19:39, Evert Rol wrote:
> Do things work when you use SSL or TLS (through SMTP_SSL or using starttls, respectively)? Perhaps Vista is more strict in checking for this when connecting through a secure port (465 for SSL, 587 for TLS).
>
> It's just a very simple guess, because I have no access to any Windows system.
>
>
>

From steve at pearwood.info  Sat Sep 11 04:19:12 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 12:19:12 +1000
Subject: [Tutor] Python social network / cms components?
In-Reply-To: <AANLkTikzMH76=du0sQ-xPEu4U16FJyx9VPfv2tm=YBY9@mail.gmail.com>
References: <AANLkTikzMH76=du0sQ-xPEu4U16FJyx9VPfv2tm=YBY9@mail.gmail.com>
Message-ID: <201009111219.13039.steve@pearwood.info>

On Fri, 10 Sep 2010 05:34:49 am Igor Choromanski wrote:
> Hi,
>
> After much research, I've come up with a list of what I think might
> be the best way of putting together a Python based social
> network/cms, but have some questions about how some of these
> components fit together.

This does not sound like a question for the tutor list. All I can 
suggest is that if you're considering building a major project like a 
CMS or social network while still learning the language, you're looking 
at a world of pain! You should consider at least doing a tutorial or 
two first.

If you're already experienced with the language, enough that the basic 
concepts and syntax of Python programming no longer confuse you, then a 
CMS is still an ambitious project, but it's entirely doable with time 
and effort. However you should take this question to the main python 
list, at python-list at python.org or its Usenet mirror, comp.lang.python.

To answer some of your specific questions:


> 1. Google App Engine -- this is an attempt to cut to the chase as
> many pieces of the puzzle seem to be in place.
> Question: Am I limiting my options with this choice? 

Of course you are. *Every* choice limits your options. If you decide to 
build a web-app, that means you're not building a peer-to-peer desktop 
app. If you decide to simulate a desktop GUI in the browser, that means 
losing the ability to support people who want a fast, efficient, 
minimalist Javascript- and AJAX-free experience. And so on.


> 2. Python -- I considered 'drupal' at first, but in the end decided
> that being dependent on modules that may or
> may not exist tomorrow 

What makes you think that drupal is more likely to disappear than 
GoogleApps?


> + limitations of its templating system are a 
> no-no. Learning its API, too, would be useless elsewhere
> whereas Python seems like a swiss army knife of languages -- good for
> almost anything.
> Question: v.2.5.2 is required by GAE, but python.org recommends
> 2.5.5. Which do I install?

2.5 is not supported except *possibly* for security fixes, and probably 
not even those. Even 2.6 is now only "bug fixes only". For a major 
project, I wouldn't consider anything below 2.6, and possibly even 
2.7 -- by the time you're ready to release your first alpha version, 
2.7 should have received a couple of point releases and be well-tested 
and stable.

There are many other templating engines for Python-based web apps, such 
as CherryPy or Zope, and many more. Before building a huge project, 
you're probably better off at least trying to build a "Hello World" app 
with them so you're not *entirely* flying blind.



-- 
Steven D'Aprano

From rabidpoobear at gmail.com  Sat Sep 11 05:06:35 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Fri, 10 Sep 2010 22:06:35 -0500
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8AC5B9.8070807@gmail.com>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
	<4C8A57B1.9000302@libero.it>
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>
	<4C8A778D.4080601@libero.it>
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
	<4C8AC5B9.8070807@gmail.com>
Message-ID: <AANLkTikTaWBzKrg9C_jLyvzfXj9uxogw63c+3ygZQ_fQ@mail.gmail.com>

Roleof, do you think you could stop sending HTML messages and use
plaintext instead?  I usually skip over your posts because your font
is so small and hard to read that I don't even bother.
If you send plain-text messages (which is the norm on programming
mailing lists) then you leave it up to the e-mail client to render the
text.

Yes, I could turn off HTML on my end, but that is a pain and breaks
messages that I legitimately want to be HTML.

Thanks,
-Luke

On Fri, Sep 10, 2010 at 6:56 PM, bob gailer <bgailer at gmail.com> wrote:
> On 9/10/2010 2:48 PM, Roelof Wobben wrote:
>
>
> Date: Fri, 10 Sep 2010 20:23:09 +0200
> From: fal at libero.it
> To: tutor at python.org
> Subject: Re: [Tutor] exceptions problem
>
> On 10/09/2010 18.12, Roelof Wobben wrote:
>> ...
>> def readposint():
>>         x = raw_input("Please enter a positive integer :")
>>         try:
>>               if not (x == int(x) and x<  0): raise(ValueError)
>>         except:
>>                 print x , "is not a positive integer.    Try again."
>>                 return False
>>         return True
>>
>> y = readposint()
>> print y
>> while y == False:
>>         readposint()
>> print "You have entered : ", y
>>
>> But -9 and 2 are both true.
> My fault, I didn't notice that after raw_input, whatever you enter is a
> STRING, not an integer! So, without any exception thrown, the comparison
> x == int(x) is always False. Let's make it better:
>     if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
>
>
> Then, if the input value x is indeed a positive integer, you should
> return x, not True or False. Try returning -1 if the exception is
> thrown, in line 7, and returning x in line 8. Then, you should change
> also line 12... ok, here's to you:
>
> def readposint():
>      x = raw_input("Please enter a positive integer :")
>      try:
>          if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
>      except:
>          print x , "is not a positive integer.    Try again."
>          return -1
>      return x
>
> y = readposint()
> print y
> while y == -1:
>      readposint()
> print "You have entered : ", y
>
>>
>> Roelof
> Francesco
>
> Thank you.
>
> I never thought that you can use a float and a integer to look if the number
> is a integer.
>
> You can't.
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From knacktus at googlemail.com  Sat Sep 11 10:23:53 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sat, 11 Sep 2010 10:23:53 +0200
Subject: [Tutor] design question
In-Reply-To: <763847.51052.qm@web110703.mail.gq1.yahoo.com>
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
	<4C8A34C5.8060100@googlemail.com>
	<763847.51052.qm@web110703.mail.gq1.yahoo.com>
Message-ID: <4C8B3C99.10600@googlemail.com>

Am 10.09.2010 16:11, schrieb Albert-Jan Roskam:
> Hi Jan,
>
> Here's a screendump of my program: http://nl.tinypic.com/r/2qtlojc/7 .
> This might make my description a little bit clearer. The beautiful
> sunset will in reality be a dull, handwritten form. ;-)
>
> Regarding the iterator pattern, I was referring to this:
> http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#iterators-and-generators
> Inside my program I have to keep a list of all the image files that are
> scheduled for data entry. The main purpose is to be able to read in the
> image files one by one. Another one of the purposes of this list is to
> show some information on the title bar. Currently, my program only has a
> 'next' button and the fact that implementing a 'previous' button is
> causing problems suggests to me that I have to look for a more
> fundamentally better solution.
Sounds to me that the easiest solution would be to simply use a list to 
hold the images, a reference to the current image and your desired 
methods in a class.

class ImageStack(object):

     def __init__(self, images=None)
         self.images = images or []
         self.current_image = None

     def next_image(self):
         if self.current_image:
             current_index = self.images.index(self.current_image)
             try:
                 next_image = self.images[current_index + 1]
             except IndexError:
                 print "All images done" # or return the first one
         else:
             next_image = self.images[0]
         self.current_image = next_image
         return next_image

     def prev_image(self):
         if self.current_image:
             current_index = self.images.index(self.current_image)
             try:
                 prev_image = self.images[current_index - 1]
                 self.current_image = next_image
                 return next_image
             except IndexError:
                 print "There's no prev image"
         print "There's no current image"


You could also track the current_index instead of the current_image. 
That would make the class easier, but how to track the current image 
depends on what other methods you need.

HTH,

Jan

> Cheers!!
> Albert-Jan

From steve at pearwood.info  Sat Sep 11 10:40:17 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 18:40:17 +1000
Subject: [Tutor] design question
In-Reply-To: <763847.51052.qm@web110703.mail.gq1.yahoo.com>
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
	<4C8A34C5.8060100@googlemail.com>
	<763847.51052.qm@web110703.mail.gq1.yahoo.com>
Message-ID: <201009111840.18307.steve@pearwood.info>

On Sat, 11 Sep 2010 12:11:37 am Albert-Jan Roskam wrote:

> Inside my program I have to keep a list of all the image files that
> are scheduled for data entry. 

Sounds like you need to keep a list of all the image files that are 
scheduled for data entry then.


> The main purpose is to be able to read 
> in the image files one by one. Another one of the purposes of this
> list is to show some information on the title bar. 

No it isn't. You don't need a list of image files in order to show "some 
information" in the title bar (unless that information is the list of 
files). From your earlier post, you want to show:

filename 23 of 245 (9.4%)

or similar. For that, all you need is three pieces of information:

* the name of the current file
* the number of the current file
* the total number of files

You don't need all 245 files for that.

I'm being pedantic here. Obviously you need the list of files 
*somewhere*, and you need it for other reasons, but you don't *need* a 
list of 243 files in order to show the name of one of them!

You may decide that it is *convenient* to give the function which 
changes the title bar access to the entire list, but it's not a 
*requirement*. Think about alternatives: 

def change_titlebar(name, count, total):
    template = "%s %d of %d (%.1f %%)"
    percentage = count*100.0/total
    title = template % (name, count, total, percentage)
    do_magic_with(title)  # whatever it takes to change the title

It doesn't need the entire list.


> Currently, my 
> program only has a 'next' button and the fact that implementing a
> 'previous' button is causing problems suggests to me that I have to
> look for a more fundamentally better solution.

Sounds to me that you *don't* want the iterator pattern. The iterator 
pattern generally means that you step forward through each item. If you 
want to advance backwards or forwards, something with random access is 
probably better. That would probably mean a list.

Don't be too hung up about "design patterns". Most design patterns just 
exist to work around limitations of the language, lack of power, or 
slavish devotion to object oriented programming when the problem is 
crying out for a functional or procedural solution. Don't be afraid to 
write functions instead of classes -- there's no need for a 
TitlebarManipulator class just to change the titlebar.

My solution would be to keep *two* pieces of information:

* the list of filenames;
* the current position in that list

Set the current position to 0, and have the Next button add one to the 
position and refresh the page, and Prev subtract one and refresh the 
page. Obviously you need code to ensure that the position doesn't go 
out of bounds, code to save the data in the fields, and so forth. The 
page refresh code should do something like:

* given the current position, extract the filename to use;
* change the title bar;
* open and display the appropriate image;
* pre-populate any fields;
etc.
        
Good luck!


-- 
Steven D'Aprano

From knacktus at googlemail.com  Sat Sep 11 11:03:33 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sat, 11 Sep 2010 11:03:33 +0200
Subject: [Tutor] What Design Pattern for Document class (NOT URGENT)
In-Reply-To: <4C760D11.5090302@free.fr>
References: <4C760D11.5090302@free.fr>
Message-ID: <4C8B45E5.8070208@googlemail.com>

Hi Karim,

it's difficult to comment as to me the problem is not quite clear.
But I try ;-)

You have a complex xml and need to read different data types. For each 
type you have certain rules, how to extract them from the xml (docrules).

You could create a DocRule class, that do nothing but hold instructions 
of how to read and write the xml for each data, e.g. xpathes. For each 
data type you create an instance of that class.

Then, in your main xml Reader class you define a method, that accepts a 
doc rule instance as argument.

doc_rule_1 = DocRule("some_pattern")
doc_rule_2 = DocRule("another_pattern")

class Reader(object):

     def __init__(self, filename):
         ... # create the etree

     def get_data_by_doc_rule(self, doc_rule):
         ... # search the tree based on the doc_rule
         ... # you can use any type here if it has the correct mehtods

In your "get_data_by_doc_rule" method you can use any type for the 
doc_rule, that has corresponding attributes and methods ("duck typing"). 
So you have a lot of flexibility of how to create your doc_rules.

Is that what you're looking for?

Jan

From fal at libero.it  Sat Sep 11 11:04:21 2010
From: fal at libero.it (Francesco Loffredo)
Date: Sat, 11 Sep 2010 11:04:21 +0200
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8AC5B9.8070807@gmail.com>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>, ,
	<4C8A57B1.9000302@libero.it>,
	<SNT118-W76F5CBCBAE3C67FC3C036AE740@phx.gbl>,
	<4C8A778D.4080601@libero.it>	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
	<4C8AC5B9.8070807@gmail.com>
Message-ID: <4C8B4615.6020603@libero.it>

On 11/09/2010 1.56, bob gailer wrote:
>   On 9/10/2010 2:48 PM, Roelof Wobben wrote:
>>
>>
>> Date: Fri, 10 Sep 2010 20:23:09 +0200
>> From: fal at libero.it
>> To: tutor at python.org
>> Subject: Re: [Tutor] exceptions problem
>> ...
>> > ...
>> >  Roelof
>> Francesco
>> Thank you.
>> I never thought that you can use a float and a integer to look if the number is a integer.
>
> You can't.
How enlightening! A REAL Tutor advice...

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3126 -  Data di rilascio: 09/10/10 09:08:00

From michael at trollope.org  Sat Sep 11 11:58:21 2010
From: michael at trollope.org (Michael Powe)
Date: Sat, 11 Sep 2010 05:58:21 -0400
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
Message-ID: <20100911095821.GA2670@cecilia>

On Sat, Sep 11, 2010 at 01:28:26AM +0200, Evert Rol wrote:
> > My script to call a web service authenticates.  
 
> Sorry, but where is the (full) script? I missed an attachment or (preferably) a link.

Hello,

Sorry, the verb of the sentence is "authenticates," as in, "My script
... authenticates."

But I can show the authentication portion.

8<-------------- start -------------------->8

# Creates an authentication object with the credentials for a given URL
def createPasswordManager(headers) :
    passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passwordManager.add_password(None,overview_url,headers[0],headers[1])
    return passwordManager

# Creates an authentication handler for the authentication object created above
def createAuthenticationHandler(passwordManager) :
    authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
    return authenticationHandler

# Creates an opener that sets the credentials in the Request
def createOpener(authHandler) :
    return urllib2.build_opener(authHandler)
    

# Retrieves the data    
def getData(authHeaders) :
    opener = createOpener(createAuthenticationHandler(createPasswordManager(authHeaders)))
    data = opener.open(overview_url)
    return data
8<--------------- end ------------------------>8

So, to restate the question, how can I trap an exception in the cases
in which authentication fails? 

Right now, the whole script is complete and working (thanks for your
help with my other exception-handling question).  Except for the case
of bad credentials.  The use case is that the user misspells a
username or password or puts in a wrong account information.  Then, I
don't want them to sit for 10 minutes while the script makes 30 data
connections, retries and fails each time.

Thanks.

mp    

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and <growl>; let
him come out as I do, and <bark>. -- Samuel Johnson
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/a0a7adbf/attachment.pgp>

From steve at pearwood.info  Sat Sep 11 12:02:49 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 20:02:49 +1000
Subject: [Tutor] Exception Handling and Stack traces
In-Reply-To: <20100910184713.GD3330@cecilia>
References: <20100910130900.GA3330@cecilia> <i6dg2o$rin$1@dough.gmane.org>
	<20100910184713.GD3330@cecilia>
Message-ID: <201009112002.49535.steve@pearwood.info>

On Sat, 11 Sep 2010 04:47:13 am Michael Powe wrote:

> No problem, I am working on getting this sorted out.  The
> documentation seems to be written as reminder for people who already
> know how this stuff works, rather than as a clear explanation for
> anybody working with it.

That's because the job of documentation is to be documentation, not a 
tutorial.

Admittedly, sometimes it's hard to draw a line between the two, but you 
have to assume *some* knowledge of the reader -- imagine if every time 
you tried to document some piece of code, you had to start explaining 
what variables are.

In this case, the Fine Manual is plenty clear. The example in the 
tutorial shows:

try:
    ...
except ValueError:
    ...

http://docs.python.org/tutorial/errors.html#handling-exceptions


There's no need to add an error message to the ValueError:

# this does NOT work
except ValueError("I never know what message to expect"):

There's nothing in any of the documentation I've ever seen that suggests 
that catching an exception requires you to specify the exact error 
message. Since error messages are subject to change without warning, or 
translation into other languages, this wouldn't be practical even if it 
could work (which it doesn't).


It does require a bit more knowledge to decipher the main documentation:

http://docs.python.org/reference/compound_stmts.html#try
http://docs.python.org/reference/executionmodel.html#exceptions

but as I said, this is not a tutorial. They are written for 
non-beginners. If you need a tutorial, do the tutorial, and don't 
expect the documentation to be all things to all users.

Or read example code in the standard library. If you pick a random 
module and read it, you can expect to find exception handling. See what 
other coders do.


> Eventually, I arrived at a workable conclusion by wrapping only the
> call in main and using your suggested 'as' clause.

If you're focused on the 'as' clause part, you're still missing the 
point.


> This successfully 
> suppresses the traceback and gives a useable error message. 
> Although, in the case of URLError, 'getaddrinfo failed' may not
> actually mean much to the end user, it'll have to do.
>
> I don't like the fact that I cannot locate my thrown exception at the
> point of throwing

Of course you can.



> -- i.e., I don't necessarily mind catching the 
> exception in main but I would like to be able to print out exactly
> where the exception occurred.  This is more useful when
> troubleshooting. 

Err, that's exactly what the stacktrace is for -- it shows the execution 
chain that failed.

> However, an entire stacktrace is unacceptably verbose.

For who? You, the developer, or for an end user?

If you mean for an end user, I agree. Stack traces aren't written for 
them. 

If you mean for you, the developer, then I'm sorry, but I find that a 
bogus attitude. It's true that *most of the time* the only part of the 
stack trace that you (generic you) will look at is the final call, but 
there are many, many times when you need to see the entire call chain 
to determine what's going on.

Anyway, be glad this is Python. In a former life, I worked for a company 
that had just installed a SAP accounting application. One day the 
application crashed, and printed out a stack trace direct to the 
printer. It was over fifty pages of tightly-written 9pt font. 
Seriously.

We called the developers and asked what they wanted us to do with it, 
and they said to throw it out.


-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 11 12:13:11 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 20:13:11 +1000
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
Message-ID: <201009112013.11462.steve@pearwood.info>

On Sat, 11 Sep 2010 12:35:48 am Huy Ton That wrote:
> I am reading the decorator section within Expert Python Programming
> and I am very confused in the first example, of a method that was
> done before decorators. It reads:
>
> class WhatFor(object):
>     def it(cls):
>         print 'work with %s' % cls
>     it = classmethod(it)
>     def uncommon():
>         print 'I could be a global function'
>     uncommon = staticmethod(uncommon)
>
> But I can't seem to understand the above. Under what circumstance
> would staticmethod be useful? I am just deriving that you are not
> passing self.


They usually aren't, in Python, because if you think you want a 
staticmethod, you're usually better off making it an ordinary function. 
E.g. instead of this:


class Food(object):
    @staticmethod
    def spam(x):
        return "spam"
    def ham(self):
        return "%s is a processed meat-like substance" % self.spam()


it is often better to do this:


class Food(object):
    def ham(self):
        return "%s is a processed meat-like substance" % spam()

def spam(x):
    return "spam"



There are exceptions, but you can consider that staticmethod is rarely 
needed. 



-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 11 12:22:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 20:22:47 +1000
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8AC5B9.8070807@gmail.com>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
	<4C8AC5B9.8070807@gmail.com>
Message-ID: <201009112022.47844.steve@pearwood.info>

On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
> > I never thought that you can use a float and a integer to look if
> > the number is a integer.
>
> You can't.

What? Of course you can.

def is_integer(x):
    """Return True if x is an integer."""
    try:
        return 1.0*x == int(x)
    except (TypeError, ValueError):
        return False



And in use:

>>> is_integer("12")
False
>>> is_integer(2.3)
False
>>> is_integer(2.0)
True
>>> is_integer(2)
True


The multiplication by 1.0 is not actually needed, but it doesn't hurt.

[thinks more carefully...] Actually it does hurt:

>>> is_integer(Decimal(2))
False


So although you *can* use float and int to determine if a value is an 
integer, it's best to avoid the float.




-- 
Steven D'Aprano

From __peter__ at web.de  Sat Sep 11 12:56:11 2010
From: __peter__ at web.de (Peter Otten)
Date: Sat, 11 Sep 2010 12:56:11 +0200
Subject: [Tutor] exceptions problem
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
	<4C8AC5B9.8070807@gmail.com>
	<201009112022.47844.steve@pearwood.info>
Message-ID: <i6fn66$ejn$1@dough.gmane.org>

Steven D'Aprano wrote:

> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>> > I never thought that you can use a float and a integer to look if
>> > the number is a integer.
>>
>> You can't.
> 
> What? Of course you can.
> 
> def is_integer(x):
>     """Return True if x is an integer."""
>     try:
>         return 1.0*x == int(x)
>     except (TypeError, ValueError):
>         return False

> The multiplication by 1.0 is not actually needed, but it doesn't hurt.
> 
> [thinks more carefully...] Actually it does hurt:
> 
>>>> is_integer(Decimal(2))
> False

Another problem is the limited precision of floats:

>>> x = 10**22
>>> 1.0*x == x
True
>>> x *= 10
>>> 1.0*x == x
False
 
Peter


From fal at libero.it  Sat Sep 11 13:04:05 2010
From: fal at libero.it (Francesco Loffredo)
Date: Sat, 11 Sep 2010 13:04:05 +0200
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
Message-ID: <4C8B6225.1090003@libero.it>

On 10/09/2010 23.36, Rance Hall wrote:
> I'm using the following function style I found on the net to create
> menus for a command line python script:
>
> def mainmenu():
>      # the main menu
>      todolist()
>      mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
> Items','Employee','Exit']
>      mainmenucalls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
> todomenu, empmenu, quit]
>      for i,option in enumerate(mainmenuoptions):
>          print('%s. %s' % (i, option))
>      mainchoice = int(input('\nYour Choice? '))
>      clearscreen(osname)
>      mainmenucalls[mainchoice]()
>      return
>
> It works well, but the first item is the list is item 0.  This is
> normal in most computing situations, but because this index is part of
> the output It would be nice if the first item in the list is item 1.
>
> php provided a way to change this, but I can find no documentation
> that says python can do this as well.
I don't know of any way to change this, but I can think may ways to 
bypass the "problem"  or to make good use of it. For example:

mainmenuoptions = ["Main Menu:\n", 
'Clients','Jobs','Billing','Quotes','To Do Items','Employee','Exit']
mainmenucalls = [do_nothing, clientsmenu, jobsmenu, billingmenu, 
quotesmenu, todomenu, empmenu, quit]
def do_nothing()
     pass

What about this?

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3126 -  Data di rilascio: 09/10/10 09:08:00

From steve at pearwood.info  Sat Sep 11 13:05:57 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 21:05:57 +1000
Subject: [Tutor] hashlib problems
In-Reply-To: <AANLkTin1Z7=hOhtomjc_mHmxMDo8Wbjav_tUYeYZM28T@mail.gmail.com>
References: <AANLkTinEzqO49rykXOsMBXYNojnn5cx0kvjcVZdRcA6X@mail.gmail.com>
	<D2CC526C-E8CA-4473-8BB9-0F5047A65AE8@gmail.com>
	<AANLkTin1Z7=hOhtomjc_mHmxMDo8Wbjav_tUYeYZM28T@mail.gmail.com>
Message-ID: <201009112105.57574.steve@pearwood.info>

On Sat, 11 Sep 2010 06:54:39 am Rance Hall wrote:

> I will apologize for the tone and using the word "bug" without
> sufficient evidence, and I will be more thorough in the future.

Using the word "bug" itself isn't the problem. Nor is it that you made a 
mistake -- we've all done that. A few days ago I wrote to the 
comp.lang.python newsgroup with what I was *convinced* was a bug in the 
doctest module. After somebody wrote back and said they didn't get the 
same results as me, I tried it again, and *I* couldn't get the same 
results as me!

You wrote:

"Either there is a bug in the module hashlib, or the module changed and 
the docs don't keep up."

But you neglected the third all-important option:

"...or I'm missing something here and have made a mistake."

Leaving out the third possibility makes all the difference in how people 
will react to you misdiagnosing a non-bug as a bug. Particularly if 
you're still a beginner, or a newbie to Python.

If you're Guido van Rossum (Python's creator), or the Timbot (Tim 
Peters, who designed Python's amazing sort routine), and you 
misdiagnose a bug, nobody will blink. We all make mistakes. But when 
you're a newbie (generic you, not you personally), and haven't learned 
the language yet, and you think you've spotted something which tens or 
hundreds of thousands of experienced Python coders have failed to 
notice *without* considering that maybe the bug is in *your* code, 
well, people will either write you off as arrogant or laugh in your 
face. (Still generic you.)

Anyway, welcome on board!


-- 
Steven D'Aprano

From evert.rol at gmail.com  Sat Sep 11 13:09:31 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 11 Sep 2010 13:09:31 +0200
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <20100911095821.GA2670@cecilia>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
Message-ID: <3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>

>>> My script to call a web service authenticates.  
> 
>> Sorry, but where is the (full) script? I missed an attachment or (preferably) a link.
> 
> Hello,
> 
> Sorry, the verb of the sentence is "authenticates," as in, "My script
> ... authenticates."

Sorry, misread that.
Although code does help :-). 
I assume the rest of the code is just the loop around the items you want to fetch, calling getData each time with a new URL.


> But I can show the authentication portion.
> 
> 8<-------------- start -------------------->8
> 
> # Creates an authentication object with the credentials for a given URL
> def createPasswordManager(headers) :
>    passwordManager = urllib2.HTTPPasswordMgrWithDefaultRealm()
>    passwordManager.add_password(None,overview_url,headers[0],headers[1])
>    return passwordManager
> 
> # Creates an authentication handler for the authentication object created above
> def createAuthenticationHandler(passwordManager) :
>    authenticationHandler = urllib2.HTTPBasicAuthHandler(passwordManager)
>    return authenticationHandler
> 
> # Creates an opener that sets the credentials in the Request
> def createOpener(authHandler) :
>    return urllib2.build_opener(authHandler)
> 
> 
> # Retrieves the data    
> def getData(authHeaders) :
>    opener = createOpener(createAuthenticationHandler(createPasswordManager(authHeaders)))
>    data = opener.open(overview_url)
>    return data
> 8<--------------- end ------------------------>8
> 
> So, to restate the question, how can I trap an exception in the cases
> in which authentication fails? 
> 
> Right now, the whole script is complete and working (thanks for your
> help with my other exception-handling question).  Except for the case
> of bad credentials.  The use case is that the user misspells a
> username or password or puts in a wrong account information.  Then, I
> don't want them to sit for 10 minutes while the script makes 30 data
> connections, retries and fails each time.

I'm not sure what you're exactly doing here, or what you're getting, but I did get curious and dug around urllib2.py. Apparently, there is a hardcoded 5 retries before the authentication really fails. So any stack trace would be the normal stack trace times 5. Not the 30 you mentioned, but annoying enough anyway (I don't see how it would fail for every element in the loop though. Once it raises an exception, the program basically ends).
I don't know why it's hard-coded that way, and not just an option with a default of 5, but that's currently how it is (maybe someone else on this list knows?).
If that's what you're finding, perhaps the quickest way is to subclass urllib2.HTTPBasicAuthHandler, and override the http_error_auth_reqed method (essentially keeping it exactly the same apart from the hard-coded 5).

Otherwise, I'm afraid I still don't know what's the problem you're having.

  Evert


From steve at pearwood.info  Sat Sep 11 13:18:17 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 11 Sep 2010 21:18:17 +1000
Subject: [Tutor] smtp connection problem --- socket error 10061
In-Reply-To: <4C8A7450.9020406@gmail.com>
References: <4C8A7450.9020406@gmail.com>
Message-ID: <201009112118.17845.steve@pearwood.info>

On Sat, 11 Sep 2010 04:09:20 am goodhei8 at gmail.com wrote:
>   I could not connect with gmail smtp server in Vista 32( worked ok
> in XP 32). Both vista and xp have same anti-virus software.
>
> >>> smtplib.SMTP("smtp.gmail.com",587)
>
> Traceback (most recent call last):
>    File "<pyshell#1>", line 1, in <module>
>      smtplib.SMTP("smtp.gmail.com",587)
>    File "C:\Program Files\Python25\lib\smtplib.py", line 244, in
> __init__ (code, msg) = self.connect(host, port)
>    File "C:\Program Files\Python25\lib\smtplib.py", line 310, in
> connect raise socket.error, msg
> error: (10061, 'Connection refused')


Works for me:

>>> import smtplib
>>> smtplib.SMTP("smtp.gmail.com",587)
<smtplib.SMTP instance at 0xb7ca620c>


> I am using IPV4 for my vista wireless connection. No improvement with
> firewall disabled.

Which firewall? On the router, or on Windows?

Perhaps your ISP is blocking the port, or maybe it was just that Gmail 
was not allowing connections at that moment.

Have you verified that you can connect to the server outside of Python 
(say, with telnet)?


> Any one has this problem? any solution?

Have you tried Googling? The second hit for "smtp 10061, 'Connection 
refused'" is this:

http://bytes.com/topic/python/answers/32889-sending-mail-smtp-connection-refused-but-smtp-server-isrunning

Does that help?


-- 
Steven D'Aprano

From michael at trollope.org  Sat Sep 11 13:39:24 2010
From: michael at trollope.org (Michael Powe)
Date: Sat, 11 Sep 2010 07:39:24 -0400
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
Message-ID: <20100911113924.GB2670@cecilia>

On Sat, Sep 11, 2010 at 01:09:31PM +0200, Evert Rol wrote:

> >>> My script to call a web service authenticates.  
> > 
> >> Sorry, but where is the (full) script? I missed an attachment or (preferably) a link.
> > 
> > Hello,
> > 
> > Sorry, the verb of the sentence is "authenticates," as in, "My script
> > ... authenticates."
> 
> Sorry, misread that.
> Although code does help :-). 

> I assume the rest of the code is just the loop around the items you
> want to fetch, calling getData each time with a new URL.

Yes, it's looping over a list.  Specifically, at startup the script
does a date detection and creates a list of identifiers for each week
of the year up to the point of invocation.  So, if it is week 36, I
get a list of 36 weeks.

Then, the data retrieval and processing takes place like this:

[processData(w) for w in weeks]

Where the processData function calls getData() and passes in the
current week to process.

[ code snipped ]
 
> > So, to restate the question, how can I trap an exception in the cases
> > in which authentication fails? 

[ snip ]
 
> I'm not sure what you're exactly doing here, or what you're getting,
>but I did get curious and dug around urllib2.py. Apparently, there is
>a hardcoded 5 retries before the authentication really fails. So any
>stack trace would be the normal stack trace times 5. Not the 30 you
>mentioned, but annoying enough anyway (I don't see how it would fail
>for every element in the loop though. Once it raises an exception,
>the program basically ends).

It never throws an exception.  Or, if it does, something about the way
I'm calling suppresses it.  IOW, I can put in a bogus credential and
start the script and sit here for 5 minutes and see nothing.  Then ^C
and I get a huge stacktrace that shows the repeated calls.  After the
timeout on one element in the list, it goes to the next element, times
out, goes to the next.

> I don't know why it's hard-coded that way, and not just an option
> with a default of 5, but that's currently how it is (maybe someone
> else on this list knows?).

I don't know, but even if I could set it to 1, I'm not helped unless
there's a way for me to make it throw an exception and exit the loop. 

> If that's what you're finding, perhaps the quickest way is to
> subclass urllib2.HTTPBasicAuthHandler, and override the
> http_error_auth_reqed method (essentially keeping it exactly the
> same apart from the hard-coded 5).

Now there's a challenge!  ;-)

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA


Is it time for your medication or mine?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/decb5454/attachment.pgp>

From evert.rol at gmail.com  Sat Sep 11 14:25:24 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 11 Sep 2010 14:25:24 +0200
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <20100911113924.GB2670@cecilia>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
	<20100911113924.GB2670@cecilia>
Message-ID: <9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>

<snip />

>> I'm not sure what you're exactly doing here, or what you're getting,
>> but I did get curious and dug around urllib2.py. Apparently, there is
>> a hardcoded 5 retries before the authentication really fails. So any
>> stack trace would be the normal stack trace times 5. Not the 30 you
>> mentioned, but annoying enough anyway (I don't see how it would fail
>> for every element in the loop though. Once it raises an exception,
>> the program basically ends).
> 
> It never throws an exception.  Or, if it does, something about the way
> I'm calling suppresses it.  IOW, I can put in a bogus credential and
> start the script and sit here for 5 minutes and see nothing.  Then ^C
> and I get a huge stacktrace that shows the repeated calls.  After the
> timeout on one element in the list, it goes to the next element, times
> out, goes to the next.

Ok, now I had to try and recreate something myself. So my processData is:

def processData(f):
   global overview_url
   overview_url = baseurl + f
   getData(authHeaders)

(f being a filename, out of a list of many). Other code same as yours.

It definitely throws a 401 exception after 5 retries. No time-outs, no long waits. In fact, a time-out would to me indicate another problem (it still should throw an exception, though). So, unless you're catching the exception in processData somehow, I don't see where things could go wrong. 
I assume you have no problem with correct credentials or simply using a webbrowser?



>> I don't know why it's hard-coded that way, and not just an option
>> with a default of 5, but that's currently how it is (maybe someone
>> else on this list knows?).
> 
> I don't know, but even if I could set it to 1, I'm not helped unless
> there's a way for me to make it throw an exception and exit the loop. 
> 
>> If that's what you're finding, perhaps the quickest way is to
>> subclass urllib2.HTTPBasicAuthHandler, and override the
>> http_error_auth_reqed method (essentially keeping it exactly the
>> same apart from the hard-coded 5).
> 
> Now there's a challenge!  ;-)

It'd be straightforward, but not solve your current problem, I'm afraid.


From ranceh at gmail.com  Sat Sep 11 15:25:12 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sat, 11 Sep 2010 08:25:12 -0500
Subject: [Tutor] changing list index start
In-Reply-To: <i6ee5h$rnu$1@dough.gmane.org>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<i6ee5h$rnu$1@dough.gmane.org>
Message-ID: <AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>

On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 09/11/10 07:36, Rance Hall wrote:

<snip>

> In most cases in Python, you would almost never need to reference the
> list's index directly since python makes it easy to use iterators;
> however in your particular case, which is a valid exception, enumerate()
> takes an optional second argument `start` which defines the number that
> enumerate start to count with, i.e. you can do:
>
> for i, option in enumerate(mainmenuoptions, 1):
> ? ?print('%s. %s' % (i, option))
>
>> php provided a way to change this, but I can find no documentation
>> that says python can do this as well.
>


Thanks everyone for responding,  Because this menu structure is
repeated many times in my code, the ideal solution would have been to
"set index start = 1" in the beginning of the script.

something like sysctl variables in Linux perhaps but in this case only
valid for this program.

Its clear from the responses that this solution is not available in
python, I wish it were, it would make my life much easier for this
project.

I like the approach that Lie suggested, as it seems more "natural
python" to me as opposed to a workaround.

However this is also only half a solution since it applies to the
printed menus only and not to the response afterward.

It seems that Luke is right looks like we have to do math with the indexes.

Lie also referred to my particular case as a valid exception, are
there enough other such valid exceptions that requesting a feature
enhancement would gain some traction?

If this is but one of a few special cases, I doubt it would be worth
the time or trouble to formally make the request.

Maybe I should ask if there is a better way to do what I want to do
here. Is there?

From joel.goldstick at gmail.com  Sat Sep 11 15:46:40 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 11 Sep 2010 09:46:40 -0400
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<i6ee5h$rnu$1@dough.gmane.org>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
Message-ID: <AANLkTinv1au75+piHUziHnjDMqNLnG1YTGUZvOOP3awb@mail.gmail.com>

On Sat, Sep 11, 2010 at 9:25 AM, Rance Hall <ranceh at gmail.com> wrote:

> On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> > On 09/11/10 07:36, Rance Hall wrote:
>
> <snip>
>
> > In most cases in Python, you would almost never need to reference the
> > list's index directly since python makes it easy to use iterators;
> > however in your particular case, which is a valid exception, enumerate()
> > takes an optional second argument `start` which defines the number that
> > enumerate start to count with, i.e. you can do:
> >
> > for i, option in enumerate(mainmenuoptions, 1):
> >    print('%s. %s' % (i, option))
> >
> >> php provided a way to change this, but I can find no documentation
> >> that says python can do this as well.
> >
>
>
> Thanks everyone for responding,  Because this menu structure is
> repeated many times in my code, the ideal solution would have been to
> "set index start = 1" in the beginning of the script.
>
> something like sysctl variables in Linux perhaps but in this case only
> valid for this program.
>
> Its clear from the responses that this solution is not available in
> python, I wish it were, it would make my life much easier for this
> project.
>
> I like the approach that Lie suggested, as it seems more "natural
> python" to me as opposed to a workaround.
>
> However this is also only half a solution since it applies to the
> printed menus only and not to the response afterward.
>

It might be more trouble than its worth, but you could use a dictionary:
Instead of this:
    mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
Items','Employee','Exit']

do this:
    mainmenuoptions = {'Clients': 1,'Jobs': 2,'Billing': 3,'Quotes': 4,'To
Do
Items': 5,'Employee': 6,'Exit': 7}

Use the phrases as key, and the value as your numeric index.  Or you could
reverse {1: 'Clients', ...

if that suites your already written code.

If you use this pattern in many places, could you not refactor so that you
call
the process with the menu data structures as parameters, and fix the code
in a single place?



>
> It seems that Luke is right looks like we have to do math with the indexes.
>
> Lie also referred to my particular case as a valid exception, are
> there enough other such valid exceptions that requesting a feature
> enhancement would gain some traction?
>
> If this is but one of a few special cases, I doubt it would be worth
> the time or trouble to formally make the request.
>
> Maybe I should ask if there is a better way to do what I want to do
> here. Is there?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/b95ad12b/attachment.html>

From knacktus at googlemail.com  Sat Sep 11 16:05:27 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sat, 11 Sep 2010 16:05:27 +0200
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTinv1au75+piHUziHnjDMqNLnG1YTGUZvOOP3awb@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>	<i6ee5h$rnu$1@dough.gmane.org>	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
	<AANLkTinv1au75+piHUziHnjDMqNLnG1YTGUZvOOP3awb@mail.gmail.com>
Message-ID: <4C8B8CA7.2090900@googlemail.com>

Am 11.09.2010 15:46, schrieb Joel Goldstick:
>
>
> On Sat, Sep 11, 2010 at 9:25 AM, Rance Hall <ranceh at gmail.com
> <mailto:ranceh at gmail.com>> wrote:
>
>     On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan <lie.1296 at gmail.com
>     <mailto:lie.1296 at gmail.com>> wrote:
>      > On 09/11/10 07:36, Rance Hall wrote:
>
>     <snip>
>
>      > In most cases in Python, you would almost never need to reference the
>      > list's index directly since python makes it easy to use iterators;
>      > however in your particular case, which is a valid exception,
>     enumerate()
>      > takes an optional second argument `start` which defines the
>     number that
>      > enumerate start to count with, i.e. you can do:
>      >
>      > for i, option in enumerate(mainmenuoptions, 1):
>      >    print('%s. %s' % (i, option))
>      >
>      >> php provided a way to change this, but I can find no documentation
>      >> that says python can do this as well.
>      >
>
>
>     Thanks everyone for responding,  Because this menu structure is
>     repeated many times in my code, the ideal solution would have been to
>     "set index start = 1" in the beginning of the script.
>
>     something like sysctl variables in Linux perhaps but in this case only
>     valid for this program.
>
>     Its clear from the responses that this solution is not available in
>     python, I wish it were, it would make my life much easier for this
>     project.
>
>     I like the approach that Lie suggested, as it seems more "natural
>     python" to me as opposed to a workaround.
>
>     However this is also only half a solution since it applies to the
>     printed menus only and not to the response afterward.
>
>
> It might be more trouble than its worth, but you could use a dictionary:
> Instead of this:
>      mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
> Items','Employee','Exit']
>
> do this:
>      mainmenuoptions = {'Clients': 1,'Jobs': 2,'Billing': 3,'Quotes':
> 4,'To Do
> Items': 5,'Employee': 6,'Exit': 7}
>
> Use the phrases as key, and the value as your numeric index.  Or you could
> reverse {1: 'Clients', ...
>
> if that suites your already written code.
>
> If you use this pattern in many places, could you not refactor so that
> you call
> the process with the menu data structures as parameters, and fix the code
> in a single place?
>
>

+1 for the dictionary. A variation of Joels suggestion might be:

shortcuts_to_name_and_functions = {1: ['Clients', clientsmenu], 2: 
['Jobs', jobsmenu]}

for shortcut, name_and_func in shortcuts_to_name_and_functions.items():
     print "%s. %s" % (shortcut, name_and_func[0])

# later make your call
shortcuts_to_name_and_functions[mainchoice][1]()





>
>     It seems that Luke is right looks like we have to do math with the
>     indexes.
>
>     Lie also referred to my particular case as a valid exception, are
>     there enough other such valid exceptions that requesting a feature
>     enhancement would gain some traction?
>
>     If this is but one of a few special cases, I doubt it would be worth
>     the time or trouble to formally make the request.
>
>     Maybe I should ask if there is a better way to do what I want to do
>     here. Is there?
>     _______________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> --
> Joel Goldstick
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From michael at trollope.org  Sat Sep 11 16:48:13 2010
From: michael at trollope.org (Michael Powe)
Date: Sat, 11 Sep 2010 10:48:13 -0400
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
	<20100911113924.GB2670@cecilia>
	<9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>
Message-ID: <20100911144813.GC2670@cecilia>

On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> <snip />
 
> >> I'm not sure what you're exactly doing here, or what you're getting,
> >> but I did get curious and dug around urllib2.py. Apparently, there is
> >> a hardcoded 5 retries before the authentication really fails. So any
> >> stack trace would be the normal stack trace times 5. Not the 30 you
> >> mentioned, but annoying enough anyway (I don't see how it would fail
> >> for every element in the loop though. Once it raises an exception,
> >> the program basically ends).

> > It never throws an exception.  Or, if it does, something about the way
> > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > and I get a huge stacktrace that shows the repeated calls.  After the
> > timeout on one element in the list, it goes to the next element, times
> > out, goes to the next.
 
> Ok, now I had to try and recreate something myself. So my processData is:
 
> def processData(f):
>    global overview_url
>    overview_url = baseurl + f
>    getData(authHeaders)
> 
> (f being a filename, out of a list of many). Other code same as yours.
 
> It definitely throws a 401 exception after 5 retries. No time-outs,
> no long waits. In fact, a time-out would to me indicate another
> problem (it still should throw an exception, though). So, unless
> you're catching the exception in processData somehow, I don't see
> where things could go wrong.

> I assume you have no problem with correct credentials or simply
> using a webbrowser?

Hello,

Yes, I can retrieve data without any problem.  I can break the URL and
generate a 404 exception that is trapped and I can break it in other
ways that generate other types of exceptions.  And trap them.

I went back and looked at the code in urllib2.py and I see the
timeout counter and that it raises an HTTPError after 5 tries.  But I
don't get anything back.  If I just let the code run to completion, I
get sent back to the prompt.  I put a try/catch in the method and I
already have one on the call in main.

 
 
> >> I don't know why it's hard-coded that way, and not just an option
> >> with a default of 5, but that's currently how it is (maybe someone
> >> else on this list knows?).
> > 
> > I don't know, but even if I could set it to 1, I'm not helped unless
> > there's a way for me to make it throw an exception and exit the loop. 

Actually, there's a comment in the code about why it is set to 5 --
it's arbitrary, and allows for the Password Manager to prompt for
credentials while not letting the request be reissued until 'recursion
depth is exceeded.'

I guess I'll have to go back to ground zero and write a stub to
generate the error and then build back up to where it disappears.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
It turns out that it will be easier to simply block the top offenders
manually; the rules for pattern matching are too arcane, obscure, and
difficult to program. -- t. pascal, comp.mail.misc, "procmail to
filter spam"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/f0c34de9/attachment.pgp>

From bgailer at gmail.com  Sat Sep 11 17:05:54 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 11 Sep 2010 11:05:54 -0400
Subject: [Tutor] exceptions problem
In-Reply-To: <i6fn66$ejn$1@dough.gmane.org>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>	<4C8AC5B9.8070807@gmail.com>	<201009112022.47844.steve@pearwood.info>
	<i6fn66$ejn$1@dough.gmane.org>
Message-ID: <4C8B9AD2.5050906@gmail.com>

  On 9/11/2010 6:56 AM, Peter Otten wrote:
> Steven D'Aprano wrote:
>
>> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>>>> I never thought that you can use a float and a integer to look if
>>>> the number is a integer.
>>> You can't.
>>
I made that comment in the context of the OPs function:

def readposint():
   x = raw_input("Please enter a positive integer :")
   try:
     if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
   except:
     print x , "is not a positive integer. Try again."
     return -1
   return x

The OP thought (incorrectly) that, given for example:
x = '3.1'
float(x) - int(x) would evaluate to 0.1

In reality int(x) in this case raises an exception.
ValueError: invalid literal for int() with base 10: '3.1'

Since the expression was in a try he could not tell exactly what was 
happening.

I also don't quite understand the use of raise in the try.

I wish and hope that Roelof will learn how to do program walkthroughs 
and use the interactive prompt to solve things himself. I applaud the 
patience some of you have ih hand-holding him. I don't have that 
patience. I wish him to learn to fish.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From steve at pearwood.info  Sat Sep 11 17:15:42 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 01:15:42 +1000
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<i6ee5h$rnu$1@dough.gmane.org>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
Message-ID: <201009120115.42800.steve@pearwood.info>

On Sat, 11 Sep 2010 11:25:12 pm Rance Hall wrote:

> Thanks everyone for responding,  Because this menu structure is
> repeated many times in my code, the ideal solution would have been to
> "set index start = 1" in the beginning of the script.

That is exactly the wrong solution. That will break anything and 
everything that assumes "set index start = 0" is applying. Fortunately 
Python doesn't allow such a bad "solution".

The right solution is to get rid of all that duplicated code. Put the 
menu structure in one place, a function, and then call that function 
whenever you need it:


def display_menu(menu):
    for i,option in enumerate(menu, 1):
        print('%s. %s' % (i, option))
    choice = int(input('\nYour Choice? '))
    clearscreen(osname)
    return choice-1


Now your mainmenu function becomes:

def mainmenu():
? ? # the main menu, in case you can't read the function name
? ? todolist()  # why is this here? 
? ? menu = ['Clients','Jobs','Billing','Quotes','To Do 
Items','Employee','Exit']
? ? calls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
todomenu, empmenu, quit]
    n = display_menu(menu)
? ? calls[n]()


And similarly for your other menus:

def secondmenu():
    menu = ['About','Help','Exit']
    calls = [aboutmenu, helpmenu, quit]
    n = display_menu(menu)
    calls[n]()




> something like sysctl variables in Linux perhaps but in this case
> only valid for this program.
>
> Its clear from the responses that this solution is not available in
> python, I wish it were, it would make my life much easier for this
> project.

No, you only *think* it would make your life easier. This is probably 
the time to quote Yoda's speech about the Dark Side of the Force 
from "The Empire Strikes Back".

Such global settings are "easier, faster, simpler"... for about fifteen 
minutes. The right solution is to build reusable building blocks, then 
put them together.


[...]
> Lie also referred to my particular case as a valid exception, are
> there enough other such valid exceptions that requesting a feature
> enhancement would gain some traction?

Not a hope in hell.

You have misunderstood Lie's comment. He's talking about the use of an 
index *at all*. Normally in Python you shouldn't need to use indexes, 
regardless of whether they start with 0 or 1 or 3.1425.... Your example 
of a text menu is an exception to the rule (more of a guideline 
really) "you shouldn't care about indexes".



-- 
Steven D'Aprano

From joel.goldstick at gmail.com  Sat Sep 11 17:40:38 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 11 Sep 2010 11:40:38 -0400
Subject: [Tutor] changing list index start
In-Reply-To: <201009120115.42800.steve@pearwood.info>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<i6ee5h$rnu$1@dough.gmane.org>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
	<201009120115.42800.steve@pearwood.info>
Message-ID: <AANLkTi=dMTXC1wiq=O5HcJt3A3z+hooSqcXKgSWrtN2Y@mail.gmail.com>

On Sat, Sep 11, 2010 at 11:15 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Sat, 11 Sep 2010 11:25:12 pm Rance Hall wrote:
>
> > Thanks everyone for responding,  Because this menu structure is
> > repeated many times in my code, the ideal solution would have been to
> > "set index start = 1" in the beginning of the script.
>
> That is exactly the wrong solution. That will break anything and
> everything that assumes "set index start = 0" is applying. Fortunately
> Python doesn't allow such a bad "solution".
>
> The right solution is to get rid of all that duplicated code. Put the
> menu structure in one place, a function, and then call that function
> whenever you need it:
>
>
> def display_menu(menu):
>    for i,option in enumerate(menu, 1):
>         print('%s. %s' % (i, option))
>     choice = int(input('\nYour Choice? '))
>    clearscreen(osname)
>     return choice-1
>
>
> Now your mainmenu function becomes:
>
> def mainmenu():
>     # the main menu, in case you can't read the function name
>     todolist()  # why is this here?
>     menu = ['Clients','Jobs','Billing','Quotes','To Do
> Items','Employee','Exit']
>     calls = [clientsmenu, jobsmenu, billingmenu, quotesmenu,
> todomenu, empmenu, quit]
>     n = display_menu(menu)
>     calls[n]()
>
>
> And similarly for your other menus:
>
> def secondmenu():
>    menu = ['About','Help','Exit']
>    calls = [aboutmenu, helpmenu, quit]
>    n = display_menu(menu)
>    calls[n]()
>
>
>
>
> > something like sysctl variables in Linux perhaps but in this case
> > only valid for this program.
> >
> > Its clear from the responses that this solution is not available in
> > python, I wish it were, it would make my life much easier for this
> > project.
>
> No, you only *think* it would make your life easier. This is probably
> the time to quote Yoda's speech about the Dark Side of the Force
> from "The Empire Strikes Back".
>
> Such global settings are "easier, faster, simpler"... for about fifteen
> minutes. The right solution is to build reusable building blocks, then
> put them together.
>
>
> [...]
> > Lie also referred to my particular case as a valid exception, are
> > there enough other such valid exceptions that requesting a feature
> > enhancement would gain some traction?
>
> Not a hope in hell.
>
> You have misunderstood Lie's comment. He's talking about the use of an
> index *at all*. Normally in Python you shouldn't need to use indexes,
> regardless of whether they start with 0 or 1 or 3.1425.... Your example
> of a text menu is an exception to the rule (more of a guideline
> really) "you shouldn't care about indexes".
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


I think the first message in the original post is instructive:

"I'm using the following function style I found on the net to create
menus for a command line python script:"

I (sometimes!) love looking at other peoples code to learn.  However taking
some code and
using it in your application demands that you understand it, or it will bite
you later.  In this case,
the code might have been appropriate to the original author, but not for its
new use.

Using index starting with 1 sounds to me idiomatic of BASIC programming.
While I'm too inexperienced
with Python to consider myself good at it, I think the key to using python
is to 'get it' as to the fundamental
data types in python and how they make things easier to solve problems.
One of the earliest programming
books I read was 'Algorithms + Data Structures = Programs' by Niklaus
Wirth.  The book used Pascal, which I think
the author wrote.  But no matter the language, learn what data structures it
offers, and why and then your algorithms
will become simpler and more elegant.  If you find yourself doing weird
things with your code, see if you can rethink
how you organize your data



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/a4a2daf2/attachment.html>

From lie.1296 at gmail.com  Sat Sep 11 18:00:02 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 12 Sep 2010 02:00:02 +1000
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>	<i6ee5h$rnu$1@dough.gmane.org>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
Message-ID: <i6g922$bat$1@dough.gmane.org>

On 09/11/10 23:25, Rance Hall wrote:
> On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
>> On 09/11/10 07:36, Rance Hall wrote:
> 
> <snip>
> 
>> In most cases in Python, you would almost never need to reference the
>> list's index directly since python makes it easy to use iterators;
>> however in your particular case, which is a valid exception, enumerate()
>> takes an optional second argument `start` which defines the number that
>> enumerate start to count with, i.e. you can do:
>>
>> for i, option in enumerate(mainmenuoptions, 1):
>>    print('%s. %s' % (i, option))
>>
>>> php provided a way to change this, but I can find no documentation
>>> that says python can do this as well.
>>
> 
> 
> Thanks everyone for responding,  Because this menu structure is
> repeated many times in my code, the ideal solution would have been to
> "set index start = 1" in the beginning of the script.

That would produce a catastrophic effect. What would happen to standard
library modules or external modules now that they have to work in a
different base?

> something like sysctl variables in Linux perhaps but in this case only
> valid for this program.
> 
> Its clear from the responses that this solution is not available in
> python, I wish it were, it would make my life much easier for this
> project.

Personally I think it's a bad idea. Being able to globally rebase list
index would triple the code's WTF count.

> I like the approach that Lie suggested, as it seems more "natural
> python" to me as opposed to a workaround.
> 
> However this is also only half a solution since it applies to the
> printed menus only and not to the response afterward.
>
> It seems that Luke is right looks like we have to do math with the indexes.
>
> Lie also referred to my particular case as a valid exception, are
> there enough other such valid exceptions that requesting a feature
> enhancement would gain some traction?

When I mean, a valid exception, it's referring to "knowing the index
number" of a list, not to the ability of changing the list's base.

> If this is but one of a few special cases, I doubt it would be worth
> the time or trouble to formally make the request.

As an alternative solution, you can derive from UserList and overload
the __getitem__ and __setitem__ operator:

from UserList import UserList
class RebasedList(UserList):
    def __init__(self, base=1, *args, **kwargs):
        UserList.__init__(self, *args, **kwargs)
        self.base = base
    def __getitem__(self, index):
        if self.base <= index < self.base + len(self):
            return UserList.__getitem__(self, index - self.base)
        else:
            raise IndexError(
                "RebasedList index out of range [%s-%s), "
                "given index %s" %
                (self.base, self.base+len(self), index))
    def __setitem__(self, index, item):
        if self.base <= index < self.base + len(self):
            return UserList.__setitem__(self, index - self.base, item)
        else:
            raise IndexError(
                "RebasedList assignment index out of range [%s-%s), "
                "given index %s" %
                (self.base, self.base+len(self), index))
    # for complete emulation, you will also need to override:
    # __iter__, __delitem__, __getslice__, __setslice__,
    # __delslice__, __add__, __mul__, index, insert, pop,
    # remove, and possibly others

You can use it like this:

rl = RebasedList(10, [3, 1, 2, 4, 2, 1]
rl[10] # rl[0]
rl[11] = 29 # rl[1] = 29
print rl # [3, 29, 2, 4, 2, 1]

Then there is the case that negative index no longer work cleanly with a
custom list base.

> Maybe I should ask if there is a better way to do what I want to do
> here. Is there?



From ranceh at gmail.com  Sat Sep 11 18:05:48 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sat, 11 Sep 2010 11:05:48 -0500
Subject: [Tutor] changing list index start
In-Reply-To: <AANLkTi=dMTXC1wiq=O5HcJt3A3z+hooSqcXKgSWrtN2Y@mail.gmail.com>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<i6ee5h$rnu$1@dough.gmane.org>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
	<201009120115.42800.steve@pearwood.info>
	<AANLkTi=dMTXC1wiq=O5HcJt3A3z+hooSqcXKgSWrtN2Y@mail.gmail.com>
Message-ID: <AANLkTi=uf-CYVLPq=kE7Cibjk3D55_rf0V2+nKncPkYt@mail.gmail.com>

On Sat, Sep 11, 2010 at 10:40 AM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:

<snip>

>
> I think the first message in the original post is instructive:
>
> "I'm using the following function style I found on the net to create
> menus for a command line python script:"
>
> I (sometimes!) love looking at other peoples code to learn.? However taking
> some code and
> using it in your application demands that you understand it, or it will bite
> you later.? In this case,
> the code might have been appropriate to the original author, but not for its
> new use.
>

I agree completely and I did understand what this code snippet was
doing, and I also understood why the first menu item was labeled 0

My question revolves around the theme of "this is the idea I want to
use, it does this, I like what it does, but I'd like to alter it
slightly, how do I turn this into what I want?

> Using index starting with 1 sounds to me idiomatic of BASIC programming.
> While I'm too inexperienced
> with Python to consider myself good at it, I think the key to using python
> is to 'get it' as to the fundamental
> data types in python and how they make things easier to solve problems.
> One of the earliest programming
> books I read was 'Algorithms + Data Structures = Programs' by Niklaus
> Wirth.? The book used Pascal, which I think
> the author wrote.? But no matter the language, learn what data structures it
> offers, and why and then your algorithms
> will become simpler and more elegant.? If you find yourself doing weird
> things with your code, see if you can rethink
> how you organize your data
>

Yea, it does a little bit, doesn't it.  (at least reminding of BASIC)

I can't disagree with you on the rest of your comments either

I can't say that I thought my original idea was weird at all,  BASIC,
PHP and probably other languages allow you to approach the problem in
the same way I thought of.
But this is python and not any other language, so for me I'm finding
that the biggest issue on my plate now is not "What is this?" but more
of "Why is this better or worse than that?"

Steven reply in an example of what I'm talking about, Steven said "You
*think* its a good idea"

In some ways python is a very flexible flowing language.  In other
ways its very restrictive.  For example: I *like* how whitespace
matters in python, it forces you to structure your code.correctly.
Other languages don't care about the whitespace, you dont have to
indent your code (which is a disaster to read I know)

This is the stuff I need to learn, where is python rigid and where is
it flexible.  This gives me a framework to use for evaluating tasks.

I think my original question has been answered and I'm glad I wasn't
barking up the wrong tree.

As to the philosophical stuff maybe its time to start a new thread.

From rwobben at hotmail.com  Sat Sep 11 18:12:15 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 16:12:15 +0000
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8B9AD2.5050906@gmail.com>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>	<4C8AC5B9.8070807@gmail.com>
	<201009112022.47844.steve@pearwood.info>, <i6fn66$ejn$1@dough.gmane.org>,
	<4C8B9AD2.5050906@gmail.com>
Message-ID: <SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>




----------------------------------------
> Date: Sat, 11 Sep 2010 11:05:54 -0400
> From: bgailer at gmail.com
> To: tutor at python.org
> Subject: Re: [Tutor] exceptions problem
>
> On 9/11/2010 6:56 AM, Peter Otten wrote:
>> Steven D'Aprano wrote:
>>
>>> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>>>>> I never thought that you can use a float and a integer to look if
>>>>> the number is a integer.
>>>> You can't.
>>>
> I made that comment in the context of the OPs function:
>
> def readposint():
> x = raw_input("Please enter a positive integer :")
> try:
> if (int(x)<0 or (float(x) - int(x)> 0)): raise(ValueError)
> except:
> print x , "is not a positive integer. Try again."
> return -1
> return x
>
> The OP thought (incorrectly) that, given for example:
> x = '3.1'
> float(x) - int(x) would evaluate to 0.1
>
> In reality int(x) in this case raises an exception.
> ValueError: invalid literal for int() with base 10: '3.1'
>
> Since the expression was in a try he could not tell exactly what was
> happening.
>
> I also don't quite understand the use of raise in the try.
>
> I wish and hope that Roelof will learn how to do program walkthroughs
> and use the interactive prompt to solve things himself. I applaud the
> patience some of you have ih hand-holding him. I don't have that
> patience. I wish him to learn to fish.
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello Bob, 
 
Oke, I try to  fish.
 
When I do 
 
x= "a"
y= int(x) 
Then I get ValueError.
 
When I do 
 
x= 1.2
y=int(x)
No exception is raised.
But when I do then x ==y I get a false.
When I now do float(x) - int(x) I get 1.2 - 1 = 0.2 and that's greater then 0 
 
Because one of the two is true the Raise is executed.
 
 
x = -9 
y=int(x) 
No exception is raised.
X == y is True.
But float(x) - int(x) I get 0.0 and 0.0> 0 is False.
Because x == y is True the Raise is executed.
 
Are these the right conclusions ??
 
Roelof
 
 
  		 	   		  

From steve at pearwood.info  Sat Sep 11 19:18:19 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 03:18:19 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
Message-ID: <201009120318.19827.steve@pearwood.info>

On Fri, 10 Sep 2010 09:30:23 pm Ewald Horn wrote:

> While EAFP is great, it's not
> always the best way to proceed. 

That, at least, is correct. But what you say next is not:

> Sometimes you want programs to be 
> very robust and secure, this is where LBYL comes in - it is quite
> often used in online transaction processing and other areas where
> absolute certainty is more important than any other consideration.

If what you are saying is correct, and I doubt seriously that it is, 
then chances are good that they're not succeeding in their aim.

> EAFP tends to use less code and is faster to use, while LBYL
> principles makes your program more bulletproof.

That's almost 100% backwards.

Let's take a simple example: you want to open a file, and deal with the 
case of the file being missing:

filename = 'myfile.txt'  # whatever...
fp = open(filename)
do_something_with(fp)

Let's add some error checking. With EAFP, you get this:

try:
    fp = open(filename)
except IOError:
    handle_error()


With LBYL, you get:

if os.path.exists(filename):
    fp = open(filename)
else:
    handle_error()


The amount of code is about the same, but the try...except block 
automatically handles a whole slew of errors -- missing files, 
permission denied, bad file names, corrupt disks, all sorts of things 
that would be difficult or tedious to Look Before You Leap. Some of 
these things -- like disk corruption -- you simply can't check ahead of 
time. There is no way of knowing if a file is corrupt without actually 
opening and/or reading from it.

It gets worse. Your computer is a multitasking system. Virtually all 
computers are these days, yes, even the iPhone. Even if os.path.exists 
returns True, there is no guarantee that the file will still be there a 
millisecond later when you try to open it. Perhaps the operating 
system, or some other process, has deleted the file or renamed it. 
That's a bug waiting to happen -- a "race condition".

So if you're silly, you write this:

if os.path.exists(filename):
    try:
        fp = open(filename)
    except IOError:
        handle_error()
else:
    handle_error()

If you're sensible, you realise that for reliable, secure code, checking 
for existence *before* opening the file is a waste of time and energy. 
It's barely acceptable for quick and dirty scripts, certainly not for 
high reliability applications.

This is not the only sort of race condition. Imagine you're writing one 
of these high reliability online transactions you talked about, and you 
want to transfer money from one account to another:

amount = 1000.00
if balance >= amount:
    transfer(old_account, new_account, amount)
else:
    insufficient_balance()


Wait a second... that looks almost exactly like the LBYL code above, and 
it is vulnerable to the same sort of race condition if multiple 
processes can connect to the account at the same time. Does your bank 
allow you to log in twice? Does it have automatic transfers? If so, 
then one process can be transferring money while the other is checking 
the balance, and you have a bug waiting to happen.

In practice, the banks allow accounts to become temporarily overdrawn, 
and often charge you for the privilege. And they write complicated code 
that looks like this:


lock_id = lock_account()  # Stop anything else from transferring funds.
while lock_id == 0
    # Lock failed, wait a second and try again.
    time.sleep(1)
    lock_id = lock_account()
    if number_of_attempts() > 10:
        handle_error("internal error, please try again")
# Now it's safe to check the balance.
if balance >= amount:
    transfer(old_account, new_account, amount, lock_id)
else:
    insufficient_balance()
# Don't forget to unlock the account, or there will be trouble later!
errcode = unlock_account(lock_id)
if errcode != 0:
    # This should never happen. If it does, it might mean the lock ID 
    # is incorrect (how?), but probably means the database is corrupt.
    log_serious_error(errcode, lock_id)


It's ugly and error-prone, but it's also a kind of EAFP: instead of 
checking whether a lock is available, and then taking it, you just try 
to acquire a lock, and deal with the consequences of not receiving one 
if it fails. The only difference is that you're manually checking an 
error code rather than catching an exception.

Whatever mechanism is used for EAFP, it is most often shorter, simpler, 
more reliable and safer than LBYL.

So why would anyone ever use LBYL? Well, sometimes it is more convenient 
for quick and dirty scripts, such as using os.path.exists. But more 
importantly, sometimes you need a transaction to apply in full, or not 
at all. You can't do this:

try:
    do_this()
    do_that()
    do_something_else()
except Exception:
    do_error()


because if do_this() succeeds and do_that() fails, you might leave your 
data is a seriously inconsistent or broken state. You could do this:


failed = False
save_state()
try:
    do_this()
    try:
        do_that()
        try:
            do_something_else()
        except Exception:
            rollback()
            failed = True
    except Exception:
        rollback()
        failed = True
except Exception:
    rollback()
    failed = True
if failed:
    do_error()


Or you could do this:

if do_this_will_succeed() and do_that_will_succeed() \
and do_something_else_will_succeed():
    do_this()
    do_that()
    do_something_else()
else:
    do_error()

But that hasn't done anything to prevent race conditions. So the real 
reason people use LBYL is that they're too lazy to write hideously 
ugly, but reliable, code, and they're just hoping that they will never 
expose the race condition. (Often this is a pretty safe hope, but not 
always.)

And now you know why ACID-compliant databases are so complex.



-- 
Steven D'Aprano

From rwobben at hotmail.com  Sat Sep 11 19:24:44 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 17:24:44 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <201009120318.19827.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>,
	<201009120318.19827.steve@pearwood.info>
Message-ID: <SNT118-W36829E57D9B915D53FB370AE750@phx.gbl>




----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sun, 12 Sep 2010 03:18:19 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Fri, 10 Sep 2010 09:30:23 pm Ewald Horn wrote:
>
>> While EAFP is great, it's not
>> always the best way to proceed.
>
> That, at least, is correct. But what you say next is not:
>
>> Sometimes you want programs to be
>> very robust and secure, this is where LBYL comes in - it is quite
>> often used in online transaction processing and other areas where
>> absolute certainty is more important than any other consideration.
>
> If what you are saying is correct, and I doubt seriously that it is,
> then chances are good that they're not succeeding in their aim.
>
>> EAFP tends to use less code and is faster to use, while LBYL
>> principles makes your program more bulletproof.
>
> That's almost 100% backwards.
>
> Let's take a simple example: you want to open a file, and deal with the
> case of the file being missing:
>
> filename = 'myfile.txt' # whatever...
> fp = open(filename)
> do_something_with(fp)
>
> Let's add some error checking. With EAFP, you get this:
>
> try:
> fp = open(filename)
> except IOError:
> handle_error()
>
>
> With LBYL, you get:
>
> if os.path.exists(filename):
> fp = open(filename)
> else:
> handle_error()
>
>
> The amount of code is about the same, but the try...except block
> automatically handles a whole slew of errors -- missing files,
> permission denied, bad file names, corrupt disks, all sorts of things
> that would be difficult or tedious to Look Before You Leap. Some of
> these things -- like disk corruption -- you simply can't check ahead of
> time. There is no way of knowing if a file is corrupt without actually
> opening and/or reading from it.
>
> It gets worse. Your computer is a multitasking system. Virtually all
> computers are these days, yes, even the iPhone. Even if os.path.exists
> returns True, there is no guarantee that the file will still be there a
> millisecond later when you try to open it. Perhaps the operating
> system, or some other process, has deleted the file or renamed it.
> That's a bug waiting to happen -- a "race condition".
>
> So if you're silly, you write this:
>
> if os.path.exists(filename):
> try:
> fp = open(filename)
> except IOError:
> handle_error()
> else:
> handle_error()
>
> If you're sensible, you realise that for reliable, secure code, checking
> for existence *before* opening the file is a waste of time and energy.
> It's barely acceptable for quick and dirty scripts, certainly not for
> high reliability applications.
>
> This is not the only sort of race condition. Imagine you're writing one
> of these high reliability online transactions you talked about, and you
> want to transfer money from one account to another:
>
> amount = 1000.00
> if balance>= amount:
> transfer(old_account, new_account, amount)
> else:
> insufficient_balance()
>
>
> Wait a second... that looks almost exactly like the LBYL code above, and
> it is vulnerable to the same sort of race condition if multiple
> processes can connect to the account at the same time. Does your bank
> allow you to log in twice? Does it have automatic transfers? If so,
> then one process can be transferring money while the other is checking
> the balance, and you have a bug waiting to happen.
>
> In practice, the banks allow accounts to become temporarily overdrawn,
> and often charge you for the privilege. And they write complicated code
> that looks like this:
>
>
> lock_id = lock_account() # Stop anything else from transferring funds.
> while lock_id == 0
> # Lock failed, wait a second and try again.
> time.sleep(1)
> lock_id = lock_account()
> if number_of_attempts()> 10:
> handle_error("internal error, please try again")
> # Now it's safe to check the balance.
> if balance>= amount:
> transfer(old_account, new_account, amount, lock_id)
> else:
> insufficient_balance()
> # Don't forget to unlock the account, or there will be trouble later!
> errcode = unlock_account(lock_id)
> if errcode != 0:
> # This should never happen. If it does, it might mean the lock ID
> # is incorrect (how?), but probably means the database is corrupt.
> log_serious_error(errcode, lock_id)
>
>
> It's ugly and error-prone, but it's also a kind of EAFP: instead of
> checking whether a lock is available, and then taking it, you just try
> to acquire a lock, and deal with the consequences of not receiving one
> if it fails. The only difference is that you're manually checking an
> error code rather than catching an exception.
>
> Whatever mechanism is used for EAFP, it is most often shorter, simpler,
> more reliable and safer than LBYL.
>
> So why would anyone ever use LBYL? Well, sometimes it is more convenient
> for quick and dirty scripts, such as using os.path.exists. But more
> importantly, sometimes you need a transaction to apply in full, or not
> at all. You can't do this:
>
> try:
> do_this()
> do_that()
> do_something_else()
> except Exception:
> do_error()
>
>
> because if do_this() succeeds and do_that() fails, you might leave your
> data is a seriously inconsistent or broken state. You could do this:
>
>
> failed = False
> save_state()
> try:
> do_this()
> try:
> do_that()
> try:
> do_something_else()
> except Exception:
> rollback()
> failed = True
> except Exception:
> rollback()
> failed = True
> except Exception:
> rollback()
> failed = True
> if failed:
> do_error()
>
>
> Or you could do this:
>
> if do_this_will_succeed() and do_that_will_succeed() \
> and do_something_else_will_succeed():
> do_this()
> do_that()
> do_something_else()
> else:
> do_error()
>
> But that hasn't done anything to prevent race conditions. So the real
> reason people use LBYL is that they're too lazy to write hideously
> ugly, but reliable, code, and they're just hoping that they will never
> expose the race condition. (Often this is a pretty safe hope, but not
> always.)
>
> And now you know why ACID-compliant databases are so complex.
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello Steven.
 
Good and clear explanation.
Thank you.
 
Roelof
  		 	   		  

From steve at pearwood.info  Sat Sep 11 19:27:42 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 03:27:42 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <201009120318.19827.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
	<201009120318.19827.steve@pearwood.info>
Message-ID: <201009120327.42259.steve@pearwood.info>

On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:

> But that hasn't done anything to prevent race conditions. So the real
> reason people use LBYL is that they're too lazy to write hideously
> ugly, but reliable, code, and they're just hoping that they will
> never expose the race condition. (Often this is a pretty safe hope,
> but not always.)

http://en.wikipedia.org/wiki/Ostrich_algorithm


-- 
Steven D'Aprano

From rwobben at hotmail.com  Sat Sep 11 19:40:38 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 17:40:38 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <201009120327.42259.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>,
	<201009120318.19827.steve@pearwood.info>,
	<201009120327.42259.steve@pearwood.info>
Message-ID: <SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>




----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sun, 12 Sep 2010 03:27:42 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:
>
>> But that hasn't done anything to prevent race conditions. So the real
>> reason people use LBYL is that they're too lazy to write hideously
>> ugly, but reliable, code, and they're just hoping that they will
>> never expose the race condition. (Often this is a pretty safe hope,
>> but not always.)
>
> http://en.wikipedia.org/wiki/Ostrich_algorithm
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Oke,
 
But why is type checking then wrong.
Lets says I want a module who must work on strings, tuple and lists.
 
Can I then use EAFP ?
 
Without type checking I never know which one is used now.
 
Roelof
  		 	   		  

From rabidpoobear at gmail.com  Sat Sep 11 19:51:54 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sat, 11 Sep 2010 12:51:54 -0500
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
	<201009120318.19827.steve@pearwood.info>
	<201009120327.42259.steve@pearwood.info>
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>
Message-ID: <873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>


On Sep 11, 2010, at 12:40 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

> 
> 
> 
> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Sun, 12 Sep 2010 03:27:42 +1000
>> Subject: Re: [Tutor] recursive problem
>> 
>> On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:
>> 
>>> But that hasn't done anything to prevent race conditions. So the real
>>> reason people use LBYL is that they're too lazy to write hideously
>>> ugly, but reliable, code, and they're just hoping that they will
>>> never expose the race condition. (Often this is a pretty safe hope,
>>> but not always.)
>> 
>> http://en.wikipedia.org/wiki/Ostrich_algorithm
>> 
>> 
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
> 
> Oke,
> 
> But why is type checking then wrong.
> Lets says I want a module who must work on strings, tuple and lists.
> 
> Can I then use EAFP ?
> 
> Without type checking I never know which one is used now.
> 
> Roelof
>                           

That's the whole point! You don't WANT to know what type it is. You want to just use it how you want, an if it behaves properly, who cares what type it is?

See when you type check you are forcing the user to use those types. What if they want to derive a subclass from list? Is there really a reason why you should prevent them from using that subclass with your function?
If there is a valid reason, type checking is fine. But if there isn't, type checking is just making your code more inflexible.


From davea at ieee.org  Sat Sep 11 19:59:19 2010
From: davea at ieee.org (Dave Angel)
Date: Sat, 11 Sep 2010 13:59:19 -0400
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>	<4C8AC5B9.8070807@gmail.com>	<201009112022.47844.steve@pearwood.info>,
	<i6fn66$ejn$1@dough.gmane.org>, <4C8B9AD2.5050906@gmail.com>
	<SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>
Message-ID: <4C8BC377.4000003@ieee.org>



On 2:59 PM, Roelof Wobben wrote:
> <snip>
> Hello Bob,
>
> Oke, I try to  fish.
>
> When I do
>
> x="a"
> y=nt(x)
> Then I get ValueError.
>
> When I do
>
> x= 1.2
> y=int(x)
> No exception is raised.
> But when I do then x = I get a false.
> When I now do float(x) - int(x) I get 1.2 - 1 =.2 and that's greater then 0
>
> Because one of the two is true the Raise is executed.
>
>
> x = -9
> y= int(x)
> No exception is raised.
> X =y is True.
> But float(x) - int(x) I get 0.0 and 0.0>  0 is False.
> Because x =y is True the Raise is executed.
>
> Are these the right conclusions ??
>
> Roelof
>
>
>    		 	   		
But in your original code, x was a string.  raw_input() produces a 
string, not a float.  So the middle case is different than what you're 
trying now.

DaveA


From wprins at gmail.com  Sat Sep 11 20:01:39 2010
From: wprins at gmail.com (Walter Prins)
Date: Sat, 11 Sep 2010 19:01:39 +0100
Subject: [Tutor] recursive problem
In-Reply-To: <873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
	<201009120318.19827.steve@pearwood.info>
	<201009120327.42259.steve@pearwood.info>
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>
Message-ID: <AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>

> That's the whole point! You don't WANT to know what type it is. You want to
> just use it how you want, an if it behaves properly, who cares what type it
> is?
>
> See when you type check you are forcing the user to use those types. What
> if they want to derive a subclass from list? Is there really a reason why
> you should prevent them from using that subclass with your function?
> If there is a valid reason, type checking is fine. But if there isn't, type
> checking is just making your code more inflexible.
>
>
Well, I would submit that if were going to do type checking in such a
context you'd probably check for a base class, so deriving a subclass
wouldn't break entirely.  Your point still stands however, we don't even
want to require from users to derive from class list.  We'd be quite happy
to work with any object that "walks like a list" and "quacks like a list",
that's the beauty of duck typing...

I guess the question to ask/consider is: How can be establish whether a
particular object supports a particular interface/set of behaviours that we
require?  E.g. how do we most pythonically check whether some object "walks
like a list" and "quacks like a list" without tying such code to explicit
type checking?

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/c9977bea/attachment.html>

From steve at pearwood.info  Sat Sep 11 20:03:43 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 04:03:43 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<201009120327.42259.steve@pearwood.info>
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>
Message-ID: <201009120403.43651.steve@pearwood.info>

On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:

> But why is type checking then wrong.
> Lets says I want a module who must work on strings, tuple and lists.

It's not *always* wrong, but let me ask you... why do you want to 
*limit* the function to work on ONLY strings, tuples and lists?

The Python philosophy is "duck typing" -- if it walks like a duck, and 
swims like a duck, it is close enough to a duck that we don't care that 
it's not actually a duck, but a goose.

Here's an example:


def f1(x):
    if type(x) is int or type(x) is float:
        print("x + 1 = %s" % (x+1))
    else:
        print("x is not a number")
    

def f2(x):
    try:
        print("x + 1 = %s" % (x+1))
    except (ValueError, TypeError):
        print("x is not a number")

>>> f1(3)
x + 1 = 4
>>> from decimal import Decimal
>>> f1(Decimal(3))
x is not a number
>>> f2(Decimal(3))
x + 1 = 4

Function f1 makes the assumption that only ints and floats can be added, 
and so it gives the wrong results with Decimal numbers. But function f2 
uses "duck typing" -- it doesn't care what sort of number x is, only 
that it can be added.



> Can I then use EAFP ?
>
> Without type checking I never know which one is used now.


Going back to type-checking... sometimes you can't avoid it. Sometimes 
you use it because it is easier, and you don't care enough to write 
more complicated code. Sometimes you really do care what the type is:

>>> "abc"[2.0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers



-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 11 20:04:57 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 04:04:57 +1000
Subject: [Tutor] changing list index start
In-Reply-To: <i6g922$bat$1@dough.gmane.org>
References: <AANLkTik2A0BPvnKD6jsd9B+yw16S5iFrOBTEOen-PSWJ@mail.gmail.com>
	<AANLkTikJTQjsVSomtUisNm_PjBMxa77cGdP7rvqA-Rx4@mail.gmail.com>
	<i6g922$bat$1@dough.gmane.org>
Message-ID: <201009120404.58001.steve@pearwood.info>

On Sun, 12 Sep 2010 02:00:02 am Lie Ryan wrote:

> As an alternative solution, you can derive from UserList and overload
> the __getitem__ and __setitem__ operator:

We've been able to inherit from list directly since at least Python 2.2. 
Why are you using UserList?



-- 
Steven D'Aprano

From rwobben at hotmail.com  Sat Sep 11 20:05:50 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 18:05:50 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W1424DD7FCE39F0897F7011AE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>,
	<201009120318.19827.steve@pearwood.info>,
	<201009120327.42259.steve@pearwood.info>,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>,
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>,
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>,
	<SNT118-W1424DD7FCE39F0897F7011AE750@phx.gbl>
Message-ID: <SNT118-W3061808964C7130BA88258AE750@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: wprins at gmail.com
> Subject: RE: [Tutor] recursive problem
> Date: Sat, 11 Sep 2010 18:05:12 +0000
>
>
>
>
> ________________________________
>> Date: Sat, 11 Sep 2010 19:01:39 +0100
>> Subject: Re: [Tutor] recursive problem
>> From: wprins at gmail.com
>> To: rabidpoobear at gmail.com
>> CC: rwobben at hotmail.com; tutor at python.org
>>
>>
>> That's the whole point! You don't WANT to know what type it is. You
>> want to just use it how you want, an if it behaves properly, who cares
>> what type it is?
>>
>> See when you type check you are forcing the user to use those types.
>> What if they want to derive a subclass from list? Is there really a
>> reason why you should prevent them from using that subclass with your
>> function?
>> If there is a valid reason, type checking is fine. But if there isn't,
>> type checking is just making your code more inflexible.
>>
>>
>> Well, I would submit that if were going to do type checking in such a
>> context you'd probably check for a base class, so deriving a subclass
>> wouldn't break entirely. Your point still stands however, we don't
>> even want to require from users to derive from class list. We'd be
>> quite happy to work with any object that "walks like a list" and
>> "quacks like a list", that's the beauty of duck typing...
>>
>> I guess the question to ask/consider is: How can be establish whether a
>> particular object supports a particular interface/set of behaviours
>> that we require? E.g. how do we most pythonically check whether some
>> object "walks like a list" and "quacks like a list" without tying such
>> code to explicit type checking?
>>
>> Walter
>
> Exactly what I mean.
>
> With the knowlegde I have from the few chapters of thinking like a computer scientist I don't know the answer to the last question.
>
>
> Roelof
>
> 		 	   		  

From lie.1296 at gmail.com  Sat Sep 11 20:08:11 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 12 Sep 2010 04:08:11 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>	<201009120318.19827.steve@pearwood.info>	<201009120327.42259.steve@pearwood.info>	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>
Message-ID: <i6ggi8$6c9$1@dough.gmane.org>

On 09/12/10 04:01, Walter Prins wrote:
> I guess the question to ask/consider is: How can be establish whether a
> particular object supports a particular interface/set of behaviours that
> we require?  E.g. how do we most pythonically check whether some object
> "walks like a list" and "quacks like a list" without tying such code to
> explicit type checking?

In Python? By treating it like a list; and shooting the duck in their
webby feet when it doesn't act like a list.


From rwobben at hotmail.com  Sat Sep 11 20:09:20 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 18:09:20 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <201009120403.43651.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<201009120327.42259.steve@pearwood.info>,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>,
	<201009120403.43651.steve@pearwood.info>
Message-ID: <SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>




----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sun, 12 Sep 2010 04:03:43 +1000
> Subject: Re: [Tutor] recursive problem
>
> On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
>
>> But why is type checking then wrong.
>> Lets says I want a module who must work on strings, tuple and lists.
>
> It's not *always* wrong, but let me ask you... why do you want to
> *limit* the function to work on ONLY strings, tuples and lists?
>
> The Python philosophy is "duck typing" -- if it walks like a duck, and
> swims like a duck, it is close enough to a duck that we don't care that
> it's not actually a duck, but a goose.
>
> Here's an example:
>
>
> def f1(x):
> if type(x) is int or type(x) is float:
> print("x + 1 = %s" % (x+1))
> else:
> print("x is not a number")
>
>
> def f2(x):
> try:
> print("x + 1 = %s" % (x+1))
> except (ValueError, TypeError):
> print("x is not a number")
>
>>>> f1(3)
> x + 1 = 4
>>>> from decimal import Decimal
>>>> f1(Decimal(3))
> x is not a number
>>>> f2(Decimal(3))
> x + 1 = 4
>
> Function f1 makes the assumption that only ints and floats can be added,
> and so it gives the wrong results with Decimal numbers. But function f2
> uses "duck typing" -- it doesn't care what sort of number x is, only
> that it can be added.
>
>
>
>> Can I then use EAFP ?
>>
>> Without type checking I never know which one is used now.
>
>
> Going back to type-checking... sometimes you can't avoid it. Sometimes
> you use it because it is easier, and you don't care enough to write
> more complicated code. Sometimes you really do care what the type is:
>
>>>> "abc"[2.0]
> Traceback (most recent call last):
> File "", line 1, in 
> TypeError: string indices must be integers
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello Steven,
 
Because I follow this book "Thinking like a computer scientist" and I have only read the chapters about strings. lists and tuples.

Roelof
  		 	   		  

From michael at trollope.org  Sat Sep 11 20:16:07 2010
From: michael at trollope.org (Michael Powe)
Date: Sat, 11 Sep 2010 14:16:07 -0400
Subject: [Tutor] Trapping HTTP Authentication Failure
In-Reply-To: <20100911144813.GC2670@cecilia>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
	<20100911113924.GB2670@cecilia>
	<9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>
	<20100911144813.GC2670@cecilia>
Message-ID: <20100911181607.GD2670@cecilia>

On Sat, Sep 11, 2010 at 10:48:13AM -0400, Michael Powe wrote:
> On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> > <snip />
>  
> > >> I'm not sure what you're exactly doing here, or what you're getting,
> > >> but I did get curious and dug around urllib2.py. Apparently, there is
> > >> a hardcoded 5 retries before the authentication really fails. So any
> > >> stack trace would be the normal stack trace times 5. Not the 30 you
> > >> mentioned, but annoying enough anyway (I don't see how it would fail
> > >> for every element in the loop though. Once it raises an exception,
> > >> the program basically ends).
 
> > > It never throws an exception.  Or, if it does, something about the way
> > > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > > and I get a huge stacktrace that shows the repeated calls.  After the
> > > timeout on one element in the list, it goes to the next element, times
> > > out, goes to the next.

Hello,

More experimentation revealed that one problem was testing the script
in Idle.  Idle does something to suppress the script failure for that
particular case (IOW, it correctly returns HTTPError for things like
'404' and URLError for things like a bad domain name).

When I run the script from the command line (cmd), it actually ignores
the '5' retry limit, seemingly.  I added another catch block:

except Exception as e:
	   print "exception: ",e

That prints out "exception: maximum recursion depth exceeded."

I wonder if there is something hinky in Windows that is causing this
to happen.

Thanks.

mp
  
> > Ok, now I had to try and recreate something myself. So my processData is:
>  
> > def processData(f):
> >    global overview_url
> >    overview_url = baseurl + f
> >    getData(authHeaders)
> > 
> > (f being a filename, out of a list of many). Other code same as yours.
>  
> > It definitely throws a 401 exception after 5 retries. No time-outs,
> > no long waits. In fact, a time-out would to me indicate another
> > problem (it still should throw an exception, though). So, unless
> > you're catching the exception in processData somehow, I don't see
> > where things could go wrong.
> 
> > I assume you have no problem with correct credentials or simply
> > using a webbrowser?
> 
> Hello,
> 
> Yes, I can retrieve data without any problem.  I can break the URL and
> generate a 404 exception that is trapped and I can break it in other
> ways that generate other types of exceptions.  And trap them.
> 
> I went back and looked at the code in urllib2.py and I see the
> timeout counter and that it raises an HTTPError after 5 tries.  But I
> don't get anything back.  If I just let the code run to completion, I
> get sent back to the prompt.  I put a try/catch in the method and I
> already have one on the call in main.
> 
>  
>  
> > >> I don't know why it's hard-coded that way, and not just an option
> > >> with a default of 5, but that's currently how it is (maybe someone
> > >> else on this list knows?).
> > > 
> > > I don't know, but even if I could set it to 1, I'm not helped unless
> > > there's a way for me to make it throw an exception and exit the loop. 
> 
> Actually, there's a comment in the code about why it is set to 5 --
> it's arbitrary, and allows for the Password Manager to prompt for
> credentials while not letting the request be reissued until 'recursion
> depth is exceeded.'
> 
> I guess I'll have to go back to ground zero and write a stub to
> generate the error and then build back up to where it disappears.
> 
> Thanks.
> 
> mp
> 
> -- 
> Michael Powe		michael at trollope.org		Naugatuck CT USA
> It turns out that it will be easier to simply block the top offenders
> manually; the rules for pattern matching are too arcane, obscure, and
> difficult to program. -- t. pascal, comp.mail.misc, "procmail to
> filter spam"



> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and <growl>; let
him come out as I do, and <bark>. -- Samuel Johnson
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/44fdc62c/attachment.pgp>

From steve at pearwood.info  Sat Sep 11 20:18:22 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 04:18:22 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>
Message-ID: <201009120418.22824.steve@pearwood.info>

On Sun, 12 Sep 2010 04:01:39 am Walter Prins wrote:

> I guess the question to ask/consider is: How can be establish whether
> a particular object supports a particular interface/set of behaviours
> that we require?  E.g. how do we most pythonically check whether some
> object "walks like a list" and "quacks like a list" without tying
> such code to explicit type checking?

isinstance(object, base_class) becomes even more useful in Python 2.6 
and beyond, because when you create a class, you can register it as a 
list even if you didn't inherit from list. You're essentially 
promising "this class will walk and quack and swim like a list".

But often you don't care that something walks, quacks, and swims like a 
list. You might only care that it walks. We can combine "Look Before 
You Leap" with duck-typing:


def swap_items(sequence):
    try:
        sequence[0] = sequence[0]
    except Exception:
        print("does not support item lookup or item assignment")
    else:
        for i in range(0, len(sequence)-1, 2):
            sequence[i], sequence[i+1] = sequence[i+1], sequence[i]
        return sequence


>>> swap_items("abcd")
does not support item lookup or item assignment
>>> swap_items(['a', 'b', 'c', 'd', 'e', 'f'])
['b', 'a', 'd', 'c', 'f', 'e']




-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 11 20:19:57 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 04:19:57 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<201009120403.43651.steve@pearwood.info>
	<SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>
Message-ID: <201009120419.58043.steve@pearwood.info>

On Sun, 12 Sep 2010 04:09:20 am Roelof Wobben wrote:

> > On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
> >> But why is type checking then wrong.
> >> Lets says I want a module who must work on strings, tuple and
> >> lists.
> >
> > It's not *always* wrong, but let me ask you... why do you want to
> > *limit* the function to work on ONLY strings, tuples and lists?

> Because I follow this book "Thinking like a computer scientist" and I
> have only read the chapters about strings. lists and tuples.

Good answer!

Don't worry about all the complications. Learn to walk first, then learn 
to run.



-- 
Steven D'Aprano

From bgailer at gmail.com  Sat Sep 11 20:43:28 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 11 Sep 2010 14:43:28 -0400
Subject: [Tutor] exceptions problem
In-Reply-To: <SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>	<4C8AC5B9.8070807@gmail.com>	<201009112022.47844.steve@pearwood.info>,
	<i6fn66$ejn$1@dough.gmane.org>, <4C8B9AD2.5050906@gmail.com>
	<SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>
Message-ID: <4C8BCDD0.4080909@gmail.com>

  On 9/11/2010 12:12 PM, Roelof Wobben wrote:
>
>
> ----------------------------------------
>> Date: Sat, 11 Sep 2010 11:05:54 -0400
>> From: bgailer at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] exceptions problem
>>
>> On 9/11/2010 6:56 AM, Peter Otten wrote:
>>> Steven D'Aprano wrote:
>>>
>>>> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>>>>>> I never thought that you can use a float and a integer to look if
>>>>>> the number is a integer.
>>>>> You can't.
>> I made that comment in the context of the OPs function:
>>
>> def readposint():
>> x = raw_input("Please enter a positive integer :")
>> try:
>> if (int(x)<0 or (float(x) - int(x)>  0)): raise(ValueError)
>> except:
>> print x , "is not a positive integer. Try again."
>> return -1
>> return x
>>
>> The OP thought (incorrectly) that, given for example:
>> x = '3.1'
>> float(x) - int(x) would evaluate to 0.1
>>
>> In reality int(x) in this case raises an exception.
>> ValueError: invalid literal for int() with base 10: '3.1'
>>
>> Since the expression was in a try he could not tell exactly what was
>> happening.
>>
>> I also don't quite understand the use of raise in the try.
>>
>> I wish and hope that Roelof will learn how to do program walkthroughs
>> and use the interactive prompt to solve things himself. I applaud the
>> patience some of you have ih hand-holding him. I don't have that
>> patience. I wish him to learn to fish.
> Hello Bob,
>
> Oke, I try to  fish.

Thank you.

>
> When I do
>
> x= "a"
> y= int(x)
> Then I get ValueError.
>
> When I do
>
> x= 1.2
> y=int(x)
> No exception is raised.

As Dave pointed out you switched from string to numeric. Try instead x = 
'1.2'

> But when I do then x ==y I get a false.
> When I now do float(x) - int(x) I get 1.2 - 1 = 0.2 and that's greater then 0
>
> Because one of the two is true the Raise is executed.
>
>
> x = -9
> y=int(x)
> No exception is raised.
> X == y is True.
> But float(x) - int(x) I get 0.0 and 0.0>  0 is False.
> Because x == y is True the Raise is executed.
>
> Are these the right conclusions ??
>
> Roelof


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From michael at trollope.org  Sat Sep 11 20:44:59 2010
From: michael at trollope.org (Michael Powe)
Date: Sat, 11 Sep 2010 14:44:59 -0400
Subject: [Tutor] SOLVED: Re:  Trapping HTTP Authentication Failure
In-Reply-To: <20100911181607.GD2670@cecilia>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
	<20100911113924.GB2670@cecilia>
	<9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>
	<20100911144813.GC2670@cecilia> <20100911181607.GD2670@cecilia>
Message-ID: <20100911184459.GE2670@cecilia>

Hello,

It is bloody Winblows.  The script works as designed and traps the 401
exception on my slackware box ... something in the implementation of
urllib2 on Windoze is broken.  This has to be a known issue.  Just did
not see it known anywhere.

Thanks.

mp

On Sat, Sep 11, 2010 at 02:16:07PM -0400, Michael Powe wrote:
> On Sat, Sep 11, 2010 at 10:48:13AM -0400, Michael Powe wrote:
> > On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> > > <snip />
> >  
> > > >> I'm not sure what you're exactly doing here, or what you're getting,
> > > >> but I did get curious and dug around urllib2.py. Apparently, there is
> > > >> a hardcoded 5 retries before the authentication really fails. So any
> > > >> stack trace would be the normal stack trace times 5. Not the 30 you
> > > >> mentioned, but annoying enough anyway (I don't see how it would fail
> > > >> for every element in the loop though. Once it raises an exception,
> > > >> the program basically ends).
>  
> > > > It never throws an exception.  Or, if it does, something about the way
> > > > I'm calling suppresses it.  IOW, I can put in a bogus credential and
> > > > start the script and sit here for 5 minutes and see nothing.  Then ^C
> > > > and I get a huge stacktrace that shows the repeated calls.  After the
> > > > timeout on one element in the list, it goes to the next element, times
> > > > out, goes to the next.
> 
> Hello,
> 
> More experimentation revealed that one problem was testing the script
> in Idle.  Idle does something to suppress the script failure for that
> particular case (IOW, it correctly returns HTTPError for things like
> '404' and URLError for things like a bad domain name).
> 
> When I run the script from the command line (cmd), it actually ignores
> the '5' retry limit, seemingly.  I added another catch block:
> 
> except Exception as e:
> 	   print "exception: ",e
> 
> That prints out "exception: maximum recursion depth exceeded."
> 
> I wonder if there is something hinky in Windows that is causing this
> to happen.
> 
> Thanks.
> 
> mp
>   
> > > Ok, now I had to try and recreate something myself. So my processData is:
> >  
> > > def processData(f):
> > >    global overview_url
> > >    overview_url = baseurl + f
> > >    getData(authHeaders)
> > > 
> > > (f being a filename, out of a list of many). Other code same as yours.
> >  
> > > It definitely throws a 401 exception after 5 retries. No time-outs,
> > > no long waits. In fact, a time-out would to me indicate another
> > > problem (it still should throw an exception, though). So, unless
> > > you're catching the exception in processData somehow, I don't see
> > > where things could go wrong.
> > 
> > > I assume you have no problem with correct credentials or simply
> > > using a webbrowser?
> > 
> > Hello,
> > 
> > Yes, I can retrieve data without any problem.  I can break the URL and
> > generate a 404 exception that is trapped and I can break it in other
> > ways that generate other types of exceptions.  And trap them.
> > 
> > I went back and looked at the code in urllib2.py and I see the
> > timeout counter and that it raises an HTTPError after 5 tries.  But I
> > don't get anything back.  If I just let the code run to completion, I
> > get sent back to the prompt.  I put a try/catch in the method and I
> > already have one on the call in main.
> > 
> >  
> >  
> > > >> I don't know why it's hard-coded that way, and not just an option
> > > >> with a default of 5, but that's currently how it is (maybe someone
> > > >> else on this list knows?).
> > > > 
> > > > I don't know, but even if I could set it to 1, I'm not helped unless
> > > > there's a way for me to make it throw an exception and exit the loop. 
> > 
> > Actually, there's a comment in the code about why it is set to 5 --
> > it's arbitrary, and allows for the Password Manager to prompt for
> > credentials while not letting the request be reissued until 'recursion
> > depth is exceeded.'
> > 
> > I guess I'll have to go back to ground zero and write a stub to
> > generate the error and then build back up to where it disappears.
> > 
> > Thanks.
> > 
> > mp
> > 
> > -- 
> > Michael Powe		michael at trollope.org		Naugatuck CT USA
> > It turns out that it will be easier to simply block the top offenders
> > manually; the rules for pattern matching are too arcane, obscure, and
> > difficult to program. -- t. pascal, comp.mail.misc, "procmail to
> > filter spam"
> 
> 
> 
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 
> 
> -- 
> Michael Powe		michael at trollope.org		Naugatuck CT USA
> I hate a fellow whom pride, or cowardice, or laziness drives into a
> corner, and who does nothing when he is there but sit and <growl>; let
> him come out as I do, and <bark>. -- Samuel Johnson



> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA

"If you don't like the news, go out and make some of your own." 
          -- Scoop Nisker, KSAN-FM, San Francisco
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/1829ebf6/attachment.pgp>

From lie.1296 at gmail.com  Sat Sep 11 20:47:00 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 12 Sep 2010 04:47:00 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <201009120318.19827.steve@pearwood.info>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>	<SNT118-W57BD93747C67231B1E2834AE740@phx.gbl>	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>
	<201009120318.19827.steve@pearwood.info>
Message-ID: <i6gir3$fke$1@dough.gmane.org>

On 09/12/10 03:18, Steven D'Aprano wrote:
> Or you could do this:
> 
> if do_this_will_succeed() and do_that_will_succeed() \
> and do_something_else_will_succeed():
>     do_this()
>     do_that()
>     do_something_else()
> else:
>     do_error()
> 
> But that hasn't done anything to prevent race conditions. So the real 
> reason people use LBYL is that they're too lazy to write hideously 
> ugly, but reliable, code, and they're just hoping that they will never 
> expose the race condition. (Often this is a pretty safe hope, but not 
> always.)

Or, probably the best alternative is to mix LBYL and EAFP, e.g.:

attempt = 0
while attempt < 10:
    # first acquire the lock using EAFP
    try:
        lock = acquire_lock()
    except FailToAcquireLock:
        attempt += 1
        time.sleep(1)
    else:
        # Now apply LBYL, since there is no point in doing
        # operations that may be expensive if they will definitely
        # fail by the quick check
        if account_active(fromAcc) and account_active(toAcc)
                and can_withdraw(fromAcc, amount):

            # this operations only writes to a scratch space
            withdraw(fromAcc, amount)
            deposit(toAcc, amount)

            # back to EAFP, since there is no way of assuring
            # this with LBYL
            try:
                # mark the scratch space as permanent change
                commit()
            except CommitFailure:
                raise SeriousError("this can't be happening")
        else:
    finally:
        # LBYL:
        # there is no point in releasing unacquired lock;
        # should probably be done inside release_lock() so that
        # calling release_lock() an unacquired lock safely does nothing
        if not lock:
            release_lock(lock)
else:
    raise Failure("failed to acquire lock")




else:
    do_error("no privilege")

release_lock(lock)


From rwobben at hotmail.com  Sat Sep 11 22:13:51 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 20:13:51 +0000
Subject: [Tutor]  recursive problem
In-Reply-To: <SNT118-W4AF02D84CED0B8CA3173FAE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<201009120403.43651.steve@pearwood.info>,
	<SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>,
	<201009120419.58043.steve@pearwood.info>,
	<SNT118-W4AF02D84CED0B8CA3173FAE750@phx.gbl>
Message-ID: <SNT118-W50890F99A08A8530C05C4BAE750@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: steve at pearwood.info
> Subject: RE: [Tutor] recursive problem
> Date: Sat, 11 Sep 2010 18:39:31 +0000
>
>
>
>
> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Sun, 12 Sep 2010 04:19:57 +1000
>> Subject: Re: [Tutor] recursive problem
>>
>> On Sun, 12 Sep 2010 04:09:20 am Roelof Wobben wrote:
>>
>>>> On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
>>>>> But why is type checking then wrong.
>>>>> Lets says I want a module who must work on strings, tuple and
>>>>> lists.
>>>>
>>>> It's not *always* wrong, but let me ask you... why do you want to
>>>> *limit* the function to work on ONLY strings, tuples and lists?
>>
>>> Because I follow this book "Thinking like a computer scientist" and I
>>> have only read the chapters about strings. lists and tuples.
>>
>> Good answer!
>>
>> Don't worry about all the complications. Learn to walk first, then learn
>> to run.
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

 Oke,

So EAFP for me is one step to far ?

Roelof 		 	   		  

From rwobben at hotmail.com  Sat Sep 11 22:14:35 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 11 Sep 2010 20:14:35 +0000
Subject: [Tutor]  exceptions problem
In-Reply-To: <SNT118-W19274B162F20006572DB71AE750@phx.gbl>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>,
	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>
	<4C8AC5B9.8070807@gmail.com>, <201009112022.47844.steve@pearwood.info>, ,
	<i6fn66$ejn$1@dough.gmane.org>, , <4C8B9AD2.5050906@gmail.com>,
	<SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>,
	<4C8BCDD0.4080909@gmail.com>,
	<SNT118-W19274B162F20006572DB71AE750@phx.gbl>
Message-ID: <SNT118-W448135325967FC605C940CAE750@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: bgailer at gmail.com
> Subject: RE: [Tutor] exceptions problem
> Date: Sat, 11 Sep 2010 18:51:12 +0000
>
>
>
>
> ----------------------------------------
>> Date: Sat, 11 Sep 2010 14:43:28 -0400
>> From: bgailer at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] exceptions problem
>>
>> On 9/11/2010 12:12 PM, Roelof Wobben wrote:
>>>
>>>
>>> ----------------------------------------
>>>> Date: Sat, 11 Sep 2010 11:05:54 -0400
>>>> From: bgailer at gmail.com
>>>> To: tutor at python.org
>>>> Subject: Re: [Tutor] exceptions problem
>>>>
>>>> On 9/11/2010 6:56 AM, Peter Otten wrote:
>>>>> Steven D'Aprano wrote:
>>>>>
>>>>>> On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
>>>>>>>> I never thought that you can use a float and a integer to look if
>>>>>>>> the number is a integer.
>>>>>>> You can't.
>>>> I made that comment in the context of the OPs function:
>>>>
>>>> def readposint():
>>>> x = raw_input("Please enter a positive integer :")
>>>> try:
>>>> if (int(x)<0 or (float(x) - int(x)> 0)): raise(ValueError)
>>>> except:
>>>> print x , "is not a positive integer. Try again."
>>>> return -1
>>>> return x
>>>>
>>>> The OP thought (incorrectly) that, given for example:
>>>> x = '3.1'
>>>> float(x) - int(x) would evaluate to 0.1
>>>>
>>>> In reality int(x) in this case raises an exception.
>>>> ValueError: invalid literal for int() with base 10: '3.1'
>>>>
>>>> Since the expression was in a try he could not tell exactly what was
>>>> happening.
>>>>
>>>> I also don't quite understand the use of raise in the try.
>>>>
>>>> I wish and hope that Roelof will learn how to do program walkthroughs
>>>> and use the interactive prompt to solve things himself. I applaud the
>>>> patience some of you have ih hand-holding him. I don't have that
>>>> patience. I wish him to learn to fish.
>>> Hello Bob,
>>>
>>> Oke, I try to fish.
>>
>> Thank you.
>>
>>>
>>> When I do
>>>
>>> x= "a"
>>> y= int(x)
>>> Then I get ValueError.
>>>
>>> When I do
>>>
>>> x= 1.2
>>> y=int(x)
>>> No exception is raised.
>>
>> As Dave pointed out you switched from string to numeric. Try instead x =
>> '1.2'

Then I get a ValueError when I do y=int('1.2')
So it will Raise the error.

Roelof 		 	   		  

From fomcl at yahoo.com  Sat Sep 11 22:56:20 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 11 Sep 2010 13:56:20 -0700 (PDT)
Subject: [Tutor] design question
In-Reply-To: <201009111840.18307.steve@pearwood.info>
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
	<4C8A34C5.8060100@googlemail.com>
	<763847.51052.qm@web110703.mail.gq1.yahoo.com>
	<201009111840.18307.steve@pearwood.info>
Message-ID: <424945.64697.qm@web110715.mail.gq1.yahoo.com>

Hi Jan and Steven,

Thanks a lot for your valuable comments. I greatly appreciate you looking into 
it.

Steven, you recommend to <<Don't be too hung up about "design patterns">>. On 
one website it was mentioned that "To a young boy with a hammer, everything 
looks like a nail". Which meant to say that just because you CAN use a design 
pattern, it doesn't mean you SHOULD. This corresponds with your advice!

 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: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Sent: Sat, September 11, 2010 10:40:17 AM
Subject: Re: [Tutor] design question

On Sat, 11 Sep 2010 12:11:37 am Albert-Jan Roskam wrote:

> Inside my program I have to keep a list of all the image files that
> are scheduled for data entry. 

Sounds like you need to keep a list of all the image files that are 
scheduled for data entry then.


> The main purpose is to be able to read 
> in the image files one by one. Another one of the purposes of this
> list is to show some information on the title bar. 

No it isn't. You don't need a list of image files in order to show "some 
information" in the title bar (unless that information is the list of 
files). From your earlier post, you want to show:

filename 23 of 245 (9.4%)

or similar. For that, all you need is three pieces of information:

* the name of the current file
* the number of the current file
* the total number of files

You don't need all 245 files for that.

I'm being pedantic here. Obviously you need the list of files 
*somewhere*, and you need it for other reasons, but you don't *need* a 
list of 243 files in order to show the name of one of them!

You may decide that it is *convenient* to give the function which 
changes the title bar access to the entire list, but it's not a 
*requirement*. Think about alternatives: 

def change_titlebar(name, count, total):
    template = "%s %d of %d (%.1f %%)"
    percentage = count*100.0/total
    title = template % (name, count, total, percentage)
    do_magic_with(title)  # whatever it takes to change the title

It doesn't need the entire list.


> Currently, my 
> program only has a 'next' button and the fact that implementing a
> 'previous' button is causing problems suggests to me that I have to
> look for a more fundamentally better solution.

Sounds to me that you *don't* want the iterator pattern. The iterator 
pattern generally means that you step forward through each item. If you 
want to advance backwards or forwards, something with random access is 
probably better. That would probably mean a list.

Don't be too hung up about "design patterns". Most design patterns just 
exist to work around limitations of the language, lack of power, or 
slavish devotion to object oriented programming when the problem is 
crying out for a functional or procedural solution. Don't be afraid to 
write functions instead of classes -- there's no need for a 
TitlebarManipulator class just to change the titlebar.

My solution would be to keep *two* pieces of information:

* the list of filenames;
* the current position in that list

Set the current position to 0, and have the Next button add one to the 
position and refresh the page, and Prev subtract one and refresh the 
page. Obviously you need code to ensure that the position doesn't go 
out of bounds, code to save the data in the fields, and so forth. The 
page refresh code should do something like:

* given the current position, extract the filename to use;
* change the title bar;
* open and display the appropriate image;
* pre-populate any fields;
etc.
        
Good luck!


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



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100911/867fefc8/attachment.html>

From wprins at gmail.com  Sun Sep 12 01:03:49 2010
From: wprins at gmail.com (Walter Prins)
Date: Sun, 12 Sep 2010 00:03:49 +0100
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W50890F99A08A8530C05C4BAE750@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<201009120403.43651.steve@pearwood.info>
	<SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>
	<201009120419.58043.steve@pearwood.info>
	<SNT118-W4AF02D84CED0B8CA3173FAE750@phx.gbl>
	<SNT118-W50890F99A08A8530C05C4BAE750@phx.gbl>
Message-ID: <AANLkTimVnddE9YB1BhAu1bMwP1pX1qLi+i46f_wd41aZ@mail.gmail.com>

Just a quick contribution for what it's worth: One of the subjects being
implicitly talked about here is "introspection" -- you may want to google
that and see else you can find. That said, a nice article covering some of
Python's introspection features is presented here on IBM's site:
http://www.ibm.com/developerworks/library/l-pyint.html

<http://www.ibm.com/developerworks/library/l-pyint.html>Actually any user
that's used to doing introspection in the Python shell already has that same
tool at their disposal for programmatic introspection, e.g. the dir()
method.  (This is covered in the above article.)

So, perhaps it's an idea to call dir() on a given object and see whether the
object provides the necessary methods to function, e.g. __iter__,
__delitem__, __setitem__ and friends?

Here's some code which constructs a class from scratch, which contains 2
member variables, which are made available via list indexing by implementing
__getitem__ and _setitem__ and shows how you can then use that object as if
it's a list, as least as far as the first 2 elements are concerned.  Also
does some interrogation with dir() at the end.

http://pastebin.com/rRZpbham

Hope that helps,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/b49b716c/attachment.html>

From steve at pearwood.info  Sun Sep 12 02:10:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 12 Sep 2010 10:10:53 +1000
Subject: [Tutor] recursive problem
In-Reply-To: <AANLkTimVnddE9YB1BhAu1bMwP1pX1qLi+i46f_wd41aZ@mail.gmail.com>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>
	<SNT118-W50890F99A08A8530C05C4BAE750@phx.gbl>
	<AANLkTimVnddE9YB1BhAu1bMwP1pX1qLi+i46f_wd41aZ@mail.gmail.com>
Message-ID: <201009121010.54124.steve@pearwood.info>

On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:

> So, perhaps it's an idea to call dir() on a given object and see
> whether the object provides the necessary methods to function, e.g.
> __iter__, __delitem__, __setitem__ and friends?

There's no need to do this:

attributes = dir(obj)
if '__iter__' in attributes and '__len__' in attributes:
    print "Quacks like a list"
else:
    print "Not like a list"


when you can do this:


if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
    print "Quacks like a list"
else:
    print "Not like a list"


or this:

try:
    obj.__iter__
    obj.__len__
except AttributeError:
    print "Not like a list"
else:
    print "Quacks like a list"


or even 

try:
    iter(obj)
    len(obj)
except TypeError:
    print "Not like a list"
else:
    print "Quacks like a list"


Where possible, the last version is to be preferred, because it doesn't 
care about internal details which might change.



-- 
Steven D'Aprano

From rwobben at hotmail.com  Sun Sep 12 09:59:44 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 07:59:44 +0000
Subject: [Tutor]  recursive problem
In-Reply-To: <SNT118-W65EA7D86EF3A88B7ABDDACAE760@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<SNT118-W50890F99A08A8530C05C4BAE750@phx.gbl>,
	<AANLkTimVnddE9YB1BhAu1bMwP1pX1qLi+i46f_wd41aZ@mail.gmail.com>,
	<201009121010.54124.steve@pearwood.info>,
	<SNT118-W65EA7D86EF3A88B7ABDDACAE760@phx.gbl>
Message-ID: <SNT118-W44DCAB4E34164A2561FE5DAE760@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: steve at pearwood.info
> Subject: RE: [Tutor] recursive problem
> Date: Sun, 12 Sep 2010 07:58:48 +0000
>
>
>
>
> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Sun, 12 Sep 2010 10:10:53 +1000
>> Subject: Re: [Tutor] recursive problem
>>
>> On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:
>>
>>> So, perhaps it's an idea to call dir() on a given object and see
>>> whether the object provides the necessary methods to function, e.g.
>>> __iter__, __delitem__, __setitem__ and friends?
>>
>> There's no need to do this:
>>
>> attributes = dir(obj)
>> if '__iter__' in attributes and '__len__' in attributes:
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> when you can do this:
>>
>>
>> if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
>> print "Quacks like a list"
>> else:
>> print "Not like a list"
>>
>>
>> or this:
>>
>> try:
>> obj.__iter__
>> obj.__len__
>> except AttributeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> or even
>>
>> try:
>> iter(obj)
>> len(obj)
>> except TypeError:
>> print "Not like a list"
>> else:
>> print "Quacks like a list"
>>
>>
>> Where possible, the last version is to be preferred, because it doesn't
>> care about internal details which might change.
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Oke,

This is to far for me.
Im only at chapter 11 and this stuff will be in chapter 13 and further.

Roelof 		 	   		  

From rwobben at hotmail.com  Sun Sep 12 13:15:04 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 11:15:04 +0000
Subject: [Tutor] tree problem
Message-ID: <SNT118-W128EF356300115600F196AE760@phx.gbl>



Hello, 

I have this problem.

Write a program named litter.py that creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default). 

So I change the example to this :

def traverse(path, s='.\n', f=0, d=0):
path2file = os.path.join(path) *** pathfile contains the path 
if os.path.isdir(path2file): **** if pathfile is a dir.
d += 1 ***** the is one more directory
if getdirlist(path2file): ****** if the outcome of getdirlist is the same as the current directory
s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
else:
f += 1 ****** else f (number of files increases with 1 
return s, f, d ****** return s , numbers of files and the number of directories.


When I try to make it run I get this message :

File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in traverse
if os.path.isdir(path2file):
File "C:\Python27\lib\genericpath.py", line 44, in isdir
return stat.S_ISDIR(st.st_mode)
File "C:\Python27\lib\stat.py", line 41, in S_ISDIR
return S_IFMT(mode) == S_IFDIR
RuntimeError: maximum recursion depth exceeded

I can't see why this happens.
I know I have to fish but I can't see what's wrong here.
So I hope someone can learn how to fish here.

Roelof 		 	   		  

From evert.rol at gmail.com  Sun Sep 12 13:29:12 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sun, 12 Sep 2010 13:29:12 +0200
Subject: [Tutor] tree problem
In-Reply-To: <SNT118-W128EF356300115600F196AE760@phx.gbl>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
Message-ID: <8987E8B2-12B6-490A-BD86-9811CEFF4500@gmail.com>

> Write a program named litter.py that creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default). 
> 
> So I change the example to this :
> 
> def traverse(path, s='.\n', f=0, d=0):
> path2file = os.path.join(path) *** pathfile contains the path 
> if os.path.isdir(path2file): **** if pathfile is a dir.
> d += 1 ***** the is one more directory
> if getdirlist(path2file): ****** if the outcome of getdirlist is the same as the current directory
> s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
> else:
> f += 1 ****** else f (number of files increases with 1 
> return s, f, d ****** return s , numbers of files and the number of directories.

That can't be a valid program: no indentation, comments not preceded by a comment mark (#), and getdirlist is nowhere defined afaics. While probably anyone can understand what's the real code of the above snippet, it doesn't help putting non-valid code like this in your email. If you can directly copy-paste code (plain text), that is almost always better.


> When I try to make it run I get this message :
> 
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
> s, f, d = traverse(path2file, '| ' + s, f, d)
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in traverse
> if os.path.isdir(path2file):
> File "C:\Python27\lib\genericpath.py", line 44, in isdir
> return stat.S_ISDIR(st.st_mode)
> File "C:\Python27\lib\stat.py", line 41, in S_ISDIR
> return S_IFMT(mode) == S_IFDIR
> RuntimeError: maximum recursion depth exceeded
> 
> I can't see why this happens.
> I know I have to fish but I can't see what's wrong here.
> So I hope someone can learn how to fish here.

Fishing is debugging. You could use the logging module for that, but assuming you're not familiar with that, litter your program with print statements, and print out the value of the various variables at certain points in your program (it helps putting a short string in the print statement as well, so you know which print statement print where. Eg, print '1:', s, f, d; and then a few lines below, print '2:', s, f, d).
Having done that (you will get a lot of output), try to follow the logic of the program and see why things happen the way they do. In this case, why you keep spiraling in and never break out of your recursion. Then, step by step, you can try and change or add statements so you actually find a way to break out the recursion.

  Evert


From lie.1296 at gmail.com  Sun Sep 12 13:54:12 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 12 Sep 2010 21:54:12 +1000
Subject: [Tutor] tree problem
In-Reply-To: <SNT118-W128EF356300115600F196AE760@phx.gbl>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
Message-ID: <i6if12$tmu$1@dough.gmane.org>

On 09/12/10 21:15, Roelof Wobben wrote:
> 
> 
> Hello, 
> 
> I have this problem.
> 
> Write a program named litter.py that creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default). 

By default, Python has a recursion limit of 1000 deep; that is, your
function is calling itself 1000 times without returning.

In this case, the only reason why you hit the recursion limit is if you
have a directory which is 1000 deep (quite unlikely, Windows has a
directory depth limit much lower than that).

Or your function somehow never returns, in a typical recursive function,
it's usually because you have problem in the precondition.


From rwobben at hotmail.com  Sun Sep 12 15:02:05 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 13:02:05 +0000
Subject: [Tutor] tree problem
In-Reply-To: <8987E8B2-12B6-490A-BD86-9811CEFF4500@gmail.com>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>,
	<8987E8B2-12B6-490A-BD86-9811CEFF4500@gmail.com>
Message-ID: <SNT118-W61B4C9E963663161BAE5BCAE760@phx.gbl>




----------------------------------------
> Subject: Re: [Tutor] tree problem
> From: evert.rol at gmail.com
> Date: Sun, 12 Sep 2010 13:29:12 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com
>
>> Write a program named litter.py that creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default).
>>
>> So I change the example to this :
>>
>> def traverse(path, s='.\n', f=0, d=0):
>> path2file = os.path.join(path) *** pathfile contains the path
>> if os.path.isdir(path2file): **** if pathfile is a dir.
>> d += 1 ***** the is one more directory
>> if getdirlist(path2file): ****** if the outcome of getdirlist is the same as the current directory
>> s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
>> else:
>> f += 1 ****** else f (number of files increases with 1
>> return s, f, d ****** return s , numbers of files and the number of directories.
>
> That can't be a valid program: no indentation, comments not preceded by a comment mark (#), and getdirlist is nowhere defined afaics. While probably anyone can understand what's the real code of the above snippet, it doesn't help putting non-valid code like this in your email. If you can directly copy-paste code (plain text), that is almost always better.
>
>
>> When I try to make it run I get this message :
>>
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
>> s, f, d = traverse(path2file, '| ' + s, f, d)
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
>> s, f, d = traverse(path2file, '| ' + s, f, d)
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 31, in traverse
>> s, f, d = traverse(path2file, '| ' + s, f, d)
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in traverse
>> if os.path.isdir(path2file):
>> File "C:\Python27\lib\genericpath.py", line 44, in isdir
>> return stat.S_ISDIR(st.st_mode)
>> File "C:\Python27\lib\stat.py", line 41, in S_ISDIR
>> return S_IFMT(mode) == S_IFDIR
>> RuntimeError: maximum recursion depth exceeded
>>
>> I can't see why this happens.
>> I know I have to fish but I can't see what's wrong here.
>> So I hope someone can learn how to fish here.
>
> Fishing is debugging. You could use the logging module for that, but assuming you're not familiar with that, litter your program with print statements, and print out the value of the various variables at certain points in your program (it helps putting a short string in the print statement as well, so you know which print statement print where. Eg, print '1:', s, f, d; and then a few lines below, print '2:', s, f, d).
> Having done that (you will get a lot of output), try to follow the logic of the program and see why things happen the way they do. In this case, why you keep spiraling in and never break out of your recursion. Then, step by step, you can try and change or add statements so you actually find a way to break out the recursion.
>
> Evert
>
 
Hello Evert.
 
Sorry but the change to plain text destroyed also this.
 
What I have it this.
 
def getdirlist(path):
    dirlist = os.listdir(path)
    dirlist = [name for name in dirlist if name[0] != '.']
    dirlist.sort()
    return dirlist

def traverse(path, s='.\n', f=0, d=0):
    dirlist = getdirlist(path)
    for file in enumerate(dirlist):
        print file
        path2file = os.path.join(path)
        if os.path.isdir(path2file):
            d += 1
            if getdirlist(path2file):
                print path2file
            myfile = open ('trash.txt', 'w')
            myfile.close () 
    return s, f, d
 
The file is made. Now find out why it doesn't go into the next level.
With this : s, f, d = traverse(path2file, '|   ' + s, f, d) I goes into a loop which never ends.
 
Roelof


  		 	   		  

From joel.goldstick at gmail.com  Sun Sep 12 15:08:18 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 12 Sep 2010 09:08:18 -0400
Subject: [Tutor] tree problem
In-Reply-To: <i6if12$tmu$1@dough.gmane.org>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
	<i6if12$tmu$1@dough.gmane.org>
Message-ID: <AANLkTim-gyESP22c69kc=8skfPsfcLDNRNg9CB07RZaG@mail.gmail.com>

On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan <lie.1296 at gmail.com> wrote:

> On 09/12/10 21:15, Roelof Wobben wrote:
> >
> >
> > Hello,
> >
> > I have this problem.
> >
> > Write a program named litter.py that creates an empty file named
> trash.txt in each subdirectory of a directory tree given the root of the
> tree as an argument (or the current directory as a default).
>
> By default, Python has a recursion limit of 1000 deep; that is, your
> function is calling itself 1000 times without returning.
>
> In this case, the only reason why you hit the recursion limit is if you
> have a directory which is 1000 deep (quite unlikely, Windows has a
> directory depth limit much lower than that).
>
> Or your function somehow never returns, in a typical recursive function,
> it's usually because you have problem in the precondition.
>
> You really have two problems here:

1. You need to know how to write an empty file with the name litter.py.  You
should probably write a function to see if you can do that.  That's pretty
easy

2. You need to traverse a tree.  I see you are using os module.  You should
try help(os) while in your python shell to learn what methods are
available.  Traversing a tree is also sometimes called 'walking'

good luck


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/04bc4960/attachment-0001.html>

From joel.goldstick at gmail.com  Sun Sep 12 15:46:08 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 12 Sep 2010 09:46:08 -0400
Subject: [Tutor] tree problem
In-Reply-To: <SNT118-W30E91671E02CF5C9103E64AE760@phx.gbl>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
	<i6if12$tmu$1@dough.gmane.org>
	<AANLkTim-gyESP22c69kc=8skfPsfcLDNRNg9CB07RZaG@mail.gmail.com>
	<SNT118-W30E91671E02CF5C9103E64AE760@phx.gbl>
Message-ID: <AANLkTinWPHCLf0cOLUcsXYM9EStSvJLPxXD5ZTZzU8vT@mail.gmail.com>

On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
> ________________________________
> > Date: Sun, 12 Sep 2010 09:08:18 -0400
> > From: joel.goldstick at gmail.com
> > To: tutor at python.org
>
> > Subject: Re: [Tutor] tree problem
> >
> >
> >
> > On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
> > > wrote:
> > On 09/12/10 21:15, Roelof Wobben wrote:
> > >
> > >
> > > Hello,
> > >
> > > I have this problem.
> > >
> > > Write a program named litter.py that creates an empty file named
> > trash.txt in each subdirectory of a directory tree given the root of
> > the tree as an argument (or the current directory as a default).
> >
> > By default, Python has a recursion limit of 1000 deep; that is, your
> > function is calling itself 1000 times without returning.
> >
> > In this case, the only reason why you hit the recursion limit is if you
> > have a directory which is 1000 deep (quite unlikely, Windows has a
> > directory depth limit much lower than that).
> >
> > Or your function somehow never returns, in a typical recursive function,
> > it's usually because you have problem in the precondition.
> >
> > You really have two problems here:
> >
> > 1. You need to know how to write an empty file with the name
> > litter.py. You should probably write a function to see if you can do
> > that. That's pretty easy
> >
> > 2. You need to traverse a tree. I see you are using os module. You
> > should try help(os) while in your python shell to learn what methods
> > are available. Traversing a tree is also sometimes called 'walking'
> >
> > good luck
> >
> >
> > --
> > Joel Goldstick
> >
> >
> > _______________________________________________ Tutor maillist -
>
> > Tutor at python.org To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> Hello Joel.
>
> Youre right.
>  Problem 1 is easily solved by using myfile = open ('filename', 'w')
> followed by myfile.close()
>
> Problem 2 is more difficult.
>
> I have to use recursion and as example the source of the tree command in
> linux is given.
> The traverse module looks like this :
>
>  def traverse(path, prefix='|--', s='.\n', f=0, d=0):
>

what's up with the prefix???


>     dirlist = getdirlist(path)
>     for num, file in enumerate(dirlist):
>

why are you using enumerate?  it gives you num which you never use
 for file in dirlist gives what you seem to be using

>         lastprefix = prefix[:-3] + '``--'
>         dirsize = len(dirlist)
>         if num < dirsize - 1:
>             s += '%s %s\n' % (prefix, file)
>         else:
>             s += '%s %s\n' % (lastprefix, file)
>         path2file = os.path.join(path, file)
>
>         if os.path.isdir(path2file):
>             d += 1
>             if getdirlist(path2file):
>                 s, f, d = traverse(path2file, '|   ' + prefix, s, f, d)
>         else:
>             f += 1
>     return s, f, d
>
> For me it looks like the pathfile = os.path.join(path, file)
> and then the s.f.d. rule take care that a subdir is entered.
>
what are s.f.d.  Can you use more descriptive names

>
> Am I right on this ?
>
> Roelof
>
>
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/6884b93e/attachment.html>

From rwobben at hotmail.com  Sun Sep 12 16:48:07 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 14:48:07 +0000
Subject: [Tutor] tree problem
In-Reply-To: <AANLkTinWPHCLf0cOLUcsXYM9EStSvJLPxXD5ZTZzU8vT@mail.gmail.com>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>,
	<i6if12$tmu$1@dough.gmane.org>,
	<AANLkTim-gyESP22c69kc=8skfPsfcLDNRNg9CB07RZaG@mail.gmail.com>,
	<SNT118-W30E91671E02CF5C9103E64AE760@phx.gbl>,
	<AANLkTinWPHCLf0cOLUcsXYM9EStSvJLPxXD5ZTZzU8vT@mail.gmail.com>
Message-ID: <SNT118-W57274EAF6D6F587F765C04AE760@phx.gbl>




________________________________
> Date: Sun, 12 Sep 2010 09:46:08 -0400
> From: joel.goldstick at gmail.com
> To: tutor at python.org
> Subject: Re: [Tutor] tree problem
>
>
>
> On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben
>> wrote:
>
>
> ________________________________
>> Date: Sun, 12 Sep 2010 09:08:18 -0400
>> From: joel.goldstick at gmail.com
>> To: tutor at python.org
>
>> Subject: Re: [Tutor] tree problem
>>
>>
>>
>> On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
>>> wrote:
>> On 09/12/10 21:15, Roelof Wobben wrote:
>>>
>>>
>>> Hello,
>>>
>>> I have this problem.
>>>
>>> Write a program named litter.py that creates an empty file named
>> trash.txt in each subdirectory of a directory tree given the root of
>> the tree as an argument (or the current directory as a default).
>>
>> By default, Python has a recursion limit of 1000 deep; that is, your
>> function is calling itself 1000 times without returning.
>>
>> In this case, the only reason why you hit the recursion limit is if you
>> have a directory which is 1000 deep (quite unlikely, Windows has a
>> directory depth limit much lower than that).
>>
>> Or your function somehow never returns, in a typical recursive function,
>> it's usually because you have problem in the precondition.
>>
>> You really have two problems here:
>>
>> 1. You need to know how to write an empty file with the name
>> litter.py. You should probably write a function to see if you can do
>> that. That's pretty easy
>>
>> 2. You need to traverse a tree. I see you are using os module. You
>> should try help(os) while in your python shell to learn what methods
>> are available. Traversing a tree is also sometimes called 'walking'
>>
>> good luck
>>
>>
>> --
>> Joel Goldstick
>>
>>
>> _______________________________________________ Tutor maillist -
>
>> Tutor at python.org To unsubscribe or change
> subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Hello Joel.
>
> Youre right.
> Problem 1 is easily solved by using myfile = open ('filename', 'w')
> followed by myfile.close()
>
> Problem 2 is more difficult.
>
> I have to use recursion and as example the source of the tree command
> in linux is given.
> The traverse module looks like this :
>
> def traverse(path, prefix='|--', s='.\n', f=0, d=0):
>
> what's up with the prefix???
>
> dirlist = getdirlist(path)
> for num, file in enumerate(dirlist):
>
> why are you using enumerate? it gives you num which you never use
> for file in dirlist gives what you seem to be using
> lastprefix = prefix[:-3] + '``--'
> dirsize = len(dirlist)
> if num < dirsize - 1:
> s += '%s %s\n' % (prefix, file)
> else:
> s += '%s %s\n' % (lastprefix, file)
> path2file = os.path.join(path, file)
>
> if os.path.isdir(path2file):
> d += 1
> if getdirlist(path2file):
> s, f, d = traverse(path2file, '| ' + prefix, s, f, d)
> else:
> f += 1
> return s, f, d
>
> For me it looks like the pathfile = os.path.join(path, file)
> and then the s.f.d. rule take care that a subdir is entered.
> what are s.f.d. Can you use more descriptive names
>
> Am I right on this ?
>
> Roelof
>
>
>
>
>
> --
> Joel Goldstick
>
>
> _______________________________________________ Tutor maillist -
> Tutor at python.org To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I solved this by this programm :
 
import os
import sys

def getroot():
    if len(sys.argv) == 1:
        path = ''
    else:
        path = sys.argv[1]
    if os.path.isabs(path):
        tree_root = path
    else:
        tree_root = os.path.join(os.getcwd(), path)
    return tree_root

def getdirlist(path):
    dirlist = os.listdir(path)
    dirlist = [name for name in dirlist if name[0] != '.']
    dirlist.sort()
    return dirlist

def traverse(path, s='.\n', f=0, d=0):
    file = os.path.join(path,'trash.txt')
    myfile = open (file, 'w')
    myfile.close()
    dirlist = getdirlist(path)
    for num, file in enumerate(dirlist):
        dirsize = len(dirlist)
        if num < dirsize - 1:
            s += '%s \n' % (file)
        else:
            s += '%s \n' % (file)
        path2file = os.path.join(path, file)
        if os.path.isdir(path2file):
            d += 1
            s, f, d = traverse(path2file, '|   ' + s, f, d)
    return s,f,d

if __name__ == '__main__':
    root =  getroot()
    tree_str, files, dirs = traverse(root)

 
Roelof

  		 	   		  

From asmosis.asterix at gmail.com  Sun Sep 12 17:17:02 2010
From: asmosis.asterix at gmail.com (Daniel)
Date: Sun, 12 Sep 2010 18:17:02 +0300
Subject: [Tutor] Function object
In-Reply-To: <AANLkTi=SyrK2aa11Svy8v1mGcNQ5-oQaEnOUaUcMQ-Tv@mail.gmail.com>
References: <AANLkTinBMvAPoyav_G22HfO3YBhyn1a8Defu_RZMUeM5@mail.gmail.com>
	<i53o9j$n2n$1@dough.gmane.org>
	<AANLkTi=SyrK2aa11Svy8v1mGcNQ5-oQaEnOUaUcMQ-Tv@mail.gmail.com>
Message-ID: <AANLkTi=3NaZX=EB1Dqa8U9=dAaHu6_ctXfzHU5uTBE-x@mail.gmail.com>

What can I say except, thanks so much everyone for taking your time and
writing me an explication. I finally understood what function objects are.
Thanks, really thanks for  helping me out. I wish everyone the best.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/6df246b4/attachment.html>

From ranceh at gmail.com  Sun Sep 12 17:55:27 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 10:55:27 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
Message-ID: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>

I'm not sure if this is the right forum for this or not, if there is a
better place to ask this question please let me know and I'll re-post
elsewhere.

I'm using python v3.1 and the py-postgresql v1.0.1 module located at
http://python.projects.postgresql.org/docs/1.0/

I'm using prepared sql statements like:

insertnote = db.prepare("INSERT INTO business.to_do_list (note) VALUES ($1)")
delete_note = db.prepare("DELETE FROM business.to_do_list WHERE item = $1")

so far so good, everything is working well and I understand whats going on.

But I have a situation where I want to count the number of notes in
the database, and if 0 do something, and if 1 do something else.
I have another occasion where I only want the first few records to be returned.

So for testing the idea I did this:

get_todo = db.prepare("SELECT note FROM business.to_do_list ORDER BY item")
get_todo_limit = db.prepare("SELECT note FROM business.to_do_list
ORDER BY item LIMIT 10")
get_todo_count = db.prepare("SELECT COUNT(note) AS notecount FROM
business.to_do_list")

I *think* there is a better way to do this, but I'm not seeing it in
the documentation, or its there and I'm not understanding it
correctly.

I suspect that the get_todo_count statement is not required at all.  I
have a hunch, although I can't prove yet that the result set returned
by the SQL SELECT statement will have some way to access the record
count directly

Something like this:

m = get_todo_limit()

if m.count == 0:
    do stuff
else:
    do other stuff

I can't quite narrow this down.  I'm sure its possible, It likely
depends on what python variable type is used by the py-postgresql
module, but I'm not seeing this in the docs.

Second question is more of a performance question:

I don't suspect a "large" # of items in the to_do list, so I *think*
that it would be better to just have one SQL statement and then loop
through the results 10 times to get the first few records rather than
having a seperate sql statement as I have shown here.  I'm too new at
python to have a feel for the *right* way to go about this part

Could someone point me in the right direction please?

From joel.goldstick at gmail.com  Sun Sep 12 17:59:07 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 12 Sep 2010 11:59:07 -0400
Subject: [Tutor] tree problem
In-Reply-To: <SNT118-W57274EAF6D6F587F765C04AE760@phx.gbl>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
	<i6if12$tmu$1@dough.gmane.org>
	<AANLkTim-gyESP22c69kc=8skfPsfcLDNRNg9CB07RZaG@mail.gmail.com>
	<SNT118-W30E91671E02CF5C9103E64AE760@phx.gbl>
	<AANLkTinWPHCLf0cOLUcsXYM9EStSvJLPxXD5ZTZzU8vT@mail.gmail.com>
	<SNT118-W57274EAF6D6F587F765C04AE760@phx.gbl>
Message-ID: <AANLkTin6aXyS6S49jMj_cQsSd93qz4JAUeHNWTPPw_=_@mail.gmail.com>

On Sun, Sep 12, 2010 at 10:48 AM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
>
> ________________________________
> > Date: Sun, 12 Sep 2010 09:46:08 -0400
> > From: joel.goldstick at gmail.com
> > To: tutor at python.org
> > Subject: Re: [Tutor] tree problem
> >
> >
> >
> > On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben
> >> wrote:
> >
> >
> > ________________________________
> >> Date: Sun, 12 Sep 2010 09:08:18 -0400
> >> From: joel.goldstick at gmail.com
> >> To: tutor at python.org
> >
> >> Subject: Re: [Tutor] tree problem
> >>
> >>
> >>
> >> On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
> >>> wrote:
> >> On 09/12/10 21:15, Roelof Wobben wrote:
> >>>
> >>>
> >>> Hello,
> >>>
> >>> I have this problem.
> >>>
> >>> Write a program named litter.py that creates an empty file named
> >> trash.txt in each subdirectory of a directory tree given the root of
> >> the tree as an argument (or the current directory as a default).
> >>
> >> By default, Python has a recursion limit of 1000 deep; that is, your
> >> function is calling itself 1000 times without returning.
> >>
> >> In this case, the only reason why you hit the recursion limit is if you
> >> have a directory which is 1000 deep (quite unlikely, Windows has a
> >> directory depth limit much lower than that).
> >>
> >> Or your function somehow never returns, in a typical recursive function,
> >> it's usually because you have problem in the precondition.
> >>
> >> You really have two problems here:
> >>
> >> 1. You need to know how to write an empty file with the name
> >> litter.py. You should probably write a function to see if you can do
> >> that. That's pretty easy
> >>
> >> 2. You need to traverse a tree. I see you are using os module. You
> >> should try help(os) while in your python shell to learn what methods
> >> are available. Traversing a tree is also sometimes called 'walking'
> >>
> >> good luck
> >>
> >>
> >> --
> >> Joel Goldstick
> >>
> >>
> >> _______________________________________________ Tutor maillist -
> >
> >> Tutor at python.org To unsubscribe or change
> > subscription options:
> >> http://mail.python.org/mailman/listinfo/tutor
> >
> > Hello Joel.
> >
> > Youre right.
> > Problem 1 is easily solved by using myfile = open ('filename', 'w')
> > followed by myfile.close()
> >
> > Problem 2 is more difficult.
> >
> > I have to use recursion and as example the source of the tree command
> > in linux is given.
> > The traverse module looks like this :
> >
> > def traverse(path, prefix='|--', s='.\n', f=0, d=0):
> >
> > what's up with the prefix???
> >
> > dirlist = getdirlist(path)
> > for num, file in enumerate(dirlist):
> >
> > why are you using enumerate? it gives you num which you never use
> > for file in dirlist gives what you seem to be using
> > lastprefix = prefix[:-3] + '``--'
> > dirsize = len(dirlist)
> > if num < dirsize - 1:
> > s += '%s %s\n' % (prefix, file)
> > else:
> > s += '%s %s\n' % (lastprefix, file)
> > path2file = os.path.join(path, file)
> >
> > if os.path.isdir(path2file):
> > d += 1
> > if getdirlist(path2file):
> > s, f, d = traverse(path2file, '| ' + prefix, s, f, d)
> > else:
> > f += 1
> > return s, f, d
> >
> > For me it looks like the pathfile = os.path.join(path, file)
> > and then the s.f.d. rule take care that a subdir is entered.
> > what are s.f.d. Can you use more descriptive names
> >
> > Am I right on this ?
> >
> > Roelof
> >
> >
> >
> >
> >
> > --
> > Joel Goldstick
> >
> >
> > _______________________________________________ Tutor maillist -
> > Tutor at python.org To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> Hello,
>
> I solved this by this programm :
>
> import os
> import sys
>
> def getroot():
>    if len(sys.argv) == 1:
>        path = ''
>    else:
>        path = sys.argv[1]
>    if os.path.isabs(path):
>        tree_root = path
>    else:
>        tree_root = os.path.join(os.getcwd(), path)
>    return tree_root
>
> def getdirlist(path):
>    dirlist = os.listdir(path)
>     dirlist = [name for name in dirlist if name[0] != '.']
>    dirlist.sort()
>    return dirlist
>
> def traverse(path, s='.\n', f=0, d=0):
>    file = os.path.join(path,'trash.txt')
>    myfile = open (file, 'w')
>    myfile.close()
>     dirlist = getdirlist(path)
>    for num, file in enumerate(dirlist):
>         dirsize = len(dirlist)
>        if num < dirsize - 1:
>             s += '%s \n' % (file)
>        else:
>             s += '%s \n' % (file)
>         path2file = os.path.join(path, file)
>        if os.path.isdir(path2file):
>            d += 1
>             s, f, d = traverse(path2file, '|   ' + s, f, d)
>    return s,f,d
>
> if __name__ == '__main__':
>    root =  getroot()
>    tree_str, files, dirs = traverse(root)
>
>
> Roelof
>
>
Good for you.  Some questions:

   What do you mean to be happening here:

       if num < dirsize - 1:
            s += '%s \n' % (file)
       else:
            s += '%s \n' % (file)

it does the same thing in either case

What exactly does s do for you?

You use the first parameter 'path' in your calls to traverse, but  I don't
see how you are using f or d anywhere either
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/7aaf0e33/attachment.html>

From rwobben at hotmail.com  Sun Sep 12 19:52:07 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 17:52:07 +0000
Subject: [Tutor] tree problem
In-Reply-To: <AANLkTimOkUq+3sk=rgtkaih0S8tBV+ThdYDk5dsr48yz@mail.gmail.com>
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>,
	<i6if12$tmu$1@dough.gmane.org>,
	<AANLkTim-gyESP22c69kc=8skfPsfcLDNRNg9CB07RZaG@mail.gmail.com>,
	<SNT118-W30E91671E02CF5C9103E64AE760@phx.gbl>,
	<AANLkTinWPHCLf0cOLUcsXYM9EStSvJLPxXD5ZTZzU8vT@mail.gmail.com>,
	<SNT118-W57274EAF6D6F587F765C04AE760@phx.gbl>,
	<AANLkTin6aXyS6S49jMj_cQsSd93qz4JAUeHNWTPPw_=_@mail.gmail.com>,
	<SNT118-W15EFEE60936226CA138705AE760@phx.gbl>,
	<AANLkTimOkUq+3sk=rgtkaih0S8tBV+ThdYDk5dsr48yz@mail.gmail.com>
Message-ID: <SNT118-W5600F1F76FFDB8403A018EAE760@phx.gbl>




________________________________
> Date: Sun, 12 Sep 2010 13:40:09 -0400
> Subject: Re: [Tutor] tree problem
> From: joel.goldstick at gmail.com
> To: rwobben at hotmail.com
>
>
>
> On Sun, Sep 12, 2010 at 1:20 PM, Roelof Wobben
>> wrote:
>
>
>
> ________________________________
>> Date: Sun, 12 Sep 2010 11:59:07 -0400
>> From: joel.goldstick at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] tree problem
>>
>>
>>
>> On Sun, Sep 12, 2010 at 10:48 AM, Roelof Wobben
>>> wrote:
>>
>>
>>
>> ________________________________
>>> Date: Sun, 12 Sep 2010 09:46:08 -0400
>>> From: joel.goldstick at gmail.com
>>> To: tutor at python.org
>>> Subject: Re: [Tutor] tree problem
>>>
>>>
>>>
>>> On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben
>>>> wrote:
>>>
>>>
>>> ________________________________
>>>> Date: Sun, 12 Sep 2010 09:08:18 -0400
>>>> From: joel.goldstick at gmail.com
>>>> To: tutor at python.org
>>>
>>>> Subject: Re: [Tutor] tree problem
>>>>
>>>>
>>>>
>>>> On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
>>>>> wrote:
>>>> On 09/12/10 21:15, Roelof Wobben wrote:
>>>>>
>>>>>
>>>>> Hello,
>>>>>
>>>>> I have this problem.
>>>>>
>>>>> Write a program named litter.py that creates an empty file named
>>>> trash.txt in each subdirectory of a directory tree given the root of
>>>> the tree as an argument (or the current directory as a default).
>>>>
>>>> By default, Python has a recursion limit of 1000 deep; that is, your
>>>> function is calling itself 1000 times without returning.
>>>>
>>>> In this case, the only reason why you hit the recursion limit is if you
>>>> have a directory which is 1000 deep (quite unlikely, Windows has a
>>>> directory depth limit much lower than that).
>>>>
>>>> Or your function somehow never returns, in a typical recursive function,
>>>> it's usually because you have problem in the precondition.
>>>>
>>>> You really have two problems here:
>>>>
>>>> 1. You need to know how to write an empty file with the name
>>>> litter.py. You should probably write a function to see if you can do
>>>> that. That's pretty easy
>>>>
>>>> 2. You need to traverse a tree. I see you are using os module. You
>>>> should try help(os) while in your python shell to learn what methods
>>>> are available. Traversing a tree is also sometimes called 'walking'
>>>>
>>>> good luck
>>>>
>>>>
>>>> --
>>>> Joel Goldstick
>>>>
>>>>
>>>> _______________________________________________ Tutor maillist -
>>>
>>>> Tutor at python.org To unsubscribe or change
>>> subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>> Hello Joel.
>>>
>>> Youre right.
>>> Problem 1 is easily solved by using myfile = open ('filename', 'w')
>>> followed by myfile.close()
>>>
>>> Problem 2 is more difficult.
>>>
>>> I have to use recursion and as example the source of the tree command
>>> in linux is given.
>>> The traverse module looks like this :
>>>
>>> def traverse(path, prefix='|--', s='.\n', f=0, d=0):
>>>
>>> what's up with the prefix???
>>>
>>> dirlist = getdirlist(path)
>>> for num, file in enumerate(dirlist):
>>>
>>> why are you using enumerate? it gives you num which you never use
>>> for file in dirlist gives what you seem to be using
>>> lastprefix = prefix[:-3] + '``--'
>>> dirsize = len(dirlist)
>>> if num < dirsize - 1:
>>> s += '%s %s\n' % (prefix, file)
>>> else:
>>> s += '%s %s\n' % (lastprefix, file)
>>> path2file = os.path.join(path, file)
>>>
>>> if os.path.isdir(path2file):
>>> d += 1
>>> if getdirlist(path2file):
>>> s, f, d = traverse(path2file, '| ' + prefix, s, f, d)
>>> else:
>>> f += 1
>>> return s, f, d
>>>
>>> For me it looks like the pathfile = os.path.join(path, file)
>>> and then the s.f.d. rule take care that a subdir is entered.
>>> what are s.f.d. Can you use more descriptive names
>>>
>>> Am I right on this ?
>>>
>>> Roelof
>>>
>>>
>>>
>>>
>>>
>>> --
>>> Joel Goldstick
>>>
>>>
>>> _______________________________________________ Tutor maillist -
>>> Tutor at python.org To unsubscribe or change
>> subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> Hello,
>>
>> I solved this by this programm :
>>
>> import os
>> import sys
>>
>> def getroot():
>> if len(sys.argv) == 1:
>> path = ''
>> else:
>> path = sys.argv[1]
>> if os.path.isabs(path):
>> tree_root = path
>> else:
>> tree_root = os.path.join(os.getcwd(), path)
>> return tree_root
>>
>> def getdirlist(path):
>> dirlist = os.listdir(path)
>> dirlist = [name for name in dirlist if name[0] != '.']
>> dirlist.sort()
>> return dirlist
>>
>> def traverse(path, s='.\n', f=0, d=0):
>> file = os.path.join(path,'trash.txt')
>> myfile = open (file, 'w')
>> myfile.close()
>> dirlist = getdirlist(path)
>> for num, file in enumerate(dirlist):
>> dirsize = len(dirlist)
>> if num < dirsize - 1:
>> s += '%s \n' % (file)
>> else:
>> s += '%s \n' % (file)
>> path2file = os.path.join(path, file)
>> if os.path.isdir(path2file):
>> d += 1
>> s, f, d = traverse(path2file, '| ' + s, f, d)
>> return s,f,d
>>
>> if __name__ == '__main__':
>> root = getroot()
>> tree_str, files, dirs = traverse(root)
>>
>>
>> Roelof
>>
>>
>> Good for you. Some questions:
>>
>> What do you mean to be happening here:
>>
>> if num < dirsize - 1:
>> s += '%s \n' % (file)
>> else:
>> s += '%s \n' % (file)
>>
>> it does the same thing in either case
>>
>> What exactly does s do for you?
>>
>> You use the first parameter 'path' in your calls to traverse, but I
>> don't see how you are using f or d anywhere either
>> --
>> Joel Goldstick
>>
>>
>> _______________________________________________ Tutor maillist -
>> Tutor at python.org To unsubscribe or change
> subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> Hello,
>
> Your right about this rule.
> The rule takes care about that the filename is printed with a newline.
>
> Correct, f,d and s were variables used by the tree programm and can all
> be deleted.
>
> Then the traverse function looks like this:
>
> def traverse(path):
> test = ""
> file = os.path.join(path,'trash.txt')
> myfile = open (file, 'w')
> myfile.close()
> dirlist = getdirlist(path)
> dirsize = len(dirlist)
> for num, file in enumerate(dirlist):
> path2file = os.path.join(path, file)
> if os.path.isdir(path2file):
> test = traverse(path2file)
> return
>
> Roelof
>
>
> or even this:
> def traverse(path):
> ## this does nothing test = ""
> file = os.path.join(path,'trash.txt')
> myfile = open (file, 'w')
> myfile.close()
> dirlist = getdirlist(path)
> dirsize = len(dirlist)
> ## no need for num or enumerate for num, file in enumerate(dirlist):
> for file in dirlist:
> path2file = os.path.join(path, file)
> if os.path.isdir(path2file):
> ## no need for test.. it holds non test = traverse(path2file)
> traverse(path2file)
> return
>
>
> good luck
> --
> Joel Goldstick
>
 
Oke, Thanks everybody for the help.
 
Roelof

  		 	   		  

From ranceh at gmail.com  Sun Sep 12 20:19:41 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 13:19:41 -0500
Subject: [Tutor] forcing hashlib to has string variables
Message-ID: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>

Everybody knows you don't store plain text passwords in a database,
you store hashes instead

consider:

userpass = getpass.getpass("User password? ")

encuserpass = hashlib.md5()

encuserpass.update(userpass)

del userpass


Now the documentation clearly states that if you are hashing a string
you need to covert it to bytes first with a line like this:

encuserpass.update(b"text string here")

The "b" in this syntax is a shortcut to converting the string to bytes
for hasing purposes.

which means that the first code snippet fails, since I didnt convert
the variable contents to bytes instead of text.

I didn't see an example that addresses hashing the string contents of
a variable.

Whats missing in the above example that makes hashing the contents of
a string variable work?

From rabidpoobear at gmail.com  Sun Sep 12 20:47:20 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 12 Sep 2010 13:47:20 -0500
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
Message-ID: <FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>

This is how I use it (untested)
Import hashlib
Print hashlib.md5("somestr").hexdigest()

Works fine without using binary string.


On Sep 12, 2010, at 1:19 PM, Rance Hall <ranceh at gmail.com> wrote:

> Everybody knows you don't store plain text passwords in a database,
> you store hashes instead
> 
> consider:
> 
> userpass = getpass.getpass("User password? ")
> 
> encuserpass = hashlib.md5()
> 
> encuserpass.update(userpass)
> 
> del userpass
> 
> 
> Now the documentation clearly states that if you are hashing a string
> you need to covert it to bytes first with a line like this:
> 
> encuserpass.update(b"text string here")
> 
> The "b" in this syntax is a shortcut to converting the string to bytes
> for hasing purposes.
> 
> which means that the first code snippet fails, since I didnt convert
> the variable contents to bytes instead of text.
> 
> I didn't see an example that addresses hashing the string contents of
> a variable.
> 
> Whats missing in the above example that makes hashing the contents of
> a string variable work?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From wallenpb at gmail.com  Sun Sep 12 20:52:27 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 12 Sep 2010 13:52:27 -0500
Subject: [Tutor] SOLVED: Re: Trapping HTTP Authentication Failure
In-Reply-To: <20100911184459.GE2670@cecilia>
References: <20100910191013.GE3330@cecilia>
	<AB1A6C6C-C468-4F11-9707-65410443E5BF@gmail.com>
	<20100911095821.GA2670@cecilia>
	<3BBCCBF4-2501-43BD-8C25-062C2C7C3DCE@gmail.com>
	<20100911113924.GB2670@cecilia>
	<9CE6B069-E836-4C2B-99C6-BDB229D70124@gmail.com>
	<20100911144813.GC2670@cecilia> <20100911181607.GD2670@cecilia>
	<20100911184459.GE2670@cecilia>
Message-ID: <AANLkTimpDU-hV1P2a2iVe7a_TECnGfrY9yxQLafvMcxH@mail.gmail.com>

Just in case it is not a known issue or well documented, do take the time if
you can to report it.  Especially since you have got the symptom isolated
and demonstrated that it is limited to a particular OS build.

http://docs.python.org/bugs.html


-Bill


On Sat, Sep 11, 2010 at 1:44 PM, Michael Powe <michael at trollope.org> wrote:

> Hello,
>
> It is bloody Winblows.  The script works as designed and traps the 401
> exception on my slackware box ... something in the implementation of
> urllib2 on Windoze is broken.  This has to be a known issue.  Just did
> not see it known anywhere.
>
> Thanks.
>
> mp
>
> On Sat, Sep 11, 2010 at 02:16:07PM -0400, Michael Powe wrote:
> > On Sat, Sep 11, 2010 at 10:48:13AM -0400, Michael Powe wrote:
> > > On Sat, Sep 11, 2010 at 02:25:24PM +0200, Evert Rol wrote:
> > > > <snip />
> > >
> > > > >> I'm not sure what you're exactly doing here, or what you're
> getting,
> > > > >> but I did get curious and dug around urllib2.py. Apparently, there
> is
> > > > >> a hardcoded 5 retries before the authentication really fails. So
> any
> > > > >> stack trace would be the normal stack trace times 5. Not the 30
> you
> > > > >> mentioned, but annoying enough anyway (I don't see how it would
> fail
> > > > >> for every element in the loop though. Once it raises an exception,
> > > > >> the program basically ends).
> >
> > > > > It never throws an exception.  Or, if it does, something about the
> way
> > > > > I'm calling suppresses it.  IOW, I can put in a bogus credential
> and
> > > > > start the script and sit here for 5 minutes and see nothing.  Then
> ^C
> > > > > and I get a huge stacktrace that shows the repeated calls.  After
> the
> > > > > timeout on one element in the list, it goes to the next element,
> times
> > > > > out, goes to the next.
> >
> > Hello,
> >
> > More experimentation revealed that one problem was testing the script
> > in Idle.  Idle does something to suppress the script failure for that
> > particular case (IOW, it correctly returns HTTPError for things like
> > '404' and URLError for things like a bad domain name).
> >
> > When I run the script from the command line (cmd), it actually ignores
> > the '5' retry limit, seemingly.  I added another catch block:
> >
> > except Exception as e:
> >          print "exception: ",e
> >
> > That prints out "exception: maximum recursion depth exceeded."
> >
> > I wonder if there is something hinky in Windows that is causing this
> > to happen.
> >
> > Thanks.
> >
> > mp
> >
> > > > Ok, now I had to try and recreate something myself. So my processData
> is:
> > >
> > > > def processData(f):
> > > >    global overview_url
> > > >    overview_url = baseurl + f
> > > >    getData(authHeaders)
> > > >
> > > > (f being a filename, out of a list of many). Other code same as
> yours.
> > >
> > > > It definitely throws a 401 exception after 5 retries. No time-outs,
> > > > no long waits. In fact, a time-out would to me indicate another
> > > > problem (it still should throw an exception, though). So, unless
> > > > you're catching the exception in processData somehow, I don't see
> > > > where things could go wrong.
> > >
> > > > I assume you have no problem with correct credentials or simply
> > > > using a webbrowser?
> > >
> > > Hello,
> > >
> > > Yes, I can retrieve data without any problem.  I can break the URL and
> > > generate a 404 exception that is trapped and I can break it in other
> > > ways that generate other types of exceptions.  And trap them.
> > >
> > > I went back and looked at the code in urllib2.py and I see the
> > > timeout counter and that it raises an HTTPError after 5 tries.  But I
> > > don't get anything back.  If I just let the code run to completion, I
> > > get sent back to the prompt.  I put a try/catch in the method and I
> > > already have one on the call in main.
> > >
> > >
> > >
> > > > >> I don't know why it's hard-coded that way, and not just an option
> > > > >> with a default of 5, but that's currently how it is (maybe someone
> > > > >> else on this list knows?).
> > > > >
> > > > > I don't know, but even if I could set it to 1, I'm not helped
> unless
> > > > > there's a way for me to make it throw an exception and exit the
> loop.
> > >
> > > Actually, there's a comment in the code about why it is set to 5 --
> > > it's arbitrary, and allows for the Password Manager to prompt for
> > > credentials while not letting the request be reissued until 'recursion
> > > depth is exceeded.'
> > >
> > > I guess I'll have to go back to ground zero and write a stub to
> > > generate the error and then build back up to where it disappears.
> > >
> > > Thanks.
> > >
> > > mp
> > >
> > > --
> > > Michael Powe                michael at trollope.org            Naugatuck
> CT USA
> > > It turns out that it will be easier to simply block the top offenders
> > > manually; the rules for pattern matching are too arcane, obscure, and
> > > difficult to program. -- t. pascal, comp.mail.misc, "procmail to
> > > filter spam"
> >
> >
> >
> > > _______________________________________________
> > > Tutor maillist  -  Tutor at python.org
> > > To unsubscribe or change subscription options:
> > > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> > --
> > Michael Powe          michael at trollope.org            Naugatuck CT USA
> > I hate a fellow whom pride, or cowardice, or laziness drives into a
> > corner, and who does nothing when he is there but sit and <growl>; let
> > him come out as I do, and <bark>. -- Samuel Johnson
>
>
>
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
>
> --
> Michael Powe            michael at trollope.org            Naugatuck CT USA
>
> "If you don't like the news, go out and make some of your own."
>          -- Scoop Nisker, KSAN-FM, San Francisco
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/d3d45f70/attachment.html>

From ranceh at gmail.com  Sun Sep 12 20:54:39 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 13:54:39 -0500
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
	<FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>
Message-ID: <AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>

Luke:

On python3.1 I get the following error using your (untested) two line snippet:

TypeError: Unicode-objects must be encoded before hashing

If I add the b back into the mix, I get a hash with no error messages.

But I still can't quite figure out how to get the variable contents
into the hashing function.

On Sun, Sep 12, 2010 at 1:47 PM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:
> This is how I use it (untested)
> Import hashlib
> Print hashlib.md5("somestr").hexdigest()
>
> Works fine without using binary string.
>
>
> On Sep 12, 2010, at 1:19 PM, Rance Hall <ranceh at gmail.com> wrote:
>
>> Everybody knows you don't store plain text passwords in a database,
>> you store hashes instead
>>
>> consider:
>>
>> userpass = getpass.getpass("User password? ")
>>
>> encuserpass = hashlib.md5()
>>
>> encuserpass.update(userpass)
>>
>> del userpass
>>
>>
>> Now the documentation clearly states that if you are hashing a string
>> you need to covert it to bytes first with a line like this:
>>
>> encuserpass.update(b"text string here")
>>
>> The "b" in this syntax is a shortcut to converting the string to bytes
>> for hasing purposes.
>>
>> which means that the first code snippet fails, since I didnt convert
>> the variable contents to bytes instead of text.
>>
>> I didn't see an example that addresses hashing the string contents of
>> a variable.
>>
>> Whats missing in the above example that makes hashing the contents of
>> a string variable work?
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

From rabidpoobear at gmail.com  Sun Sep 12 21:04:45 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 12 Sep 2010 14:04:45 -0500
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
	<FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>
	<AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>
Message-ID: <72B82206-9736-4783-84DC-F45E7AA5A687@gmail.com>

Ah, it works differently on py3 i guess. Py2 was pretty lax with string handling. I would suggest researching Unicode encode functions rather than looking at the hashlib for info. There is probably a string.encode or something like that.

-----------------------------
Sent from a mobile device with a bad e-mail client.
-----------------------------

On Sep 12, 2010, at 1:54 PM, Rance Hall <ranceh at gmail.com> wrote:

> Luke:
> 
> On python3.1 I get the following error using your (untested) two line snippet:
> 
> TypeError: Unicode-objects must be encoded before hashing
> 
> If I add the b back into the mix, I get a hash with no error messages.
> 
> But I still can't quite figure out how to get the variable contents
> into the hashing function.
> 
> On Sun, Sep 12, 2010 at 1:47 PM, Luke Paireepinart
> <rabidpoobear at gmail.com> wrote:
>> This is how I use it (untested)
>> Import hashlib
>> Print hashlib.md5("somestr").hexdigest()
>> 
>> Works fine without using binary string.
>> 
>> 
>> On Sep 12, 2010, at 1:19 PM, Rance Hall <ranceh at gmail.com> wrote:
>> 
>>> Everybody knows you don't store plain text passwords in a database,
>>> you store hashes instead
>>> 
>>> consider:
>>> 
>>> userpass = getpass.getpass("User password? ")
>>> 
>>> encuserpass = hashlib.md5()
>>> 
>>> encuserpass.update(userpass)
>>> 
>>> del userpass
>>> 
>>> 
>>> Now the documentation clearly states that if you are hashing a string
>>> you need to covert it to bytes first with a line like this:
>>> 
>>> encuserpass.update(b"text string here")
>>> 
>>> The "b" in this syntax is a shortcut to converting the string to bytes
>>> for hasing purposes.
>>> 
>>> which means that the first code snippet fails, since I didnt convert
>>> the variable contents to bytes instead of text.
>>> 
>>> I didn't see an example that addresses hashing the string contents of
>>> a variable.
>>> 
>>> Whats missing in the above example that makes hashing the contents of
>>> a string variable work?
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From s.nabizadeh at uqconnect.edu.au  Sun Sep 12 08:13:10 2010
From: s.nabizadeh at uqconnect.edu.au (Miss Soraya Nabizadeh)
Date: Sun, 12 Sep 2010 06:13:10 +0000
Subject: [Tutor] (no subject)
Message-ID: <CE4DDB759864764F99F4365094A11B64307424F7@BL2PRD0103MB036.prod.exchangelabs.com>

Hello!
I am new to python and I am doing an assignment which asks about writing python functions.
the assignment is about a scramjet model and the forces that acts on it.
we are to write a python function that returns a linearly-interpolated value of drag coefficient and another for computing the trajectory of the scramjet in task 4 and 5.
to understand me better and the meaning of the assignment I have attached the file.
Any help would greatly be appreciated
hope to hear from you soon
thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/2c7c341e/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: minor1_2010-1.pdf
Type: application/pdf
Size: 151390 bytes
Desc: minor1_2010-1.pdf
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/2c7c341e/attachment-0001.pdf>

From ausakato at k-state.edu  Thu Sep  9 23:52:20 2010
From: ausakato at k-state.edu (Todd Ballard)
Date: Thu, 9 Sep 2010 17:52:20 -0400 (EDT)
Subject: [Tutor] list index out of range
Message-ID: <283313442.1436289.1284069140597.JavaMail.root@ksu-mailstore04.merit.edu>

I am attempting to have a cummalative total of the y values and receive a "list index out of range" error message

import numpy
import matplotlib.pyplot as plt
    
import filereader
from filereader import *

My_Path="C:\\Python26\\assignment2\\datadownload.txt"
My_Data_Type=numpy.dtype([("year","int32"),("day","int32"),("MJ","float64")])
daily_solar_radiation=read_array(My_Path,My_Data_Type,separator=None)    

y=[]
for i in xrange(0,365):
    y+=[daily_solar_radiation["MJ"][i]]

x=[]
for i in xrange(0,365):
    x+=[daily_solar_radiation["day"][i]]

plt.plot(x,y)
plt.title('Daily Radiation')
plt.xlabel('day of the year')
plt.ylabel('MJ/m**2')
plt.show()
plt.savefig('plot1.png')

from filereader import *

My_Path="C:\\Python26\\assignment2\\datadownload.txt"
My_Data_Type=numpy.dtype([("year","int32"),("day","int32"),("MJ","float64")])
daily_solar_radiation=read_array(My_Path,My_Data_Type,skip=91,separator=None)

y=[daily_solar_radiation["MJ"][0]]
for i in xrange(0,275):
    y=[daily_solar_radiation["MJ"]][i]+y[i-1]
            
for i in xrange(0,275):    
    x+=[daily_solar_radiation["day"][i]]

plt.plot(x,y)
plt.title('Daily Radiation')
plt.xlabel('day of the year')
plt.ylabel('MJ/m**2')
plt.show()
plt.savefig('plot2.png')


From gsong at nd.edu  Fri Sep 10 19:04:26 2010
From: gsong at nd.edu (Jack (Geliang) Song)
Date: Fri, 10 Sep 2010 13:04:26 -0400
Subject: [Tutor] smtp connection problem --- socket error 10061
Message-ID: <4C8A651A.5010705@nd.edu>

  I could not connect with gmail smtp server in Vista 32( worked ok in 
XP 32). Both vista and xp have same anti-virus software.

 >>> smtplib.SMTP("smtp.gmail.com",587)

Traceback (most recent call last):
   File "<pyshell#1>", line 1, in <module>
     smtplib.SMTP("smtp.gmail.com",587)
   File "C:\Program Files\Python25\lib\smtplib.py", line 244, in __init__
     (code, msg) = self.connect(host, port)
   File "C:\Program Files\Python25\lib\smtplib.py", line 310, in connect
     raise socket.error, msg
error: (10061, 'Connection refused')

I am using IPV4 for my vista wireless connection. No improvement with 
firewall disabled.

Any one has this problem? any solution?

Thanks a lot.

Jack


From davea at ieee.org  Sun Sep 12 21:23:36 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 12 Sep 2010 15:23:36 -0400
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
Message-ID: <4C8D28B8.90508@ieee.org>



On 2:59 PM, Rance Hall wrote:
> Everybody knows you don't store plain text passwords in a database,
> you store hashes instead
>
> consider:
>
> userpass = getpass.getpass("User password? ")
>
> encuserpass = hashlib.md5()
>
> encuserpass.update(userpass)
>
> del userpass
>
>
> Now the documentation clearly states that if you are hashing a string
> you need to covert it to bytes first with a line like this:
>
> encuserpass.update(b"text string here")
>
> The "b" in this syntax is a shortcut to converting the string to bytes
> for hasing purposes.
>
> which means that the first code snippet fails, since I didnt convert
> the variable contents to bytes instead of text.
>
> I didn't see an example that addresses hashing the string contents of
> a variable.
>
> Whats missing in the above example that makes hashing the contents of
> a string variable work?
>
What version of Python are you using, and what version of Python is "the 
documentation" written for?

In version 2.x, a string is already a series of bytes.

DaveA


From alan.gauld at btinternet.com  Sun Sep 12 21:28:38 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 20:28:38 +0100
Subject: [Tutor] (no subject)
References: <CE4DDB759864764F99F4365094A11B64307424F7@BL2PRD0103MB036.prod.exchangelabs.com>
Message-ID: <i6j9l3$v3g$1@dough.gmane.org>

"Miss Soraya Nabizadeh" <s.nabizadeh at uqconnect.edu.au> wrote

> I am new to python

Welcome,

> and I am doing an assignment which asks about writing python 
> functions.

The rules of the forum are that we don;t do assignments for you but we
will offer suggestions ior answer specific qquestions. That works best 
if
you start by telling us what you think you should be doing and showing
us at least some basic code that you have written yourself.

Finally, you say you are new to Python. Are you also new to 
programming?
Or do you know any other programming languages? And if you are 
following
an online tutorial? ASnd which version of Python and which Operationg 
System.
These are all useful bits of information that help us to help you.

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



From davea at ieee.org  Sun Sep 12 21:29:16 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 12 Sep 2010 15:29:16 -0400
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>	<FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>
	<AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>
Message-ID: <4C8D2A0C.3060703@ieee.org>

  On 2:59 PM, Rance Hall wrote:
> Luke:
>
> On python3.1 I get the following error using your (untested) two line snippet:
>
> TypeError: Unicode-objects must be encoded before hashing
>
> If I add the b back into the mix, I get a hash with no error messages.
>
> But I still can't quite figure out how to get the variable contents
> into the hashing function.
Since you top-posted, I'm clipping out all the stuff that is now out of 
order.  Add your remarks after the part you're quoting.

You're in Python 3, and you have a password in a string variable pass, 
and you want to use those bytes as an argument to a function that takes 
bytes?

Convert the string to bytes.  If the string is ASCII, you can simply use 
the bytes() function.  If not, you may need to specify an encoding.

The b'xxx' syntax is only for entering in a literal byte string.  It 
gets encoded according to the source file's encoding declaration.  But 
that's not generally of any use for passwords, since you're going to ask 
the user the password, not enter it into the source.

DaveA


From alan.gauld at btinternet.com  Sun Sep 12 21:37:18 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 20:37:18 +0100
Subject: [Tutor] What Design Pattern for Document class (NOT URGENT)
References: <4C760D11.5090302@free.fr>
Message-ID: <i6ja5b$1gu$1@dough.gmane.org>

"Karim" <karim.liateni at free.fr> wrote

> My first idea is to create an *docrules* class which holds my 
> document.

Why not create a Document class that is your document.

> This class will use 2 other instances from 2 respectives classes
> reader and writer. The main method of  reader is get().
> The main method of writer is write(). To resume I have:

And then the document could know how to get(why not read?)
and write itself? (Possibly using other helper classes but
we don't need to worry about that yet)


> The *docrules* will do the parsing (*xml.etree* very effective)
> and create the reader and the writer instance.

Maybe the document knows how to parse itself? Maybe using
some supporting rules class, but maybe not.

> I want to create 2 others classes (or more) more specific which have
> more the knowledge about the XML documents structures.
> *SpecificRuleReader*, *SpecificRuleWriter* which are deriving resp.

Maybe. Or are they subclasses of Document for some specific
type of XML? (Either approach is valid depending on how many
different rulesets you need.)

> My purpose is to separate as far as possible XML representation from
> core classes.

Thats a good idea, but creating an abstracted document class is a
good way of hiding your users from the internal details of how the
reading/writing and parsing is done.

>  I don't want necessarily have 2 big classes which
> know everything about XML document because I will have too many
> methods.

That depends on how you build the parsing of the document,
if you focus on what your user wants to do it should not be too many.
But if you expose the XML internals to your users it surely will.
Remember to design your objects interface from the users perspective
not based on the implementation!

Its fine to use helper objects - like rules, parsers etc - but you 
want
to shield your client code from them as much as possible.

HTH,

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



From alan.gauld at btinternet.com  Sun Sep 12 21:52:06 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 20:52:06 +0100
Subject: [Tutor] recursive problem
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>,
	<201009120318.19827.steve@pearwood.info>,
	<201009120327.42259.steve@pearwood.info>,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>,
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>,
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>,
	<SNT118-W1424DD7FCE39F0897F7011AE750@phx.gbl>
	<SNT118-W3061808964C7130BA88258AE750@phx.gbl>
Message-ID: <i6jb17$4vg$1@dough.gmane.org>

"Roelof Wobben" <rwobben at hotmail.com> wrote

>>> I guess the question to ask/consider is: How can be establish 
>>> whether a
>>> particular object supports a particular interface/set of 
>>> behaviours

In general we "try" it and handle the exceptions

>>> that we require? E.g. how do we most pythonically check whether 
>>> some
>>> object "walks like a list" and "quacks like a list" without tying 
>>> such
>>> code to explicit type checking?

But the risk is that although it may quack, it does so like a missile
launch program rather than a list - oops! :-)

> With the knowlegde I have from the few chapters of thinking like
> a computer scientist I don't know the answer to the last question.

If you do need to avoid accidentally launching missiles then you need
to do some type checking - although ideally using isinstance() instead
of type(). But in the majority of cases some sensible documentation
and Python's culture that we are all adults here usually means you 
don't
need to.

HTH,

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



From rwobben at hotmail.com  Sun Sep 12 21:58:22 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 12 Sep 2010 19:58:22 +0000
Subject: [Tutor] recursive problem
In-Reply-To: <i6jb17$4vg$1@dough.gmane.org>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>, ,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>, ,
	<201009120318.19827.steve@pearwood.info>, ,
	<201009120327.42259.steve@pearwood.info>, ,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>, ,
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>, ,
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>, ,
	<SNT118-W1424DD7FCE39F0897F7011AE750@phx.gbl>,
	<SNT118-W3061808964C7130BA88258AE750@phx.gbl>,
	<i6jb17$4vg$1@dough.gmane.org>
Message-ID: <SNT118-W356645B4E37D5982098B4AE760@phx.gbl>




----------------------------------------
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Sun, 12 Sep 2010 20:52:06 +0100
> Subject: Re: [Tutor] recursive problem
>
> "Roelof Wobben" wrote
>
>>>> I guess the question to ask/consider is: How can be establish
>>>> whether a
>>>> particular object supports a particular interface/set of
>>>> behaviours
>
> In general we "try" it and handle the exceptions
>
>>>> that we require? E.g. how do we most pythonically check whether
>>>> some
>>>> object "walks like a list" and "quacks like a list" without tying
>>>> such
>>>> code to explicit type checking?
>
> But the risk is that although it may quack, it does so like a missile
> launch program rather than a list - oops! :-)
>
>> With the knowlegde I have from the few chapters of thinking like
>> a computer scientist I don't know the answer to the last question.
>
> If you do need to avoid accidentally launching missiles then you need
> to do some type checking - although ideally using isinstance() instead
> of type(). But in the majority of cases some sensible documentation
> and Python's culture that we are all adults here usually means you
> don't
> need to.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello Alan, 
 
The last chapter I don't understand completly.
Do i have no need for type checking or make use of isinstance() or do I misunderstood you.
Sorry that English is not a language I speak very well.
 
Roelof

  		 	   		  

From alan.gauld at btinternet.com  Sun Sep 12 21:56:55 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 20:56:55 +0100
Subject: [Tutor] recursive problem
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>,
	<201009120327.42259.steve@pearwood.info>,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>,
	<201009120403.43651.steve@pearwood.info>
	<SNT118-W13807C851F0F7BA4AF981EAE750@phx.gbl>
Message-ID: <i6jba8$60b$1@dough.gmane.org>

"Roelof Wobben" <rwobben at hotmail.com> wrote
> Because I follow this book "Thinking like a computer scientist" and
> I have only read the chapters about strings. lists and tuples.

And that book tries to use Python to teach a general Computing
Science degree 101 course. So it teaches you what are classically
considered good practices even when these are not normal Python
practice. That doesn't make it a bad book but its not purely Pythonic.

FWIW The same is true of my tutorial - I try to teach general 
principles
rather than pure Python - but my attempt to minimise the difference
is to include examples using VBScript and Javascriopt to illustrate
alternate approaches. You pick your favourite and run with it, but
recognise the limits...

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




From alan.gauld at btinternet.com  Sun Sep 12 22:02:21 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 21:02:21 +0100
Subject: [Tutor] design question
References: <445813.72562.qm@web110715.mail.gq1.yahoo.com>
Message-ID: <i6jbkd$792$1@dough.gmane.org>


"Albert-Jan Roskam" <fomcl at yahoo.com> wrote

> following classes: Menu (responsible for the widget creation), 
> Autocomplete (a
> subclass of the tkinter text entry widget which I've found on the 
> internet, I
> wanted to keep this intact), Convert (responsible for the 
> conversion/cropping of
> the images, which is somewhat tedious) and Events (here's the pain 
> spot: this
> has become a mixed bag). Originally, the Events class was supposed 
> to contain
> all the commands behind the widgets, but it has slowly gotten more
> responsibilities.

That last bit is bad...

> I'd like to rewrite to entire program so that (1) all classes have 
> just one
> responsibility (2) classes connect to as little other classes (so it 
> becomes
> easy to e.g. change to another widget set). I'd love to hear some 
> thoughts or


You need to go back to first principles of GUI design.
Separate the data classes(models) from the behaviour of the GUI 
(controller)
and the display(views)
Read up on the MVC pattern on Wikipedia.
Build the core application code in your models.
Display them in views.
Use a controller(or occasionally controllers) to manage the 
interactions.

HTH,


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



From alan.gauld at btinternet.com  Sun Sep 12 22:05:23 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 21:05:23 +0100
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
Message-ID: <i6jbq3$7tl$1@dough.gmane.org>


"Huy Ton That" <huyslogic at gmail.com> wrote

> class WhatFor(object):
>    def it(cls):
>        print 'work with %s' % cls
>    it = classmethod(it)
>    def uncommon():
>        print 'I could be a global function'
>    uncommon = staticmethod(uncommon)
>
> But I can't seem to understand the above. Under what circumstance 
> would
> staticmethod be useful? I am just deriving that you are not passing 
> self.

I think static methjods are largely a mistake of history. ISTR They 
were
introduced into python before class methods (not by much - one 
release?)
and to support backward compatibility they stayed. In practice 
classmethod
will be a better choice.

IMHO at least :-)

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



From alan.gauld at btinternet.com  Sun Sep 12 22:10:26 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 12 Sep 2010 21:10:26 +0100
Subject: [Tutor] tree problem
References: <SNT118-W128EF356300115600F196AE760@phx.gbl>
	<i6if12$tmu$1@dough.gmane.org>
Message-ID: <i6jc3j$91d$1@dough.gmane.org>


"Lie Ryan" <lie.1296 at gmail.com> wrote

> In this case, the only reason why you hit the recursion limit is if 
> you
> have a directory which is 1000 deep (quite unlikely, Windows has a
> directory depth limit much lower than that).

Or you accidentally have a recursive directory - one that contains a
shortcut to a folder higher up in the chain. These are easy to create
in Windows but nearly impossible tyo remove.

I have one such folder in my work PC(*) that I renamed to
"BAD FOLDER DO NOT USE" and have to remove from every
backup I ever make because it causees infinite looping.

(*) I will point out that I didn't create it - it was a malfunctioning
application that I was using in Beta... And if anyone knows how
to remove it I'd be very grateful!

Alan G.



From ranceh at gmail.com  Sun Sep 12 22:15:55 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 15:15:55 -0500
Subject: [Tutor] forcing hashlib to has string variables
In-Reply-To: <4C8D2A0C.3060703@ieee.org>
References: <AANLkTinZayvxmA+7Acw7e-7SqgCcNDq9mUNEM4VQww03@mail.gmail.com>
	<FA557C87-A5EB-488A-BC5C-BB3C110D2642@gmail.com>
	<AANLkTi=1VgiDERZ-RO5TcCduqZP=0aiKRJNyKOssi6kj@mail.gmail.com>
	<4C8D2A0C.3060703@ieee.org>
Message-ID: <AANLkTimxqr9g3-tSC02Bg1o8J80EMRibO7CyttBDYDiU@mail.gmail.com>

On Sun, Sep 12, 2010 at 2:29 PM, Dave Angel <davea at ieee.org> wrote:
> ?On 2:59 PM, Rance Hall wrote:
<snip>
> Convert the string to bytes. ?If the string is ASCII, you can simply use the
> bytes() function. ?If not, you may need to specify an encoding.
<snip>

Thanks Dave, this is what I needed, I looked in the function reference
and didn't see it.

From wallenpb at gmail.com  Sun Sep 12 22:53:37 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 12 Sep 2010 15:53:37 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
In-Reply-To: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
References: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
Message-ID: <AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>

Rance,

I was doing something similar, except I was querying an Oracle database,
using the cx_Oracle module.  I wanted the non-duplicated count of parts in
my database that met certain criteria.  All the output that met the criteria
of the select statements is loaded into the cursor object.  I then loop
through the cursor object appending the contents into a list.   Then I
converted the list to a set to blow out the duplicates and then back to a
list and took the len of the list for my final count.

#Fetch the list of parts
cursor.execute("select pobj_name from pfmc_part where pmodel = :arg_1 and
pstatus = :arg_2", arg_1 = "PN-DWG", arg_2 = "RELEASED")
for pobj_name in cursor:
    Parts_List.append(pobj_name)

print("size of Parts_List before set operation =", len(Parts_List))
Parts_List = list(set(Parts_List))
print("size of Parts_List after set operation  =", len(Parts_List))

Perhaps you could loop though your get_todo object and load into a list and
do similar or just take a len of it directly if it is already a list.

-Bill

On Sun, Sep 12, 2010 at 10:55 AM, Rance Hall <ranceh at gmail.com> wrote:

> I'm not sure if this is the right forum for this or not, if there is a
> better place to ask this question please let me know and I'll re-post
> elsewhere.
>
> I'm using python v3.1 and the py-postgresql v1.0.1 module located at
> http://python.projects.postgresql.org/docs/1.0/
>
> I'm using prepared sql statements like:
>
> insertnote = db.prepare("INSERT INTO business.to_do_list (note) VALUES
> ($1)")
> delete_note = db.prepare("DELETE FROM business.to_do_list WHERE item = $1")
>
> so far so good, everything is working well and I understand whats going on.
>
> But I have a situation where I want to count the number of notes in
> the database, and if 0 do something, and if 1 do something else.
> I have another occasion where I only want the first few records to be
> returned.
>
> So for testing the idea I did this:
>
> get_todo = db.prepare("SELECT note FROM business.to_do_list ORDER BY item")
> get_todo_limit = db.prepare("SELECT note FROM business.to_do_list
> ORDER BY item LIMIT 10")
> get_todo_count = db.prepare("SELECT COUNT(note) AS notecount FROM
> business.to_do_list")
>
> I *think* there is a better way to do this, but I'm not seeing it in
> the documentation, or its there and I'm not understanding it
> correctly.
>
> I suspect that the get_todo_count statement is not required at all.  I
> have a hunch, although I can't prove yet that the result set returned
> by the SQL SELECT statement will have some way to access the record
> count directly
>
> Something like this:
>
> m = get_todo_limit()
>
> if m.count == 0:
>    do stuff
> else:
>    do other stuff
>
> I can't quite narrow this down.  I'm sure its possible, It likely
> depends on what python variable type is used by the py-postgresql
> module, but I'm not seeing this in the docs.
>
> Second question is more of a performance question:
>
> I don't suspect a "large" # of items in the to_do list, so I *think*
> that it would be better to just have one SQL statement and then loop
> through the results 10 times to get the first few records rather than
> having a seperate sql statement as I have shown here.  I'm too new at
> python to have a feel for the *right* way to go about this part
>
> Could someone point me in the right direction please?
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/dc00962a/attachment-0001.html>

From alan.gauld at btinternet.com  Sun Sep 12 23:08:53 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sun, 12 Sep 2010 21:08:53 +0000 (GMT)
Subject: [Tutor] recursive problem
In-Reply-To: <SNT118-W356645B4E37D5982098B4AE760@phx.gbl>
References: <SNT118-W16F3293C98E2CBB40F9D37AE730@phx.gbl>, ,
	<AANLkTi=gNL7Kvgn13BpkVX867iz0Ab_omCFJZ5zEmXDU@mail.gmail.com>, ,
	<201009120318.19827.steve@pearwood.info>, ,
	<201009120327.42259.steve@pearwood.info>, ,
	<SNT118-W60F518F3657EB6A4D294CFAE750@phx.gbl>, ,
	<873ABE79-1C7E-4D4A-864D-1FA19D53389F@gmail.com>, ,
	<AANLkTinNo=a2bFN=J90Rr_rA-S9Xk+5aAxiXPSeCnWh=@mail.gmail.com>, ,
	<SNT118-W1424DD7FCE39F0897F7011AE750@phx.gbl>,
	<SNT118-W3061808964C7130BA88258AE750@phx.gbl>,
	<i6jb17$4vg$1@dough.gmane.org>
	<SNT118-W356645B4E37D5982098B4AE760@phx.gbl>
Message-ID: <939334.31004.qm@web86708.mail.ird.yahoo.com>



> > If you do need to avoid accidentally launching  missiles then you need
> > to do some type checking - although ideally using  isinstance() instead
> > of type(). But in the majority of cases some  sensible documentation
> > and Python's culture that we are all adults here  usually means you
> > don't need to.
> 
> The last chapter I don't understand completly.
> Do i have no need for type  checking or make use of isinstance() or do I 
>misunderstood you.
> Sorry that  English is not a language I speak very well.

I'm saying that most of the time you should try working without type checking 
but there are occasions when you must do it. And if you do need to you should 
nearly always use isinstance() rather than type()

HTH,

Alan G

From wallenpb at gmail.com  Sun Sep 12 23:11:30 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 12 Sep 2010 16:11:30 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
In-Reply-To: <AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
References: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
	<AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
Message-ID: <AANLkTimPK+3CLEmdmWPrP73VoHhv1ammpEnwNQEyevq+@mail.gmail.com>

>
>> Second question is more of a performance question:
>>
>> I don't suspect a "large" # of items in the to_do list, so I *think*
>> that it would be better to just have one SQL statement and then loop
>> through the results 10 times to get the first few records rather than
>> having a seperate sql statement as I have shown here.  I'm too new at
>> python to have a feel for the *right* way to go about this part
>>
>> Could someone point me in the right direction please?
>>
>
As to your second question, I had the same question a few days ago that the
folks here helped me out with.  if you have a list of items you can limit
the loop to get just the first ten items like this:

for x in list_of_results[:10]
     do something with x...

If your object does not easily lend itself to applying a slice, then look
into the itertools module and the islice() method which can help you get and
iterable list from a normaly non-iterable source, like this:

import itertools
for x in itertools.islice(results, 0, 10)
    do something with x...


-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/4888f021/attachment.html>

From ranceh at gmail.com  Sun Sep 12 23:42:50 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 16:42:50 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
In-Reply-To: <AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
References: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
	<AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
Message-ID: <AANLkTinjgqrr5gfFMfNpOn-zMSVJ2Xx6PVEoqgaXZ8jV@mail.gmail.com>

On Sun, Sep 12, 2010 at 3:53 PM, Bill Allen <wallenpb at gmail.com> wrote:
> Rance,
>
> I was doing something similar, except I was querying an Oracle database,
> using the cx_Oracle module.? I wanted the non-duplicated count of parts in
> my database that met certain criteria.? All the output that met the criteria
> of the select statements is loaded into the cursor object.? I then loop
> through the cursor object appending the contents into a list.?? Then I
> converted the list to a set to blow out the duplicates and then back to a
> list and took the len of the list for my final count.
>
> #Fetch the list of parts
> cursor.execute("select pobj_name from pfmc_part where pmodel = :arg_1 and
> pstatus = :arg_2", arg_1 = "PN-DWG", arg_2 = "RELEASED")
> for pobj_name in cursor:
> ??? Parts_List.append(pobj_name)
>
> print("size of Parts_List before set operation =", len(Parts_List))
> Parts_List = list(set(Parts_List))
> print("size of Parts_List after set operation? =", len(Parts_List))
>
> Perhaps you could loop though your get_todo object and load into a list and
> do similar or just take a len of it directly if it is already a list.
>

Thanks for the tip.  I'll do some more research but this sounds promising.

Rance

From rabidpoobear at gmail.com  Sun Sep 12 23:54:37 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Sun, 12 Sep 2010 16:54:37 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
In-Reply-To: <AANLkTinjgqrr5gfFMfNpOn-zMSVJ2Xx6PVEoqgaXZ8jV@mail.gmail.com>
References: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
	<AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
	<AANLkTinjgqrr5gfFMfNpOn-zMSVJ2Xx6PVEoqgaXZ8jV@mail.gmail.com>
Message-ID: <CF5776D8-168F-4A60-ABFB-1350C02166DB@gmail.com>

> 
> Thanks for the tip.  I'll do some more research but this sounds promising.
> 
> Rance
> 
Just be aware that some methods of list building will iterate over the list and evaluate it. So if you only want to retrieve the first 10 results but you do something like
Results = [I.fetch() for I in cursor]
print Results[:10]

You will actually be retrieving all records.
Obviously this is a contrived example and it will be more subtle in practice. Just be cautious that you're not fetching all your data initially and then paging it. You could maybe check your database for the number of results it's returning for each query maybe. I'm not very knowledgeable about database monitoring and optimization but this strikes me as something you could probably do.

From ranceh at gmail.com  Mon Sep 13 00:18:49 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 12 Sep 2010 17:18:49 -0500
Subject: [Tutor] py-postgressql v1.0.1 question
In-Reply-To: <CF5776D8-168F-4A60-ABFB-1350C02166DB@gmail.com>
References: <AANLkTimgnjhZjF9TDjNfFgGXWHW3HTGdnZ=LGTW4sqiB@mail.gmail.com>
	<AANLkTin=zwvDCLgX5cpXvGMqKB6T+iCCJ06-_L-U6Rc2@mail.gmail.com>
	<AANLkTinjgqrr5gfFMfNpOn-zMSVJ2Xx6PVEoqgaXZ8jV@mail.gmail.com>
	<CF5776D8-168F-4A60-ABFB-1350C02166DB@gmail.com>
Message-ID: <AANLkTikP1jmF2Bhd4T2kfee4abn45nbX_ZnF6+bRma78@mail.gmail.com>

On Sun, Sep 12, 2010 at 4:54 PM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:
>>
>> Thanks for the tip. ?I'll do some more research but this sounds promising.
>>
>> Rance
>>
> Just be aware that some methods of list building will iterate over the list and evaluate it. So if you only want to retrieve the first 10 results but you do something like
> Results = [I.fetch() for I in cursor]
> print Results[:10]
>
> You will actually be retrieving all records.
> Obviously this is a contrived example and it will be more subtle in practice. Just be cautious that you're not fetching all your data initially and then paging it. You could maybe check your database for the number of results it's returning for each query maybe. I'm not very knowledgeable about database monitoring and optimization but this strikes me as something you could probably do.

Thanks for the warning here, and I had already suspected as much.  I
am making a calculated guess that there will only be at most 15-20
items at a time in the result set.  Getting all 20 and only choosing
the first 10 during the list iteration process seems to be the best
route.  Especially since sometimes I will want all of them.  If I just
play games with the iterator then I can reuse my get_list code other
places.

If my calculated guess turns out to be wrong, and there are a
significant # of items in the list, then I can revisit this issue.

Rance

From steve at pearwood.info  Mon Sep 13 00:56:55 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 13 Sep 2010 08:56:55 +1000
Subject: [Tutor] list index out of range
In-Reply-To: <283313442.1436289.1284069140597.JavaMail.root@ksu-mailstore04.merit.edu>
References: <283313442.1436289.1284069140597.JavaMail.root@ksu-mailstore04.merit.edu>
Message-ID: <201009130856.55670.steve@pearwood.info>

On Fri, 10 Sep 2010 07:52:20 am Todd Ballard wrote:
> I am attempting to have a cummalative total of the y values and
> receive a "list index out of range" error message

How unfortunate.

Do you have an actual question to ask, or are you just sharing?

If you are having problems fixing the error, what does the stack 
traceback say? Not just the error message, which is the least important 
part of the error, but the entire traceback. This will show *where* the 
function occurs, as well as *what* the error is, and sometimes *why* as 
well.


A couple of other comments follow:

> import filereader
> from filereader import *

It's rare to actually need to do both of this together. Are you sure you 
need both? It's generally better to stick to the first form, and have 
fully-qualified names like filereader.read_array. If that's too long, 
it's best to import only the functions you actually need, which in your 
case seems to be:

from filereader import read_array

The "import *" form should be considered advanced usage best avoided 
unless you know what you're doing.

> My_Path="C:\\Python26\\assignment2\\datadownload.txt"

A little-known fact: Windows supports both \ and / as the directory 
separator. Since Python uses backslash for the escape character, it 
gets tedious and error-prone to write strings with lots of backslashes. 
So the best way to write pathnames under Windows in Python is with 
forward-slashes:

My_Path="C:/Python26/assignment2/datadownload.txt"


> y=[]
> for i in xrange(0,365):

There's no need to say xrange(0, 365). Just xrange(365) will have the 
same effect, because the starting index defaults to 0.

>     y+=[daily_solar_radiation["MJ"][i]]

It's generally more efficient to use:

    y.append(daily_solar_radiation["MJ"][i])

instead of y += [...] as you do, although for only 365 items it won't 
make a huge difference.


> from filereader import *

You've already done this above, you don't need to do this again.





-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 13 01:13:25 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 13 Sep 2010 09:13:25 +1000
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <i6jbq3$7tl$1@dough.gmane.org>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
	<i6jbq3$7tl$1@dough.gmane.org>
Message-ID: <201009130913.26305.steve@pearwood.info>

On Mon, 13 Sep 2010 06:05:23 am Alan Gauld wrote:

> I think static methjods are largely a mistake of history. ISTR They
> were
> introduced into python before class methods (not by much - one
> release?)

No, they were introduced at the same time. But it turned out that the 
use cases Guido van Rossum envisaged for them weren't as compelling as 
he first imagined. At some point he wrote that staticmethod was the 
only Python feature where there was no example of it being used in the 
standard library, apart from tests to ensure that staticmethod worked 
correctly.

Of course that doesn't mean that staticmethod is a bad feature, only 
that it's a very specialized function. It probably should have been 
moved into functools.

If anyone is interested in descriptors like classmethod and 
staticmethod, I have published a recipe for a third member of the 
family:

http://code.activestate.com/recipes/577030/

"dualmethod" creates a method that receives the instance when you call 
it normally from the instance, and the class when you call it from the 
class. This makes it like a cross between ordinary methods and class 
methods.



-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 13 01:27:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 13 Sep 2010 09:27:56 +1000
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <201009130913.26305.steve@pearwood.info>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
	<i6jbq3$7tl$1@dough.gmane.org>
	<201009130913.26305.steve@pearwood.info>
Message-ID: <201009130927.56297.steve@pearwood.info>

On Mon, 13 Sep 2010 09:13:25 am Steven D'Aprano wrote:
> On Mon, 13 Sep 2010 06:05:23 am Alan Gauld wrote:
> > I think static methjods are largely a mistake of history. ISTR They
> > were
> > introduced into python before class methods (not by much - one
> > release?)
>
> No, they were introduced at the same time. But it turned out that the
> use cases Guido van Rossum envisaged for them weren't as compelling
> as he first imagined. 

A little more information... static methods are quite common[1] in Java 
and C++, where people feel the need (or in the case of Java, are forced 
by the language) to make every function a method.

Re Java, see this amusing discussion:

http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html




[1] For some definition of "common".

-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Mon Sep 13 03:01:13 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 13 Sep 2010 02:01:13 +0100
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com><i6jbq3$7tl$1@dough.gmane.org><201009130913.26305.steve@pearwood.info>
	<201009130927.56297.steve@pearwood.info>
Message-ID: <i6jt4q$ubt$1@dough.gmane.org>

"Steven D'Aprano" <steve at pearwood.info> wrote

> A little more information... static methods are quite common[1] in 
> Java
> and C++, where people feel the need (or in the case of Java, are 
> forced
> by the language) to make every function a method.

static methods in C++ are normally reserved for use as class
methods (although with the "pollution" from Java that is slowly
changing). Java OTOH has made them much more common but
as substitutes for functions as well as true class methods - yeck!

They are also found in a slightly different guise in Delphi.

Python classmethods are more powerful and useful than either.

Alan G. 



From huyslogic at gmail.com  Mon Sep 13 04:29:07 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Sun, 12 Sep 2010 22:29:07 -0400
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <i6jt4q$ubt$1@dough.gmane.org>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
	<i6jbq3$7tl$1@dough.gmane.org> <201009130913.26305.steve@pearwood.info>
	<201009130927.56297.steve@pearwood.info> <i6jt4q$ubt$1@dough.gmane.org>
Message-ID: <AANLkTik9x1NNNZ734m8YAqwDDUrnKA38F3=nmgk4X9kM@mail.gmail.com>

Hm, thanks guys; I just had to verify I was thinking sanely about it. I am
going to pick up classmethods next. Do any of you have common design
patterns for the usage. They are just items I haven't integrated in my
coding, and I want to be certain I'm off on the right foot (:


On Sun, Sep 12, 2010 at 9:01 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Steven D'Aprano" <steve at pearwood.info> wrote
>
>
>  A little more information... static methods are quite common[1] in Java
>> and C++, where people feel the need (or in the case of Java, are forced
>> by the language) to make every function a method.
>>
>
> static methods in C++ are normally reserved for use as class
> methods (although with the "pollution" from Java that is slowly
> changing). Java OTOH has made them much more common but
> as substitutes for functions as well as true class methods - yeck!
>
> They are also found in a slightly different guise in Delphi.
>
> Python classmethods are more powerful and useful than either.
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100912/d9dfd2ea/attachment.html>

From michael at trollope.org  Mon Sep 13 11:54:24 2010
From: michael at trollope.org (Michael Powe)
Date: Mon, 13 Sep 2010 05:54:24 -0400
Subject: [Tutor] Documenting a Module
Message-ID: <20100913095424.GF2670@cecilia>

Hello,

Are there any tools for documenting a module other than Sphinx? 

Apparently, I need a full-blown dev box with Visual Studio installed
to get Sphinx up, due to the dependency on Jinja, which comes
source-only and requires VC. 

I wrote a module, I'd like to produce a decent document of its
functionality from the comments and doc strings; and I already wasted
a considerable part of my Sunday afternoon trying to get along with
Sphinx. I'm not talking about a huge Python project, nor am I likely
to need that type of documentation tool in the near future.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA


Is it time for your medication or mine?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/a847b60d/attachment.pgp>

From ralf at schoenian-online.de  Mon Sep 13 12:03:27 2010
From: ralf at schoenian-online.de (ralf at schoenian-online.de)
Date: Mon, 13 Sep 2010 12:03:27 +0200 (CEST)
Subject: [Tutor] Documenting a Module
In-Reply-To: <20100913095424.GF2670@cecilia>
References: <20100913095424.GF2670@cecilia>
Message-ID: <1181043741.65805.1284372207332.JavaMail.open-xchange@oxltgw01.schlund.de>


Hi Michael,
?
I can recommend epydoc. You can find it here:
?http://epydoc.sourceforge.net/?It's a nice tool and you should have no problems
with the installation.
?
Ralf
?
?
?

Michael Powe <michael at trollope.org> hat am 13. September 2010 um 11:54
geschrieben:

> Hello,
>
> Are there any tools for documenting a module other than Sphinx?
>
> Apparently, I need a full-blown dev box with Visual Studio installed
> to get Sphinx up, due to the dependency on Jinja, which comes
> source-only and requires VC.
>
> I wrote a module, I'd like to produce a decent document of its
> functionality from the comments and doc strings; and I already wasted
> a considerable part of my Sunday afternoon trying to get along with
> Sphinx. I'm not talking about a huge Python project, nor am I likely
> to need that type of documentation tool in the near future.
>
> Thanks.
>
> mp
>
> --
> Michael Powe? ? ? ? ? ? ? ? michael at trollope.org? ? ? ? ? ? ? ? Naugatuck CT
> USA
>
>
> Is it time for your medication or mine?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/afde478b/attachment.html>

From fal at libero.it  Mon Sep 13 12:55:46 2010
From: fal at libero.it (Francesco Loffredo)
Date: Mon, 13 Sep 2010 12:55:46 +0200
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8BCDD0.4080909@gmail.com>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>	<SNT118-W404C0C144D7164349CE4A5AE740@phx.gbl>	<4C8AC5B9.8070807@gmail.com>	<201009112022.47844.steve@pearwood.info>,
	<i6fn66$ejn$1@dough.gmane.org>,
	<4C8B9AD2.5050906@gmail.com>	<SNT118-W53D11032D947AD2BCA1BAAE750@phx.gbl>
	<4C8BCDD0.4080909@gmail.com>
Message-ID: <4C8E0332.7020605@libero.it>

On 11/09/2010 20.43, bob gailer wrote:
> On 9/11/2010 12:12 PM, Roelof Wobben wrote:
>>...
>>>>>> You can't.
>>> I made that comment in the context of the OPs function:
>>>
>>> def readposint():
>>> x = raw_input("Please enter a positive integer :")
>>> try:
>>> if (int(x)<0 or (float(x) - int(x)> 0)): raise(ValueError)
>>> except:
>>> print x , "is not a positive integer. Try again."
>>> return -1
>>> return x
>>>
>>> The OP thought (incorrectly) that, given for example:
>>> x = '3.1'
>>> float(x) - int(x) would evaluate to 0.1
>>>
>>> In reality int(x) in this case raises an exception.
>>> ValueError: invalid literal for int() with base 10: '3.1'
>>>
>>> Since the expression was in a try he could not tell exactly what was
>>> happening.
>>>
>>> I also don't quite understand the use of raise in the try.
It took me some time to understand that OP was... me! What do you mean 
by OP? If it stands (as usual) for Original Poster, he (Roelof Wobben) 
did not write this piece of cleverly crafted code. It was me, and I'm 
glad to show you its internals.
My aim was to exclude everything but positive integers, and so I did by 
EAFP programming. You pointed out that int('3.1') throws an exception, 
as I did not know.
                     *So what?*
My little readposint() function only needed to let POSITIVE INTEGERS go, 
and so it does. Everything else generates an exception, even positive 
floats (thanks to the raise inserted in a try), and I handle it 
informing the user and returning a well-defined and repeatable wrong 
value, that can be easily handled.
Sure, I could make the funcion more efficient, and nearly all of you can 
make it more Pythonic, whatever that means. But I thought it was quite 
sufficient, for a school exercise.
Note that int('7') returns, correctly, 7, while float('5.2') returns 5.2 
as expected. I don't like this rough behaviour of int(), spitting out an 
exception if given a legitimate string representation of a float. Can 
some of you Tutors explain me why it must be so?

>>> I wish and hope that Roelof will learn how to do program walkthroughs
>>> and use the interactive prompt to solve things himself. I applaud the
>>> patience some of you have ih hand-holding him. I don't have that
>>> patience. I wish him to learn to fish.
I don't like fishing, but many fishermen friends of mine tell me it's 
something that greatly improve patience. If you lack this quality, as 
you said, then you're the one who should go fishing...

>> Hello Bob,
>>
>> Oke, I try to fish.
>
> Thank you.
I hope you will keep trying to learn programming and Python too, Roelof. 
You show tenacity and determination, and those (with patience, I would 
add) are very useful in serious programming. Anyway, remember the Python 
shell is your friend, make good use of it!

>>
>> Are these the right conclusions ??
>>
>> Roelof
You're very close, Roelof. I just wanted to produce exactly the same 
error message and result for any wrong value inserted, and return the 
right number if the right number was input by the user. So I started 
with (int(x) < 0) to get rid of all that int() cannot handle (I never 
knew it couldn't handle "3.2", but for now it's OK) and also negative 
integers (and negative floats, I thought); then I found a way to exclude 
positive floats. I think this is what(float(x) - int(x) > 0) can do. I 
pseudo code, my function is:

input value
if (value is not a positive integer): throw exception
else: return value.
exception: inform user
            return -1.

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3130 -  Data di rilascio: 09/12/10 08:34:00

From steve at pearwood.info  Mon Sep 13 13:05:10 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 13 Sep 2010 21:05:10 +1000
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <AANLkTik9x1NNNZ734m8YAqwDDUrnKA38F3=nmgk4X9kM@mail.gmail.com>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
	<i6jt4q$ubt$1@dough.gmane.org>
	<AANLkTik9x1NNNZ734m8YAqwDDUrnKA38F3=nmgk4X9kM@mail.gmail.com>
Message-ID: <201009132105.11105.steve@pearwood.info>

On Mon, 13 Sep 2010 12:29:07 pm Huy Ton That wrote:
> Hm, thanks guys; I just had to verify I was thinking sanely about it.
> I am going to pick up classmethods next. Do any of you have common
> design patterns for the usage. They are just items I haven't
> integrated in my coding, and I want to be certain I'm off on the
> right foot (:

The most common use for classmethods is to implement alternative 
constructors. For example, in the Decimal class starting in version 2.7 
and 3.1, you have two constructors:

>>> from decimal import Decimal
>>> Decimal("1.2345")
Decimal('1.2345')
>>> Decimal.from_float(1.2345)
Decimal('1.2344999999999999307220832633902318775653839111328125')

from_float is a class method.


-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 13 13:59:03 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 13 Sep 2010 21:59:03 +1000
Subject: [Tutor] exceptions problem
In-Reply-To: <4C8E0332.7020605@libero.it>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>
	<4C8BCDD0.4080909@gmail.com> <4C8E0332.7020605@libero.it>
Message-ID: <201009132159.04314.steve@pearwood.info>

On Mon, 13 Sep 2010 08:55:46 pm Francesco Loffredo wrote:
> I don't like this rough behaviour of int(), spitting out an
> exception if given a legitimate string representation of a float. Can
> some of you Tutors explain me why it must be so?

The int() function behaves as a constructor, producing an integer object 
from its argument. It has two jobs:

(1) truncate (round-to-zero) numbers to a whole number by dropping any 
fraction part without rounding; and

(2) convert strings to an integer.


So int() can truncate all of these numbers:

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> int(3)  # an int is already an int, so no change
3
>>> int(5.6)
5
>>> int(Decimal("-1.2"))
-1
>>> int(Fraction(12, 5))
2


But not this one, because it's not clear what the integer part of a 
complex number is:

>>> int(5.23 + 11.76j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int


Okay, that's numbers out of the way. Pretty straightforward.

When it comes to strings, we're doing *conversions*, not truncation, so 
we need to decide what are the rules for converting strings. The usual 
rule is that, apart from a possible leading + or - sign, we expect a 
string of digits. Nobody expects int("two hundred and thirty-seven") to 
return 237. What digits are allowed? That depends on the base -- Python 
supports bases from 2 to 36:

>>> int("123")  # base 10 is the default
123
>>> int("123ff", 16)  # hexadecimal
74751
>>> int("123ff", 36)
1777371

There's also a "base 0", which uses the string's prefix to specify the 
base:

>>> int("0x123ff", 0)  # 0x... means a hex number
74751


So what are we to make of a string like "1.95"? Obviously it's not an 
integer, and "." is not a valid digit. If you, the programmer, are 
reading in data from a file and are expecting *integers*, and somebody 
slipped in a decimal-point, that is just as troublesome as if they 
slipped in a semi-colon or the letter Z. Should "1.95" be truncated to 
1, or rounded to 2? Should it remain a float? Should the dot be 
interpreted as a digit in some unusual base?

Python refuses to guess what int("1.95") should mean, and it raises an 
error, just as it does for int("1+1") or int("two").


-- 
Steven D'Aprano

From rwobben at hotmail.com  Mon Sep 13 14:19:23 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 12:19:23 +0000
Subject: [Tutor] wierd replace problem
Message-ID: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>


Hello, 

I have this string called test with the contents of 'het is een wonder \\TIS'

Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
And I get at the python prompt this answer : 'het is een wonder TIS' 
So that's right.

Now I try the same in a IDE with this programm :
 
woorden =[]
letter_counts = {}
file = open ('alice_in_wonderland.txt', 'r')
for line in file:
    line2 = line.replace ("\\","")
    line3 = line2.lower()
    woorden = line3.split()
    for letter in woorden:
        letter_counts[letter] = letter_counts.get (letter, 0) + 1
letter_items = letter_counts.items()
letter_items.sort()
print letter_items 
 
But now Im gettting this output :
 
[('"\'tis', 1), 
 
Why does the \ stays here. It should have gone as the test in the python prompt says.
 
Roelof


  		 	   		  

From fal at libero.it  Mon Sep 13 15:07:45 2010
From: fal at libero.it (Francesco Loffredo)
Date: Mon, 13 Sep 2010 15:07:45 +0200
Subject: [Tutor] exceptions problem
In-Reply-To: <201009132159.04314.steve@pearwood.info>
References: <SNT118-W17006959748E38CE83B16FAE740@phx.gbl>	<4C8BCDD0.4080909@gmail.com>
	<4C8E0332.7020605@libero.it>
	<201009132159.04314.steve@pearwood.info>
Message-ID: <4C8E2221.6020905@libero.it>

First, *THANK YOU!* for your clear and thorough explaination, Steven.

On 13/09/2010 13.59, Steven D'Aprano wrote:
> On Mon, 13 Sep 2010 08:55:46 pm Francesco Loffredo wrote:
>> I don't like this rough behaviour of int(), spitting out an
>> exception if given a legitimate string representation of a float. Can
>> some of you Tutors explain me why it must be so?
>
> The int() function behaves as a constructor, producing an integer object
> from its argument. It has two jobs:
>
> (1) truncate (round-to-zero) numbers to a whole number by dropping any
> fraction part without rounding; and
>
> (2) convert strings to an integer.
>
>
> So int() can truncate all of these numbers:
>...
> Okay, that's numbers out of the way. Pretty straightforward.
>
> When it comes to strings, we're doing *conversions*, not truncation, so
> we need to decide what are the rules for converting strings. The usual
> rule is that, apart from a possible leading + or - sign, we expect a
> string of digits. Nobody expects int("two hundred and thirty-seven") to
> return 237. What digits are allowed? That depends on the base -- Python
> supports bases from 2 to 36:
>
>>>> int("123")  # base 10 is the default
> 123
>>>> int("123ff", 16)  # hexadecimal
> 74751
>>>> int("123ff", 36)
> 1777371
>
> There's also a "base 0", which uses the string's prefix to specify the
> base:
>
>>>> int("0x123ff", 0)  # 0x... means a hex number
> 74751
>
>
> So what are we to make of a string like "1.95"? Obviously it's not an
> integer, and "." is not a valid digit. If you, the programmer, are
> reading in data from a file and are expecting *integers*, and somebody
> slipped in a decimal-point, that is just as troublesome as if they
> slipped in a semi-colon or the letter Z. Should "1.95" be truncated to
> 1, or rounded to 2? Should it remain a float? Should the dot be
> interpreted as a digit in some unusual base?
>
> Python refuses to guess what int("1.95") should mean, and it raises an
> error, just as it does for int("1+1") or int("two").

I understand this, but I don't quite agree. I mean, I don't think 
there's anything to guess. There is no ambiguity in "3.72". As far as I 
know, there is no base, between 2 and 36, in which "." represents a 
valid digit. So it would be *very* easy to do what float() does, then 
truncate as int() already does. Anyway, now that I know, I could always 
use int(float(x))... even if I find it weird.

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3130 -  Data di rilascio: 09/12/10 08:34:00

From michael at trollope.org  Mon Sep 13 15:25:49 2010
From: michael at trollope.org (Michael Powe)
Date: Mon, 13 Sep 2010 09:25:49 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
Message-ID: <20100913132549.GG2670@cecilia>

Hello,

In your script, you need to escape each backslash, in order to have it
come out correctly to the interpreter.  IOW, in the shell, '\\' is
what is being processed.  But in your script, you want to send '\\' to
the shell, and in order to do that, you have to escape each backslash,
or '\\\\'.  

In a script, '\\' means 'send through a backslash' for shell
processing. The left-most backslash is escaping the one to its right. 

Thanks.

mp

On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
>     line2 = line.replace ("\\","")
>     line3 = line2.lower()
>     woorden = line3.split()
>     for letter in woorden:
>         letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python prompt says.
>  
> Roelof
> 
> 
>   		 	   		  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"...we built a new continent in cyberspace where we could go live and be
free. And the nice thing is that, because we built it, we didn't have
to steal it from aboriginal peoples. It was completely empty, and we
invite everyone to live there with us. No immigration restrictions.
There's room for everyone in the world. Come live in the free world
and be free. That's our idea."  -- Richard Stallman
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/afc454a1/attachment.pgp>

From michael at trollope.org  Mon Sep 13 15:26:52 2010
From: michael at trollope.org (Michael Powe)
Date: Mon, 13 Sep 2010 09:26:52 -0400
Subject: [Tutor] Documenting a Module
In-Reply-To: <1181043741.65805.1284372207332.JavaMail.open-xchange@oxltgw01.schlund.de>
References: <20100913095424.GF2670@cecilia>
	<1181043741.65805.1284372207332.JavaMail.open-xchange@oxltgw01.schlund.de>
Message-ID: <20100913132652.GH2670@cecilia>

On Mon, Sep 13, 2010 at 12:03:27PM +0200, ralf at schoenian-online.de wrote:
> 
> Hi Michael,
> ??
> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should have no problems
> with the installation.
> ??
> Ralf
> ??
> ??
> ??

Thank you, much appreciated.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA


47.3% of all statistics are made up on the spot. - Steven Wright
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/aa5cc777/attachment.pgp>

From huyslogic at gmail.com  Mon Sep 13 15:53:31 2010
From: huyslogic at gmail.com (Huy Ton That)
Date: Mon, 13 Sep 2010 09:53:31 -0400
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
In-Reply-To: <201009132105.11105.steve@pearwood.info>
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com>
	<i6jt4q$ubt$1@dough.gmane.org>
	<AANLkTik9x1NNNZ734m8YAqwDDUrnKA38F3=nmgk4X9kM@mail.gmail.com>
	<201009132105.11105.steve@pearwood.info>
Message-ID: <AANLkTindfAJDe2QQypg5KRn3L_DscNY03GE3xCKX58fy@mail.gmail.com>

Thank you all,

I was taking a look at the module decimal.py as you cited, and it makes
sense now. Looks very useful to make tools without having to instantiate
anything.

On Mon, Sep 13, 2010 at 7:05 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Mon, 13 Sep 2010 12:29:07 pm Huy Ton That wrote:
> > Hm, thanks guys; I just had to verify I was thinking sanely about it.
> > I am going to pick up classmethods next. Do any of you have common
> > design patterns for the usage. They are just items I haven't
> > integrated in my coding, and I want to be certain I'm off on the
> > right foot (:
>
> The most common use for classmethods is to implement alternative
> constructors. For example, in the Decimal class starting in version 2.7
> and 3.1, you have two constructors:
>
> >>> from decimal import Decimal
> >>> Decimal("1.2345")
> Decimal('1.2345')
> >>> Decimal.from_float(1.2345)
> Decimal('1.2344999999999999307220832633902318775653839111328125')
>
> from_float is a class method.
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/20751c29/attachment.html>

From bgailer at gmail.com  Mon Sep 13 17:07:19 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 13 Sep 2010 11:07:19 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
Message-ID: <4C8E3E27.3030006@gmail.com>

  On 9/13/2010 8:19 AM, Roelof Wobben wrote:
> Hello,
>
> I have this string called test with the contents of 'het is een wonder \\TIS'
>
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS'
> So that's right.
>
> Now I try the same in a IDE with this programm :
>
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
>      line2 = line.replace ("\\","")
>      line3 = line2.lower()
>      woorden = line3.split()
>      for letter in woorden:
>          letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items
>
> But now Im gettting this output :
>
> [('"\'tis', 1),
>
> Why does the \ stays here. It should have gone as the test in the python prompt says.
I ran your program against a 1 line file containing 'het is een wonder 
\\TIS'
The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1), 
('wonder', 1)]

Dunno why you are getting a different result.

Here is where using the debugger and going step by step can help. I have 
no experience with the IDLE debugger. Perhaps others can offer advice on 
that.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Mon Sep 13 17:20:04 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 15:20:04 +0000
Subject: [Tutor]  wierd replace problem
In-Reply-To: <SNT118-W38A251466E9C84E52E05AAAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8E3E27.3030006@gmail.com>,
	<SNT118-W38A251466E9C84E52E05AAAE770@phx.gbl>
Message-ID: <SNT118-W356B1E7A35E9303CF69E18AE770@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: bgailer at gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 15:19:12 +0000
>
>
>
>
> ----------------------------------------
>> Date: Mon, 13 Sep 2010 11:07:19 -0400
>> From: bgailer at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>> On 9/13/2010 8:19 AM, Roelof Wobben wrote:
>>> Hello,
>>>
>>> I have this string called test with the contents of 'het is een wonder \\TIS'
>>>
>>> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
>>> And I get at the python prompt this answer : 'het is een wonder TIS'
>>> So that's right.
>>>
>>> Now I try the same in a IDE with this programm :
>>>
>>> woorden =[]
>>> letter_counts = {}
>>> file = open ('alice_in_wonderland.txt', 'r')
>>> for line in file:
>>> line2 = line.replace ("\\","")
>>> line3 = line2.lower()
>>> woorden = line3.split()
>>> for letter in woorden:
>>> letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>> letter_items = letter_counts.items()
>>> letter_items.sort()
>>> print letter_items
>>>
>>> But now Im gettting this output :
>>>
>>> [('"\'tis', 1),
>>>
>>> Why does the \ stays here. It should have gone as the test in the python prompt says.
>> I ran your program against a 1 line file containing 'het is een wonder
>> \\TIS'
>> The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1),
>> ('wonder', 1)]
>>
>> Dunno why you are getting a different result.
>>
>> Here is where using the debugger and going step by step can help. I have
>> no experience with the IDLE debugger. Perhaps others can offer advice on
>> that.
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello everyone.

Chancing to (r\\, '') or (\\\\, '') did not help.

I know that there were more outcome. I would only let see that on the python prompt the \ is deleted and if I use Eclipse the / stays when I use the text from alice in wonderland.

 And im still wondering why this happens.
 Maybe put the text from alice into the python prompt and look what happens.

Roelof 		 	   		  

From bgailer at gmail.com  Mon Sep 13 17:33:23 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 13 Sep 2010 11:33:23 -0400
Subject: [Tutor] Fwd: RE:  wierd replace problem
Message-ID: <4C8E4443.70602@gmail.com>

  Forwarding to the list.

	

	

	

	


----------------------------------------
>  Date: Mon, 13 Sep 2010 11:07:19 -0400
>  From: bgailer at gmail.com
>  To: tutor at python.org
>  Subject: Re: [Tutor] wierd replace problem
>
>  On 9/13/2010 8:19 AM, Roelof Wobben wrote:
>>  Hello,
>>
>>  I have this string called test with the contents of 'het is een wonder \\TIS'
>>
>>  Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
>>  And I get at the python prompt this answer : 'het is een wonder TIS'
>>  So that's right.
>>
>>  Now I try the same in a IDE with this programm :
>>
>>  woorden =[]
>>  letter_counts = {}
>>  file = open ('alice_in_wonderland.txt', 'r')
>>  for line in file:
>>  line2 = line.replace ("\\","")
>>  line3 = line2.lower()
>>  woorden = line3.split()
>>  for letter in woorden:
>>  letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>  letter_items = letter_counts.items()
>>  letter_items.sort()
>>  print letter_items
>>
>>  But now Im gettting this output :
>>
>>  [('"\'tis', 1),
>>
>>  Why does the \ stays here. It should have gone as the test in the python prompt says.
>  I ran your program against a 1 line file containing 'het is een wonder
>  \\TIS'
>  The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1),
>  ('wonder', 1)]
>
>  Dunno why you are getting a different result.
>
>  Here is where using the debugger and going step by step can help. I have
>  no experience with the IDLE debugger. Perhaps others can offer advice on
>  that.
>  istinfo/tutor


Hello everyone.

Chancing to (r\\, '') or (\\\\, '') did not help.

I know that there were more outcome. I would only let see that on the python prompt the \ is deleted and if I use Eclipse the / stays when I use the text from alice in wonderland.

And im still wondering why this happens.
Maybe put the text from alice into the python prompt and look what happens.

Roelof
   		 	   		

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/9878aa75/attachment-0001.html>

From mhubig at gmail.com  Mon Sep 13 17:36:02 2010
From: mhubig at gmail.com (Markus Hubig)
Date: Mon, 13 Sep 2010 17:36:02 +0200
Subject: [Tutor] Serial communication ...
Message-ID: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>

Hi @all!

I'm about to write a class for serial communication on Win32 and Linux which
provides a method called "talk" to send something over the serial line,
wait for
the answer and returns it. My problem is, that I don't know how long the
answer
will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

   1. Will this work on Win32 (with select)?
   2. Should I better use twisted.internet.serialport?
   3. Will self.read(260)block until it reads the full 260 bytes?

class SerialDevice(Serial):

    def __init__(self,port):
        Serial.__init__(self)
        self.port = port
        self.baudrate = 57600
        self.bytesize = EIGHTBITS
        self.parity = PARITY_ODD
        self.stopbits = STOPBITS_TWO
        self.timeout = 0
        self.xonxoff = 0
        self.rtscts = 0
        self.dsrdtr = 0
        self.open()
        self.flush()

    def _write(self, packet):
        fileno = self.fileno()
        while True:
            readable, writeable, excepts = select( [], [fileno], [], 0.2 )
            if fileno in writeable:
                time.sleep(0.1)
                length = self.write(packet)
                break
        return length

    def _read(self):
        fileno = self.fileno()
        while True:
            readable, writeable, excepts = select( [], [fileno], [], 0.2 )
            if fileno in readable:
                time.sleep(0.1)
                packet = self.read(260)
                break
        return packet

    def talk(self, packet):
        self._write(packet)
        responce = self._read()
        return responce

Thank you, Markus

-- 
Can't read my mail? Just don't hold it that way!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/4489d0a0/attachment.html>

From michael at trollope.org  Mon Sep 13 18:17:47 2010
From: michael at trollope.org (Michael Powe)
Date: Mon, 13 Sep 2010 12:17:47 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
Message-ID: <20100913161747.GI2670@cecilia>

On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
> 
> Hello, 
> 
> I have this string called test with the contents of 'het is een wonder \\TIS'
> 
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS' 
> So that's right.
> 
> Now I try the same in a IDE with this programm :
>  
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
>     line2 = line.replace ("\\","")
>     line3 = line2.lower()
>     woorden = line3.split()
>     for letter in woorden:
>         letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items 
>  
> But now Im gettting this output :
>  
> [('"\'tis', 1), 
>  
> Why does the \ stays here. It should have gone as the test in the python prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\"'tis the season to be jolly," said santa.

When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1).  The appearance of the backslash is
fortuitous.  It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string.  IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/6d99cdae/attachment.pgp>

From michael at trollope.org  Mon Sep 13 18:27:29 2010
From: michael at trollope.org (Michael Powe)
Date: Mon, 13 Sep 2010 12:27:29 -0400
Subject: [Tutor] Documenting a Module
In-Reply-To: <1181043741.65805.1284372207332.JavaMail.open-xchange@oxltgw01.schlund.de>
References: <20100913095424.GF2670@cecilia>
	<1181043741.65805.1284372207332.JavaMail.open-xchange@oxltgw01.schlund.de>
Message-ID: <20100913162729.GJ2670@cecilia>

On Mon, Sep 13, 2010 at 12:03:27PM +0200, ralf at schoenian-online.de wrote:
> 
> Hi Michael,

> I can recommend epydoc. You can find it here:
> ??http://epydoc.sourceforge.net/??It's a nice tool and you should
> have no problems with the installation.

> Ralf

Hello,

I just want to follow up that epydoc is completely awesome and exactly
the right tool for the job.  I was able to get my doc generated and
wrapped up nicely in less time than I spent trying to get Sphinx
installed yesterday.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
I hate a fellow whom pride, or cowardice, or laziness drives into a
corner, and who does nothing when he is there but sit and <growl>; let
him come out as I do, and <bark>. -- Samuel Johnson
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/5af732e7/attachment.pgp>

From rwobben at hotmail.com  Mon Sep 13 18:37:04 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 16:37:04 +0000
Subject: [Tutor] wierd replace problem
In-Reply-To: <20100913161747.GI2670@cecilia>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<20100913161747.GI2670@cecilia>
Message-ID: <SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>




----------------------------------------
Date: Mon, 13 Sep 2010 12:17:47 -0400
From: michael at trollope.org
To: tutor at python.org
Subject: Re: [Tutor] wierd replace problem


On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
>
> Hello,
>
> I have this string called test with the contents of 'het is een wonder \\TIS'
>
> Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS'
> So that's right.
>
> Now I try the same in a IDE with this programm :
>
> woorden =[]
> letter_counts = {}
> file = open ('alice_in_wonderland.txt', 'r')
> for line in file:
> line2 = line.replace ("\\","")
> line3 = line2.lower()
> woorden = line3.split()
> for letter in woorden:
> letter_counts[letter] = letter_counts.get (letter, 0) + 1
> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items
>
> But now Im gettting this output :
>
> [('"\'tis', 1),
>
> Why does the \ stays here. It should have gone as the test in the python prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\"'tis the season to be jolly," said santa.

When you run your process against a string in that format, you get the
output shown: ('"\'tis', 1). The appearance of the backslash is
fortuitous. It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string. IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

--
Michael Powe michael at trollope.org Naugatuck CT USA
"I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath." -- H.B. Stowe

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

 
Hello Michael,
 
The original text is this : 
 
`'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'

So I think I have to replace the '.
 
Roelof
  		 	   		  

From joel.goldstick at gmail.com  Mon Sep 13 18:42:56 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 13 Sep 2010 12:42:56 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<20100913161747.GI2670@cecilia>
	<SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>
Message-ID: <AANLkTinLSYRWnQorv51j4qnqtEKFHV6jc9poY20Qqamp@mail.gmail.com>

On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
>
> ----------------------------------------
> Date: Mon, 13 Sep 2010 12:17:47 -0400
> From: michael at trollope.org
> To: tutor at python.org
> Subject: Re: [Tutor] wierd replace problem
>
>
> On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
> >
> > Hello,
> >
> > I have this string called test with the contents of 'het is een wonder
> \\TIS'
> >
> > Now I want to get rid of the \\ so I do this : test2 = test.replace
> ('\\', '')
> > And I get at the python prompt this answer : 'het is een wonder TIS'
> > So that's right.
> >
> > Now I try the same in a IDE with this programm :
> >
> > woorden =[]
> > letter_counts = {}
> > file = open ('alice_in_wonderland.txt', 'r')
> > for line in file:
> > line2 = line.replace ("\\","")
> > line3 = line2.lower()
> > woorden = line3.split()
> > for letter in woorden:
> > letter_counts[letter] = letter_counts.get (letter, 0) + 1
> > letter_items = letter_counts.items()
> > letter_items.sort()
> > print letter_items
> >
> > But now Im gettting this output :
> >
> > [('"\'tis', 1),
> >
> > Why does the \ stays here. It should have gone as the test in the python
> prompt says.
>
> Hello,
>
> Actually, on closer look I can see the answer.
>
> The original text must look something like this:
>
> \\"'tis the season to be jolly," said santa.
>
> When you run your process against a string in that format, you get the
> output shown: ('"\'tis', 1). The appearance of the backslash is
> fortuitous. It has nothing to do with the string.replace(), it's
> there to escape the single quote, which is appearing in the middle of
> a single-quoted string. IF the double-quote had not also been there,
> python would have replaced the outer quotes with double quotes, as it
> does on my system before I got to thinking about that lonely double
> quote.
>
> Thanks.
>
> mp
>
> --
> Michael Powe michael at trollope.org Naugatuck CT USA
> "I wrote what I did because as a woman, as a mother, I was oppressed
> and brokenhearted with the sorrows and injustice I saw, because as a
> Christian I felt the dishonor to Christianity, -- because as a lover
> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> Hello Michael,
>
> The original text is this :
>
> `'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
> 'tis love, 'tis love, that makes the world go round!"'
>
> So I think I have to replace the '.
>
> Roelof
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


That is a completely different problem than the one you originally posed.  I
doubt that what you inserted above is actually completely correct.  It opens
with  a back tick, has a back tick before and, then ens with what looks like
a double quote then a single quote
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/44f9a6ea/attachment-0001.html>

From rwobben at hotmail.com  Mon Sep 13 18:46:09 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 16:46:09 +0000
Subject: [Tutor]  wierd replace problem
In-Reply-To: <SNT118-W41851ADDAFA8539B3AFC42AE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<20100913161747.GI2670@cecilia>,
	<SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>,
	<AANLkTinLSYRWnQorv51j4qnqtEKFHV6jc9poY20Qqamp@mail.gmail.com>,
	<SNT118-W41851ADDAFA8539B3AFC42AE770@phx.gbl>
Message-ID: <SNT118-W26C9062690A044B41BFC6BAE770@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: joel.goldstick at gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 16:45:28 +0000
>
>
>
>
> ________________________________
>> Date: Mon, 13 Sep 2010 12:42:56 -0400
>> From: joel.goldstick at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>>
>> On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
>>> wrote:
>>
>>
>>
>> ----------------------------------------
>> Date: Mon, 13 Sep 2010 12:17:47 -0400
>> From: michael at trollope.org
>> To: tutor at python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>> On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
>>>
>>> Hello,
>>>
>>> I have this string called test with the contents of 'het is een
>> wonder \\TIS'
>>>
>>> Now I want to get rid of the \\ so I do this : test2 = test.replace
>> ('\\', '')
>>> And I get at the python prompt this answer : 'het is een wonder TIS'
>>> So that's right.
>>>
>>> Now I try the same in a IDE with this programm :
>>>
>>> woorden =[]
>>> letter_counts = {}
>>> file = open ('alice_in_wonderland.txt', 'r')
>>> for line in file:
>>> line2 = line.replace ("\\","")
>>> line3 = line2.lower()
>>> woorden = line3.split()
>>> for letter in woorden:
>>> letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>> letter_items = letter_counts.items()
>>> letter_items.sort()
>>> print letter_items
>>>
>>> But now Im gettting this output :
>>>
>>> [('"\'tis', 1),
>>>
>>> Why does the \ stays here. It should have gone as the test in the
>> python prompt says.
>>
>> Hello,
>>
>> Actually, on closer look I can see the answer.
>>
>> The original text must look something like this:
>>
>> \\"'tis the season to be jolly," said santa.
>>
>> When you run your process against a string in that format, you get the
>> output shown: ('"\'tis', 1). The appearance of the backslash is
>> fortuitous. It has nothing to do with the string.replace(), it's
>> there to escape the single quote, which is appearing in the middle of
>> a single-quoted string. IF the double-quote had not also been there,
>> python would have replaced the outer quotes with double quotes, as it
>> does on my system before I got to thinking about that lonely double
>> quote.
>>
>> Thanks.
>>
>> mp
>>
>> --
>> Michael Powe michael at trollope.org
>> Naugatuck CT USA
>> "I wrote what I did because as a woman, as a mother, I was oppressed
>> and brokenhearted with the sorrows and injustice I saw, because as a
>> Christian I felt the dishonor to Christianity, -- because as a lover
>> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> Hello Michael,
>>
>> The original text is this :
>>
>> `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
>> 'tis love, 'tis love, that makes the world go round!"'
>>
>> So I think I have to replace the '.
>>
>> Roelof
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>> That is a completely different problem than the one you originally
>> posed. I doubt that what you inserted above is actually completely
>> correct. It opens with a back tick, has a back tick before and, then
>> ens with what looks like a double quote then a single quote
>> --
>> Joel Goldstick
>>
>>
>> _______________________________________________ Tutor maillist -
>> Tutor at python.org To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello Joel,

The orginal text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
So you can see I copied it right.

Roelof 		 	   		  

From rwobben at hotmail.com  Mon Sep 13 18:58:34 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 16:58:34 +0000
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W26C9062690A044B41BFC6BAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<20100913161747.GI2670@cecilia>, ,
	<SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>, ,
	<AANLkTinLSYRWnQorv51j4qnqtEKFHV6jc9poY20Qqamp@mail.gmail.com>, ,
	<SNT118-W41851ADDAFA8539B3AFC42AE770@phx.gbl>,
	<SNT118-W26C9062690A044B41BFC6BAE770@phx.gbl>
Message-ID: <SNT118-W445D0486B6D79DB1071529AE770@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: tutor at python.org
> Date: Mon, 13 Sep 2010 16:46:09 +0000
> Subject: [Tutor] wierd replace problem
>
>
>
>
> ----------------------------------------
>> From: rwobben at hotmail.com
>> To: joel.goldstick at gmail.com
>> Subject: RE: [Tutor] wierd replace problem
>> Date: Mon, 13 Sep 2010 16:45:28 +0000
>>
>>
>>
>>
>> ________________________________
>>> Date: Mon, 13 Sep 2010 12:42:56 -0400
>>> From: joel.goldstick at gmail.com
>>> To: tutor at python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>>
>>> On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
>>>> wrote:
>>>
>>>
>>>
>>> ----------------------------------------
>>> Date: Mon, 13 Sep 2010 12:17:47 -0400
>>> From: michael at trollope.org
>>> To: tutor at python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>> On Mon, Sep 13, 2010 at 12:19:23PM +0000, Roelof Wobben wrote:
>>>>
>>>> Hello,
>>>>
>>>> I have this string called test with the contents of 'het is een
>>> wonder \\TIS'
>>>>
>>>> Now I want to get rid of the \\ so I do this : test2 = test.replace
>>> ('\\', '')
>>>> And I get at the python prompt this answer : 'het is een wonder TIS'
>>>> So that's right.
>>>>
>>>> Now I try the same in a IDE with this programm :
>>>>
>>>> woorden =[]
>>>> letter_counts = {}
>>>> file = open ('alice_in_wonderland.txt', 'r')
>>>> for line in file:
>>>> line2 = line.replace ("\\","")
>>>> line3 = line2.lower()
>>>> woorden = line3.split()
>>>> for letter in woorden:
>>>> letter_counts[letter] = letter_counts.get (letter, 0) + 1
>>>> letter_items = letter_counts.items()
>>>> letter_items.sort()
>>>> print letter_items
>>>>
>>>> But now Im gettting this output :
>>>>
>>>> [('"\'tis', 1),
>>>>
>>>> Why does the \ stays here. It should have gone as the test in the
>>> python prompt says.
>>>
>>> Hello,
>>>
>>> Actually, on closer look I can see the answer.
>>>
>>> The original text must look something like this:
>>>
>>> \\"'tis the season to be jolly," said santa.
>>>
>>> When you run your process against a string in that format, you get the
>>> output shown: ('"\'tis', 1). The appearance of the backslash is
>>> fortuitous. It has nothing to do with the string.replace(), it's
>>> there to escape the single quote, which is appearing in the middle of
>>> a single-quoted string. IF the double-quote had not also been there,
>>> python would have replaced the outer quotes with double quotes, as it
>>> does on my system before I got to thinking about that lonely double
>>> quote.
>>>
>>> Thanks.
>>>
>>> mp
>>>
>>> --
>>> Michael Powe michael at trollope.org
>>> Naugatuck CT USA
>>> "I wrote what I did because as a woman, as a mother, I was oppressed
>>> and brokenhearted with the sorrows and injustice I saw, because as a
>>> Christian I felt the dishonor to Christianity, -- because as a lover
>>> of my country, I trembled at the coming day of wrath." -- H.B. Stowe
>>>
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> Hello Michael,
>>>
>>> The original text is this :
>>>
>>> `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
>>> 'tis love, 'tis love, that makes the world go round!"'
>>>
>>> So I think I have to replace the '.
>>>
>>> Roelof
>>>
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>> That is a completely different problem than the one you originally
>>> posed. I doubt that what you inserted above is actually completely
>>> correct. It opens with a back tick, has a back tick before and, then
>>> ens with what looks like a double quote then a single quote
>>> --
>>> Joel Goldstick
>>>
>>>
>>> _______________________________________________ Tutor maillist -
>>> Tutor at python.org To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Hello Joel,
>
> The orginal text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
> So you can see I copied it right.
>
> Roelof
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I tried my programm in IDLE and the problem stays.
So I think it has to do with the text-file and how python reads it.
 
Roelof

  		 	   		  

From alan.gauld at btinternet.com  Mon Sep 13 19:11:13 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 13 Sep 2010 18:11:13 +0100
Subject: [Tutor] classmethod, staticmethod functions (decorator related)
References: <AANLkTimwL6kiPKx-4cs6aTmfjyn48ODw5mapsu6Ss1oF@mail.gmail.com><i6jt4q$ubt$1@dough.gmane.org><AANLkTik9x1NNNZ734m8YAqwDDUrnKA38F3=nmgk4X9kM@mail.gmail.com><201009132105.11105.steve@pearwood.info>
	<AANLkTindfAJDe2QQypg5KRn3L_DscNY03GE3xCKX58fy@mail.gmail.com>
Message-ID: <i6llvj$u5f$1@dough.gmane.org>


"Huy Ton That" <huyslogic at gmail.com> wrote

> I was taking a look at the module decimal.py as you cited, and it 
> makes
> sense now. Looks very useful to make tools without having to 
> instantiate
> anything.

Thats not a good way to think of them.
Doing things without instantiating is usually better done by a 
function.

Class methods are for doing things to the class.
eg you might use one to get a count of all the instances - or even a 
list.
Or you might want to reset the status of a group of instances. Or find
a particular instance out of all existing ones, and if its not there
create a new instance and return it.

Class methhods are often commonly used for providing persistence
mechanisms with databases or marshalling pools for network programming
etc etc.

>> The most common use for classmethods is to implement alternative
>> constructors. For example, in the Decimal class starting in version 
>> 2.7
>> and 3.1, you have two constructors:

Whilst I'd question if its *the most common* it is certainly another 
valid
use for them in Python which doesn't offer multiple constructors as
standard. This is rather like the factory methods of Objective C.

I've rarely worked on any significant OOP project that did not use
class methods somewhere in its design. But they tend not to be used
in the typical small-scale code used in tutorials, so it's hard for a 
newbie
to really get a feel for how they are used and why.

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



From alan.gauld at btinternet.com  Mon Sep 13 19:28:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 13 Sep 2010 18:28:46 +0100
Subject: [Tutor] wierd replace problem
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
Message-ID: <i6ln0f$36j$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote

> Now I want to get rid of the \\ so I do this : test2 = test.replace 
> ('\\', '')
> And I get at the python prompt this answer : 'het is een wonder TIS'
> So that's right.

OK,. Thats replacing a double slash in the data

> for line in file:
>    line2 = line.replace ("\\","")

And this is doing the same. Any double slashes in your file content
will be replaced.

> letter_items = letter_counts.items()
> letter_items.sort()
> print letter_items

Now we have an issue of representing characters.

> [('"\'tis', 1),

This is a representation issue. Python is using the \ to escape
the single quote since you are using single quotes on the outside.
Without the backslash the \' would look like the end of the
string to Python.

If you print the actual string it will not show the quote:

for item in letter_items:
    print item[0]

Backslashes are awkward characters because they are used
for several different special purposes as well as being characters
in their own right. If you had tried replacing almost any other
character you would not have gotten confused.

HTH,

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



>
> Why does the \ stays here. It should have gone as the test in the 
> python prompt says.
>
> Roelof
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From bgailer at gmail.com  Mon Sep 13 19:37:48 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 13 Sep 2010 13:37:48 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W445D0486B6D79DB1071529AE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<20100913161747.GI2670@cecilia>, ,
	<SNT118-W330528D591A8D2E56B834BAE770@phx.gbl>, ,
	<AANLkTinLSYRWnQorv51j4qnqtEKFHV6jc9poY20Qqamp@mail.gmail.com>, ,
	<SNT118-W41851ADDAFA8539B3AFC42AE770@phx.gbl>,
	<SNT118-W26C9062690A044B41BFC6BAE770@phx.gbl>
	<SNT118-W445D0486B6D79DB1071529AE770@phx.gbl>
Message-ID: <4C8E616C.9090904@gmail.com>

  On 9/13/2010 12:58 PM, Roelof Wobben wrote:
>
>   The orginal text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt

There are no \ in that text!


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Mon Sep 13 19:50:04 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 17:50:04 +0000
Subject: [Tutor] wierd replace problem
In-Reply-To: <i6ln0f$36j$1@dough.gmane.org>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<i6ln0f$36j$1@dough.gmane.org>
Message-ID: <SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>




----------------------------------------
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Mon, 13 Sep 2010 18:28:46 +0100
> Subject: Re: [Tutor] wierd replace problem
>
>
> "Roelof Wobben" wrote
>
>> Now I want to get rid of the \\ so I do this : test2 = test.replace
>> ('\\', '')
>> And I get at the python prompt this answer : 'het is een wonder TIS'
>> So that's right.
>
> OK,. Thats replacing a double slash in the data
>
>> for line in file:
>> line2 = line.replace ("\\","")
>
> And this is doing the same. Any double slashes in your file content
> will be replaced.
>
>> letter_items = letter_counts.items()
>> letter_items.sort()
>> print letter_items
>
> Now we have an issue of representing characters.
>
>> [('"\'tis', 1),
>
> This is a representation issue. Python is using the \ to escape
> the single quote since you are using single quotes on the outside.
> Without the backslash the \' would look like the end of the
> string to Python.
>
> If you print the actual string it will not show the quote:
>
> for item in letter_items:
> print item[0]
>
> Backslashes are awkward characters because they are used
> for several different special purposes as well as being characters
> in their own right. If you had tried replacing almost any other
> character you would not have gotten confused.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>>
>> Why does the \ stays here. It should have gone as the test in the
>> python prompt says.
>>
>> Roelof
>>
>>
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
hello Alan, 
 
Your right. Then it prints like this "'tis
Which is not right. It must be tis.
So the replace does not what it supposed to do.
 
Roelof

  		 	   		  

From bgailer at gmail.com  Mon Sep 13 20:08:46 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 13 Sep 2010 14:08:46 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<i6ln0f$36j$1@dough.gmane.org>
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>
Message-ID: <4C8E68AE.2050301@gmail.com>

  On 9/13/2010 1:50 PM, Roelof Wobben wrote:

[snip]
> hello Alan,
>
> Your right. Then it prints like this "'tis
> Which is not right. It must be tis.
> So the replace does not what it supposed to do.
>
Sorry but I am now more confused. After discovering no \ in the text 
file now you seem to have have a new specification, which is to get rid 
of the '.

I suggest you give a clear, complete and correct problem statement. 
Right now we are shooting in the dark at a moving target.

Something like.

Given the file alice_in_wonderland.txt, copied from url so-and-so

Remove these characters ...

Split into words (not letters?) where word is defined as

Count the frequency of each word.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From joel.goldstick at gmail.com  Mon Sep 13 20:18:36 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 13 Sep 2010 14:18:36 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <4C8E68AE.2050301@gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<i6ln0f$36j$1@dough.gmane.org>
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>
	<4C8E68AE.2050301@gmail.com>
Message-ID: <AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>

On Mon, Sep 13, 2010 at 2:08 PM, bob gailer <bgailer at gmail.com> wrote:

>  On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>
> [snip]
>
>  hello Alan,
>>
>> Your right. Then it prints like this "'tis
>> Which is not right. It must be tis.
>> So the replace does not what it supposed to do.
>>
>>  Sorry but I am now more confused. After discovering no \ in the text file
> now you seem to have have a new specification, which is to get rid of the '.
>
> I suggest you give a clear, complete and correct problem statement. Right
> now we are shooting in the dark at a moving target.
>
> Something like.
>
> Given the file alice_in_wonderland.txt, copied from url so-and-so
>
> Remove these characters ...
>
> Split into words (not letters?) where word is defined as
>
> Count the frequency of each word.
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

How about using str.split() to put words in a list, then run strip() over
each word with the required characters to be removed ('`")

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/1de13c52/attachment.html>

From rwobben at hotmail.com  Mon Sep 13 20:21:18 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 18:21:18 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W5892FA3C52ECA6AAF3BE46AE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<i6ln0f$36j$1@dough.gmane.org>,
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>,
	<4C8E68AE.2050301@gmail.com>,
	<SNT118-W5892FA3C52ECA6AAF3BE46AE770@phx.gbl>
Message-ID: <SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>





----------------------------------------
> From: rwobben at hotmail.com
> To: bgailer at gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 18:19:43 +0000
>
>
>
>
> ----------------------------------------
>> Date: Mon, 13 Sep 2010 14:08:46 -0400
>> From: bgailer at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>
>> [snip]
>>> hello Alan,
>>>
>>> Your right. Then it prints like this "'tis
>>> Which is not right. It must be tis.
>>> So the replace does not what it supposed to do.
>>>
>> Sorry but I am now more confused. After discovering no \ in the text
>> file now you seem to have have a new specification, which is to get rid
>> of the '.
>>
>> I suggest you give a clear, complete and correct problem statement.
>> Right now we are shooting in the dark at a moving target.
>>
>> Something like.
>>
>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>
>> Remove these characters ...
>>
>> Split into words (not letters?) where word is defined as
>>
>> Count the frequency of each word.
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> Hello,
>
> The problem as stated in the book is :
>

3.Write a program called alice_words.py that creates a text file named alice_words.txt containing an alphabetical listing of all the words found in alice_in_wonderland.txt together with the number of times each word occurs. The first 10 lines of your output file should look something like this:
Word Count
=======================
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2How many times does the word, alice, occur in the book?

The text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt

So I open the file.
Read the first rule.

This is no problem for me.

Then I want to remove some characters like ' , " when the word in the text begins with these characters.
And there is the problem. The ' and " can't be removed with replace.
So in the output you will see something like this "dark instead of dark

word is the words of the sentence which is read in from the text-file.

Am i now clear what the problem is Im facing.

Roelof 		 	   		  

From rwobben at hotmail.com  Mon Sep 13 20:24:11 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 18:24:11 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W2769B378CC19C64B462752AE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<i6ln0f$36j$1@dough.gmane.org>,
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>,
	<4C8E68AE.2050301@gmail.com>,
	<AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>,
	<SNT118-W2769B378CC19C64B462752AE770@phx.gbl>
Message-ID: <SNT118-W2716D0962991397EA36B56AE770@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: joel.goldstick at gmail.com
> Subject: RE: [Tutor] wierd replace problem
> Date: Mon, 13 Sep 2010 18:23:36 +0000
>
>
>
>
> ________________________________
>> Date: Mon, 13 Sep 2010 14:18:36 -0400
>> From: joel.goldstick at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] wierd replace problem
>>
>>
>>
>> On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
>>> wrote:
>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>
>> [snip]
>>
>> hello Alan,
>>
>> Your right. Then it prints like this "'tis
>> Which is not right. It must be tis.
>> So the replace does not what it supposed to do.
>>
>> Sorry but I am now more confused. After discovering no \ in the text
>> file now you seem to have have a new specification, which is to get rid
>> of the '.
>>
>> I suggest you give a clear, complete and correct problem statement.
>> Right now we are shooting in the dark at a moving target.
>>
>> Something like.
>>
>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>
>> Remove these characters ...
>>
>> Split into words (not letters?) where word is defined as
>>
>> Count the frequency of each word.
>>
>>
>> --
>> Bob Gailer
>> 919-636-4239
>> Chapel Hill NC
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>> How about using str.split() to put words in a list, then run strip()
>> over each word with the required characters to be removed ('`")
>>
>> --
>> Joel Goldstick
>>
>>
>> _______________________________________________ Tutor maillist -
>> Tutor at python.org To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Hello Joel.

That can be a solution but when i have --dark the -- must be removed.
But in a-piece the - must not be removed.

Roelof 		 	   		  

From mhubig at gmail.com  Mon Sep 13 20:26:47 2010
From: mhubig at gmail.com (Markus Hubig)
Date: Mon, 13 Sep 2010 20:26:47 +0200
Subject: [Tutor] Serial communication ...
In-Reply-To: <AANLkTim7WQx5eoBqjL=RD63iJr+nvz9yyqsvxK2DYYWS@mail.gmail.com>
References: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
	<AANLkTim7WQx5eoBqjL=RD63iJr+nvz9yyqsvxK2DYYWS@mail.gmail.com>
Message-ID: <AANLkTi=2yqXp0_jtRj0qKxk4DGuCaD-CZsq__bT2cMFp@mail.gmail.com>

On Mon, Sep 13, 2010 at 6:10 PM, Andr? da Palma <andrefsp at gmail.com> wrote:

> Last year i was working with serial communication as well and there is
> already a library for python, i guess it's pySerial. Try to google it,
> perhaps

it can be useful for you.


Yes you're totally right! And that's the package im using im my posted code,
but im about to customize Serial class a litte bit. My code actually starts
with:

from serial import Serial, SerialExceptionfrom serial import
EIGHTBITS, PARITY_ODD, STOPBITS_TWO

And inherits from serial.Serial:

class SerialDevice(Serial):    def __init__(self,port):
Serial.__init__(self)

And serial is the module name of pyserial <http://pyserial.sourceforge.net>
 ...

How did you sense the end the stuff you're receiving via the serial line?

- Markus

-- 
Can't read my mail? Just don't hold it that way!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/1df59960/attachment-0001.html>

From bkjones at gmail.com  Mon Sep 13 20:31:00 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 13 Sep 2010 14:31:00 -0400
Subject: [Tutor] What's the best way to ask forgiveness here?
Message-ID: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>

I've been coding Python long enough that 'asking forgiveness instead of
permission' is my first instinct, but the resulting code is sometimes
clumsy, and I wonder if someone can suggest something I'm missing, or at
least validate what's going on here in some way.

What I'm trying to do is write a file to a directory. However, the directory
may not exist the first time I try to write a file there, so I'm going to
first try to write the file, and if I get an exception, create the directory
(er, *try* to), and *then* write the file there. Here's my first shot at the
code:

        try:
            self.save_file(picfile_fullpath, picdata)
        except IOError as err:
            # directory doesn't exist. Try to create it.
            try:
                os.makedirs(picfile_fullpath)
            except OSError as oserr:
                logging.error("Can't create file path: %s (%s)" %
(picfile_fullpath, oserr))
            else:
                # Created dir, now write file.
                try:
                    self.save_file(picfile_fullpath, picdata)
                except IOError as err:
                    logging.error("Bailing. Couldn't save file %s (%s)" %
(picfile_fullpath, err))
                    return False

Doesn't this seem less readable than the 'ask permission' equivalent? I
think it does, but in this case asking permission for every single operation
when the dir will only need to be created a single time (and then may be
written to several hundred times) is pretty wasteful.

I suppose I could set some sentinel variable and check for it in a while
loop, but then I need some other scaffolding code to make sure I don't
infinitely loop trying to create the directory, and probably some other
stuff I'm forgetting, so it strikes me as being just as messy.

Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/8ffabf7d/attachment.html>

From adam.jtm30 at gmail.com  Mon Sep 13 20:33:45 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 13 Sep 2010 19:33:45 +0100
Subject: [Tutor] Serial communication ...
In-Reply-To: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
References: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
Message-ID: <4C8E6E89.1070807@gmail.com>

On 13/09/10 16:36, Markus Hubig wrote:
> Hi @all!
>
> I'm about to write a class for serial communication on Win32 and Linux 
> which
> provides a method called "talk" to send something over the serial 
> line, wait for
> the answer and returns it. My problem is, that I don't know how long 
> the answer
> will be (ok max 260 bytes but most answers are much smaller).
>
> This is what I have now, please leave some comments:
>
>    1. Will this work on Win32 (with select)?
>    2. Should I better use twisted.internet.serialport?
>    3. Will self.read(260)block until it reads the full 260 bytes?
>
> class SerialDevice(Serial):
>
>     def __init__(self,port):
>         Serial.__init__(self)
>         self.port = port
>         self.baudrate = 57600
>         self.bytesize = EIGHTBITS
>         self.parity = PARITY_ODD
>         self.stopbits = STOPBITS_TWO
>         self.timeout = 0
>         self.xonxoff = 0
>         self.rtscts = 0
>         self.dsrdtr = 0
>         self.open()
>         self.flush()
>     def _write(self, packet):
>         fileno = self.fileno()
>         while True:
>             readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>             if fileno in writeable:
>                 time.sleep(0.1)
>                 length = self.write(packet)
>                 break
>         return length
>     def _read(self):
>         fileno = self.fileno()
>         while True:
>             readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>             if fileno in readable:
>                 time.sleep(0.1)
>                 packet = self.read(260)
>                 break
>         return packet
>     def talk(self, packet):
>         self._write(packet)
>         responce = self._read()
>         return responce
>
> Thank you, Markus
>
> -- 
> Can't read my mail? Just don't hold it that way!
Ideally you would send a specific ending packet and you read one byte at 
a time until the right sequence comes up. Alternatively you could have 
the first byte as a length indicator. The only other options I can think 
of are fixed length or a specific timeout.
HTH.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/1c53802a/attachment.html>

From emile at fenx.com  Mon Sep 13 20:40:08 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 13 Sep 2010 11:40:08 -0700
Subject: [Tutor] Serial communication ...
In-Reply-To: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
References: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
Message-ID: <i6lr9r$p61$1@dough.gmane.org>

On 9/13/2010 8:36 AM Markus Hubig said...
> Hi @all!
>
> I'm about to write a class for serial communication on Win32 and Linux which
> provides a method called "talk" to send something over the serial line,
> wait for
> the answer and returns it. My problem is, that I don't know how long the
> answer
> will be (ok max 260 bytes but most answers are much smaller).
>
> This is what I have now, please leave some comments:
>
>     1. Will this work on Win32 (with select)?
>     2. Should I better use twisted.internet.serialport?
>     3. Will self.read(260)block until it reads the full 260 bytes?
>

You're subclassing Serial -- the answers to your questions depend on 
what that is.  So, what is it? Does it support windows? Has anyone 
compared/contrasted it to twisted.internet.serialport?  What does its 
read do?  And finally, perhaps, does it have it's own support 
group/list?  You'll probably get better answers directly from there than 
here.

HTH,

Emile




> class SerialDevice(Serial):
>
>      def __init__(self,port):
>          Serial.__init__(self)
>          self.port = port
>          self.baudrate = 57600
>          self.bytesize = EIGHTBITS
>          self.parity = PARITY_ODD
>          self.stopbits = STOPBITS_TWO
>          self.timeout = 0
>          self.xonxoff = 0
>          self.rtscts = 0
>          self.dsrdtr = 0
>          self.open()
>          self.flush()
>
>      def _write(self, packet):
>          fileno = self.fileno()
>          while True:
>              readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>              if fileno in writeable:
>                  time.sleep(0.1)
>                  length = self.write(packet)
>                  break
>          return length
>
>      def _read(self):
>          fileno = self.fileno()
>          while True:
>              readable, writeable, excepts = select( [], [fileno], [], 0.2 )
>              if fileno in readable:
>                  time.sleep(0.1)
>                  packet = self.read(260)
>                  break
>          return packet
>
>      def talk(self, packet):
>          self._write(packet)
>          responce = self._read()
>          return responce
>
> Thank you, Markus
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From emile at fenx.com  Mon Sep 13 20:56:01 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 13 Sep 2010 11:56:01 -0700
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
Message-ID: <i6ls7l$tmo$1@dough.gmane.org>

On 9/13/2010 11:31 AM Brian Jones said...
> I've been coding Python long enough that 'asking forgiveness instead of
> permission' is my first instinct, but the resulting code is sometimes
> clumsy, and I wonder if someone can suggest something I'm missing, or at
> least validate what's going on here in some way.
>
> What I'm trying to do is write a file to a directory. However, the directory
> may not exist the first time I try to write a file there, so I'm going to
> first try to write the file, and if I get an exception, create the directory
> (er, *try* to), and *then* write the file there. Here's my first shot at the
> code:
>
>          try:
>              self.save_file(picfile_fullpath, picdata)
>          except IOError as err:
>              # directory doesn't exist. Try to create it.
>              try:
>                  os.makedirs(picfile_fullpath)
>              except OSError as oserr:
>                  logging.error("Can't create file path: %s (%s)" %
> (picfile_fullpath, oserr))
>              else:
>                  # Created dir, now write file.
>                  try:
>                      self.save_file(picfile_fullpath, picdata)
>                  except IOError as err:
>                      logging.error("Bailing. Couldn't save file %s (%s)" %
> (picfile_fullpath, err))
>                      return False

Unless this is in a tight loop, I think I'd write:

try:
     os.makedirs(picfile_fullpath)
     try:
         self.save_file(picfile_fullpath, picdata)
         return True
         # all/only error handling code follows.
     except IOError as err:
         logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))
         return False
except OSError as oserr:
     logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))
     return False

which eliminates the duplicated save_file step.

>
> Doesn't this seem less readable than the 'ask permission' equivalent? I
> think it does, but in this case asking permission for every single operation
> when the dir will only need to be created a single time (and then may be
> written to several hundred times) is pretty wasteful.

Agreed -- if it's in a loop, you'd want to only check once.  Of course, 
if the directory is eg an nfs share, continued access could be an issue.

HTH,

Emile


>
> I suppose I could set some sentinel variable and check for it in a while
> loop, but then I need some other scaffolding code to make sure I don't
> infinitely loop trying to create the directory, and probably some other
> stuff I'm forgetting, so it strikes me as being just as messy.
>
> Is there a clean sort of pattern to apply in instances like this?
>
> Thanks.
> brian
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From mhubig at gmail.com  Mon Sep 13 21:02:37 2010
From: mhubig at gmail.com (Markus Hubig)
Date: Mon, 13 Sep 2010 21:02:37 +0200
Subject: [Tutor] Serial communication ...
In-Reply-To: <4C8E6E89.1070807@gmail.com>
References: <AANLkTikvvFZckPLYZf5ApQzG5_qpXL_Z=t+CC5w7YBj7@mail.gmail.com>
	<4C8E6E89.1070807@gmail.com>
Message-ID: <AANLkTik=76iMcJHXwKLp9R-Ze-=Y1=Ft3CLTineuGhqA@mail.gmail.com>

On Mon, Sep 13, 2010 at 8:33 PM, Adam Bark <adam.jtm30 at gmail.com> wrote:

> Ideally you would send a specific ending packet and you read one byte at a
> time until the
>
right sequence comes up. Alternatively you could have the first byte as a
> length indicator.
>

Oh my dear! You're damn right! The protocol im implementing is fixed so I
can't
at an ending packet, but every message contains an length field I can use
for this!!
How could I miss this?!

Thank you, Markus

-- 
Can't read my mail? Just don't hold it that way!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/78676db7/attachment.html>

From adam.jtm30 at gmail.com  Mon Sep 13 21:07:33 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 13 Sep 2010 20:07:33 +0100
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
Message-ID: <4C8E7675.8090101@gmail.com>

On 13/09/10 19:31, Brian Jones wrote:
> I've been coding Python long enough that 'asking forgiveness instead 
> of permission' is my first instinct, but the resulting code is 
> sometimes clumsy, and I wonder if someone can suggest something I'm 
> missing, or at least validate what's going on here in some way.
>
> What I'm trying to do is write a file to a directory. However, the 
> directory may not exist the first time I try to write a file there, so 
> I'm going to first try to write the file, and if I get an exception, 
> create the directory (er, *try* to), and *then* write the file there. 
> Here's my first shot at the code:
>
>         try:
>             self.save_file(picfile_fullpath, picdata)
>         except IOError as err:
>             # directory doesn't exist. Try to create it.
>             try:
>                 os.makedirs(picfile_fullpath)
>             except OSError as oserr:
>                 logging.error("Can't create file path: %s (%s)" % 
> (picfile_fullpath, oserr))
>             else:
>                 # Created dir, now write file.
>                 try:
>                     self.save_file(picfile_fullpath, picdata)
>                 except IOError as err:
>                     logging.error("Bailing. Couldn't save file %s 
> (%s)" % (picfile_fullpath, err))
>                     return False
>
> Doesn't this seem less readable than the 'ask permission' equivalent? 
> I think it does, but in this case asking permission for every single 
> operation when the dir will only need to be created a single time (and 
> then may be written to several hundred times) is pretty wasteful.
>
> I suppose I could set some sentinel variable and check for it in a 
> while loop, but then I need some other scaffolding code to make sure I 
> don't infinitely loop trying to create the directory, and probably 
> some other stuff I'm forgetting, so it strikes me as being just as messy.
>
> Is there a clean sort of pattern to apply in instances like this?
>
> Thanks.
> brian

How about something like this?

try:
     os.makedirs(picfile_fullpath)
     self.save_file(picfile_fullpath, picdata)
except IOError, OSError as err:
     if type(err) is OSError:
         logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))
         try:
             self.save_file(picfile_fullpath, picdata)
         except IOError:
             logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))
     else:
         logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

This saves you one try except and the else although it adds an if else. 
Either way it's not as far nested.
I just thought up another way that just takes two try excepts:

try:
     try:
         os.makedirs(picfile_fullpath)
         self.save_file(picfile_fullpath, picdata)
     except OSError as oserr:
         logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))
         self.save_file(picfile_fullpath, picdata)
except IOError as err:
     logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))
     return False

HTH

From evert.rol at gmail.com  Mon Sep 13 21:07:03 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 13 Sep 2010 21:07:03 +0200
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
Message-ID: <3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>

> I've been coding Python long enough that 'asking forgiveness instead of permission' is my first instinct, but the resulting code is sometimes clumsy, and I wonder if someone can suggest something I'm missing, or at least validate what's going on here in some way. 
> 
> What I'm trying to do is write a file to a directory. However, the directory may not exist the first time I try to write a file there, so I'm going to first try to write the file, and if I get an exception, create the directory (er, *try* to), and *then* write the file there.

That would work.
Though I would just try to create the error directory first. If that fails, I check the error message/code in the except clause: if it indicates the directory already exists, I pass the exception, otherwise reraise it.
Then I continue with creating the file within the directory I now am certain of exists.
Note 1: certain is only half: some other process could remove the directory in the split second between my code creating it and my code creating the file. If you think that could happen, you'll need to look at the other ways to do this.
Note 2: the directory can exist, but not have write access to your process. So between the try-except for creating a directory and the try-except for creating a file, you may put in a try-except for chmod. Of course, if you're not the owner, both the chmod and file creation will fail (I'm assuming some *nix platform here, btw).

> Here's my first shot at the code: 
> 
>         try:  
>             self.save_file(picfile_fullpath, picdata)
>         except IOError as err:
>             # directory doesn't exist. Try to create it.

Careful: you're not checking the actually error given by the exception. There may be more than one reason that the file can't be created (examples: the permissions mentioned above, or some file creation limit in a directory).


>             try:  
>                 os.makedirs(picfile_fullpath)
>             except OSError as oserr:
>                 logging.error("Can't create file path: %s (%s)" % (picfile_fullpath, oserr))
>             else: 
>                 # Created dir, now write file.
>                 try:  
>                     self.save_file(picfile_fullpath, picdata)
>                 except IOError as err:
>                     logging.error("Bailing. Couldn't save file %s (%s)" % (picfile_fullpath, err)) 
>                     return False
> 
> Doesn't this seem less readable than the 'ask permission' equivalent? I think it does, but in this case asking permission for every single operation when the dir will only need to be created a single time (and then may be written to several hundred times) is pretty wasteful.

One of the things I once read (but I forgot where) on this issue, is the usual "it depends". It depends whether you except that often, the directory doesn't exist and the file can't directly be created. In that case, if may be quicker to ask permission first (simple if-statement). If you expect that in general, you can immediately create the file within the directory (so an exception is unlikely to occur), then use a try-except clause.
But don't take my word for it; I'd be curious what others on this list say about this.


> 
> I suppose I could set some sentinel variable and check for it in a while loop, but then I need some other scaffolding code to make sure I don't infinitely loop trying to create the directory, and probably some other stuff I'm forgetting, so it strikes me as being just as messy. 
> 
> Is there a clean sort of pattern to apply in instances like this? 

I guess not, though readability of code is an important thing to consider. In this case, I don't find the correctly unreadable, but at some point, these things do tend to get out of hand and you're better off coding it differently (perhaps even using functions).


  Evert


From bkjones at gmail.com  Mon Sep 13 21:12:12 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 13 Sep 2010 15:12:12 -0400
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
	<3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
Message-ID: <AANLkTimcaJJ69DkjFmH_pbT0PxzxwF9n9COK4-tdv-C-@mail.gmail.com>

Thanks for the replies so far. One thing that's probably relevant: once a
directory is created, I can expect to write a couple of hundred files to it,
so doing a 'try os.makedirs' right off the bat strikes me as coding for the
*least* common case instead of the *most* common (which is that the
directory exists and the file write succeeds). If this were a one-off file
write.... well then things get easier, but I'd like to avoid attempting a
makedirs 100 times when 99 of those times I know it'll give me an error.

brian

On Mon, Sep 13, 2010 at 3:07 PM, Evert Rol <evert.rol at gmail.com> wrote:

> > I've been coding Python long enough that 'asking forgiveness instead of
> permission' is my first instinct, but the resulting code is sometimes
> clumsy, and I wonder if someone can suggest something I'm missing, or at
> least validate what's going on here in some way.
> >
> > What I'm trying to do is write a file to a directory. However, the
> directory may not exist the first time I try to write a file there, so I'm
> going to first try to write the file, and if I get an exception, create the
> directory (er, *try* to), and *then* write the file there.
>
> That would work.
> Though I would just try to create the error directory first. If that fails,
> I check the error message/code in the except clause: if it indicates the
> directory already exists, I pass the exception, otherwise reraise it.
> Then I continue with creating the file within the directory I now am
> certain of exists.
> Note 1: certain is only half: some other process could remove the directory
> in the split second between my code creating it and my code creating the
> file. If you think that could happen, you'll need to look at the other ways
> to do this.
> Note 2: the directory can exist, but not have write access to your process.
> So between the try-except for creating a directory and the try-except for
> creating a file, you may put in a try-except for chmod. Of course, if you're
> not the owner, both the chmod and file creation will fail (I'm assuming some
> *nix platform here, btw).
>
> > Here's my first shot at the code:
> >
> >         try:
> >             self.save_file(picfile_fullpath, picdata)
> >         except IOError as err:
> >             # directory doesn't exist. Try to create it.
>
> Careful: you're not checking the actually error given by the exception.
> There may be more than one reason that the file can't be created (examples:
> the permissions mentioned above, or some file creation limit in a
> directory).
>
>
> >             try:
> >                 os.makedirs(picfile_fullpath)
> >             except OSError as oserr:
> >                 logging.error("Can't create file path: %s (%s)" %
> (picfile_fullpath, oserr))
> >             else:
> >                 # Created dir, now write file.
> >                 try:
> >                     self.save_file(picfile_fullpath, picdata)
> >                 except IOError as err:
> >                     logging.error("Bailing. Couldn't save file %s (%s)" %
> (picfile_fullpath, err))
> >                     return False
> >
> > Doesn't this seem less readable than the 'ask permission' equivalent? I
> think it does, but in this case asking permission for every single operation
> when the dir will only need to be created a single time (and then may be
> written to several hundred times) is pretty wasteful.
>
> One of the things I once read (but I forgot where) on this issue, is the
> usual "it depends". It depends whether you except that often, the directory
> doesn't exist and the file can't directly be created. In that case, if may
> be quicker to ask permission first (simple if-statement). If you expect that
> in general, you can immediately create the file within the directory (so an
> exception is unlikely to occur), then use a try-except clause.
> But don't take my word for it; I'd be curious what others on this list say
> about this.
>
>
> >
> > I suppose I could set some sentinel variable and check for it in a while
> loop, but then I need some other scaffolding code to make sure I don't
> infinitely loop trying to create the directory, and probably some other
> stuff I'm forgetting, so it strikes me as being just as messy.
> >
> > Is there a clean sort of pattern to apply in instances like this?
>
> I guess not, though readability of code is an important thing to consider.
> In this case, I don't find the correctly unreadable, but at some point,
> these things do tend to get out of hand and you're better off coding it
> differently (perhaps even using functions).
>
>
>  Evert
>
>


-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/4edc9346/attachment-0001.html>

From davidheiserca at gmail.com  Mon Sep 13 21:21:22 2010
From: davidheiserca at gmail.com (davidheiserca at gmail.com)
Date: Mon, 13 Sep 2010 12:21:22 -0700
Subject: [Tutor] What's the best way to ask forgiveness here?
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
	<i6ls7l$tmo$1@dough.gmane.org>
Message-ID: <4916721402C245FFAE20BA48C9863EDE@dheiser>


I suggest something like:

try:
    os.makedirs(path)
except:
    pass
open("%s/%s" % (path, filename), 'w').write(filedata)


----- Original Message ----- 
From: "Emile van Sebille" <emile at fenx.com>
To: <tutor at python.org>
Sent: Monday, September 13, 2010 11:56 AM
Subject: Re: [Tutor] What's the best way to ask forgiveness here?


> On 9/13/2010 11:31 AM Brian Jones said...
>> I've been coding Python long enough that 'asking forgiveness instead of
>> permission' is my first instinct, but the resulting code is sometimes
>> clumsy, and I wonder if someone can suggest something I'm missing, or at
>> least validate what's going on here in some way.
>>
>> What I'm trying to do is write a file to a directory. However, the 
>> directory
>> may not exist the first time I try to write a file there, so I'm going to
>> first try to write the file, and if I get an exception, create the 
>> directory
>> (er, *try* to), and *then* write the file there. Here's my first shot at 
>> the
>> code:
>>
>>          try:
>>              self.save_file(picfile_fullpath, picdata)
>>          except IOError as err:
>>              # directory doesn't exist. Try to create it.
>>              try:
>>                  os.makedirs(picfile_fullpath)
>>              except OSError as oserr:
>>                  logging.error("Can't create file path: %s (%s)" %
>> (picfile_fullpath, oserr))
>>              else:
>>                  # Created dir, now write file.
>>                  try:
>>                      self.save_file(picfile_fullpath, picdata)
>>                  except IOError as err:
>>                      logging.error("Bailing. Couldn't save file %s (%s)" 
>> %
>> (picfile_fullpath, err))
>>                      return False
>
> Unless this is in a tight loop, I think I'd write:
>
> try:
>     os.makedirs(picfile_fullpath)
>     try:
>         self.save_file(picfile_fullpath, picdata)
>         return True
>         # all/only error handling code follows.
>     except IOError as err:
>         logging.error("Bailing. Couldn't save file %s (%s)" % 
> (picfile_fullpath, err))
>         return False
> except OSError as oserr:
>     logging.error("Can't create file path: %s (%s)" % (picfile_fullpath, 
> oserr))
>     return False
>
> which eliminates the duplicated save_file step.
>
>>
>> Doesn't this seem less readable than the 'ask permission' equivalent? I
>> think it does, but in this case asking permission for every single 
>> operation
>> when the dir will only need to be created a single time (and then may be
>> written to several hundred times) is pretty wasteful.
>
> Agreed -- if it's in a loop, you'd want to only check once.  Of course, if 
> the directory is eg an nfs share, continued access could be an issue.
>
> HTH,
>
> Emile
>
>
>>
>> I suppose I could set some sentinel variable and check for it in a while
>> loop, but then I need some other scaffolding code to make sure I don't
>> infinitely loop trying to create the directory, and probably some other
>> stuff I'm forgetting, so it strikes me as being just as messy.
>>
>> Is there a clean sort of pattern to apply in instances like this?
>>
>> Thanks.
>> brian
>>
>>
>>
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor 


From rwobben at hotmail.com  Mon Sep 13 21:44:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 13 Sep 2010 19:44:46 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTimnca8m=BYYN1RVpa3w=LO9LmG8NpDiCAYRdBLb@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<i6ln0f$36j$1@dough.gmane.org>,
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>,
	<4C8E68AE.2050301@gmail.com>,
	<AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>,
	<SNT118-W2769B378CC19C64B462752AE770@phx.gbl>,
	<SNT118-W2716D0962991397EA36B56AE770@phx.gbl>,
	<AANLkTimnca8m=BYYN1RVpa3w=LO9LmG8NpDiCAYRdBLb@mail.gmail.com>
Message-ID: <SNT118-W25F9A923C9AA262FF88B14AE770@phx.gbl>




________________________________
> Date: Mon, 13 Sep 2010 15:31:08 -0400
> Subject: Re: [Tutor] FW: wierd replace problem
> From: joel.goldstick at gmail.com
> To: rwobben at hotmail.com
>
>
>
> On Mon, Sep 13, 2010 at 2:24 PM, Roelof Wobben
>> wrote:
>
>
>
> ----------------------------------------
>> From: rwobben at hotmail.com
>> To: joel.goldstick at gmail.com
>> Subject: RE: [Tutor] wierd replace problem
>> Date: Mon, 13 Sep 2010 18:23:36 +0000
>>
>>
>>
>>
>> ________________________________
>>> Date: Mon, 13 Sep 2010 14:18:36 -0400
>>> From: joel.goldstick at gmail.com
>>> To: tutor at python.org
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>>
>>>
>>> On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
>>>> wrote:
>>> On 9/13/2010 1:50 PM, Roelof Wobben wrote:
>>>
>>> [snip]
>>>
>>> hello Alan,
>>>
>>> Your right. Then it prints like this "'tis
>>> Which is not right. It must be tis.
>>> So the replace does not what it supposed to do.
>>>
>>> Sorry but I am now more confused. After discovering no \ in the text
>>> file now you seem to have have a new specification, which is to get rid
>>> of the '.
>>>
>>> I suggest you give a clear, complete and correct problem statement.
>>> Right now we are shooting in the dark at a moving target.
>>>
>>> Something like.
>>>
>>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>>
>>> Remove these characters ...
>>>
>>> Split into words (not letters?) where word is defined as
>>>
>>> Count the frequency of each word.
>>>
>>>
>>> --
>>> Bob Gailer
>>> 919-636-4239
>>> Chapel Hill NC
>>>
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>> How about using str.split() to put words in a list, then run strip()
>>> over each word with the required characters to be removed ('`")
>>>
>>> --
>>> Joel Goldstick
>>>
>>>
>>> _______________________________________________ Tutor maillist -
>>> Tutor at python.org To unsubscribe or change
> subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> Hello Joel.
>
> That can be a solution but when i have --dark the -- must be removed.
> But in a-piece the - must not be removed.
>
> Roelof
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> strip only removes from start and end of string. Not from the middle,
> so a-piece would stay as a word
>
> --
> Joel Goldstick
>
 
Oke, 
 
I have tried that but then I see this message :
 
 File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 8
    letter2 = letter.strip('`")
                              ^
SyntaxError: EOL while scanning string literal
 
Change it to (''`"") do not help either.
 
Roelof

  		 	   		  

From adam.jtm30 at gmail.com  Mon Sep 13 22:05:43 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Mon, 13 Sep 2010 21:05:43 +0100
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTimcaJJ69DkjFmH_pbT0PxzxwF9n9COK4-tdv-C-@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>	<3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
	<AANLkTimcaJJ69DkjFmH_pbT0PxzxwF9n9COK4-tdv-C-@mail.gmail.com>
Message-ID: <4C8E8417.4020203@gmail.com>

On 13/09/10 20:12, Brian Jones wrote:
> Thanks for the replies so far. One thing that's probably relevant: 
> once a directory is created, I can expect to write a couple of hundred 
> files to it, so doing a 'try os.makedirs' right off the bat strikes me 
> as coding for the *least* common case instead of the *most* common 
> (which is that the directory exists and the file write succeeds). If 
> this were a one-off file write.... well then things get easier, but 
> I'd like to avoid attempting a makedirs 100 times when 99 of those 
> times I know it'll give me an error.
>
> brian
>
> On Mon, Sep 13, 2010 at 3:07 PM, Evert Rol <evert.rol at gmail.com 
> <mailto:evert.rol at gmail.com>> wrote:
>
>     > I've been coding Python long enough that 'asking forgiveness
>     instead of permission' is my first instinct, but the resulting
>     code is sometimes clumsy, and I wonder if someone can suggest
>     something I'm missing, or at least validate what's going on here
>     in some way.
>     >
>     > What I'm trying to do is write a file to a directory. However,
>     the directory may not exist the first time I try to write a file
>     there, so I'm going to first try to write the file, and if I get
>     an exception, create the directory (er, *try* to), and *then*
>     write the file there.
>
>     That would work.
>     Though I would just try to create the error directory first. If
>     that fails, I check the error message/code in the except clause:
>     if it indicates the directory already exists, I pass the
>     exception, otherwise reraise it.
>     Then I continue with creating the file within the directory I now
>     am certain of exists.
>     Note 1: certain is only half: some other process could remove the
>     directory in the split second between my code creating it and my
>     code creating the file. If you think that could happen, you'll
>     need to look at the other ways to do this.
>     Note 2: the directory can exist, but not have write access to your
>     process. So between the try-except for creating a directory and
>     the try-except for creating a file, you may put in a try-except
>     for chmod. Of course, if you're not the owner, both the chmod and
>     file creation will fail (I'm assuming some *nix platform here, btw).
>
>     > Here's my first shot at the code:
>     >
>     >         try:
>     >             self.save_file(picfile_fullpath, picdata)
>     >         except IOError as err:
>     >             # directory doesn't exist. Try to create it.
>
>     Careful: you're not checking the actually error given by the
>     exception. There may be more than one reason that the file can't
>     be created (examples: the permissions mentioned above, or some
>     file creation limit in a directory).
>
>
>     >             try:
>     >                 os.makedirs(picfile_fullpath)
>     >             except OSError as oserr:
>     >                 logging.error("Can't create file path: %s (%s)"
>     % (picfile_fullpath, oserr))
>     >             else:
>     >                 # Created dir, now write file.
>     >                 try:
>     >                     self.save_file(picfile_fullpath, picdata)
>     >                 except IOError as err:
>     >                     logging.error("Bailing. Couldn't save file
>     %s (%s)" % (picfile_fullpath, err))
>     >                     return False
>     >
>     > Doesn't this seem less readable than the 'ask permission'
>     equivalent? I think it does, but in this case asking permission
>     for every single operation when the dir will only need to be
>     created a single time (and then may be written to several hundred
>     times) is pretty wasteful.
>
>     One of the things I once read (but I forgot where) on this issue,
>     is the usual "it depends". It depends whether you except that
>     often, the directory doesn't exist and the file can't directly be
>     created. In that case, if may be quicker to ask permission first
>     (simple if-statement). If you expect that in general, you can
>     immediately create the file within the directory (so an exception
>     is unlikely to occur), then use a try-except clause.
>     But don't take my word for it; I'd be curious what others on this
>     list say about this.
>
>
>     >
>     > I suppose I could set some sentinel variable and check for it in
>     a while loop, but then I need some other scaffolding code to make
>     sure I don't infinitely loop trying to create the directory, and
>     probably some other stuff I'm forgetting, so it strikes me as
>     being just as messy.
>     >
>     > Is there a clean sort of pattern to apply in instances like this?
>
>     I guess not, though readability of code is an important thing to
>     consider. In this case, I don't find the correctly unreadable, but
>     at some point, these things do tend to get out of hand and you're
>     better off coding it differently (perhaps even using functions).
>
>
>      Evert
>
Well surely then you just check the directory first with a try: 
os.makedirs. Then your try: self.savefile for each file.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/b0dd2f4d/attachment-0001.html>

From coolankur2006 at gmail.com  Mon Sep 13 22:45:41 2010
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Tue, 14 Sep 2010 02:15:41 +0530
Subject: [Tutor] input problem
Message-ID: <AANLkTi=vKtZ5NLJqQi68Cx+iAaiiuh5_cp6xFAGVmHBk@mail.gmail.com>

Suppose i am taking input or various variables like
a=raw_input("...............") //hello
b=raw_input("................")//hi
c=raw_input("...............")//hello
d=raw_input("..........")//hello
but i want to run a common function when input is hello

so instead of
if a=="hello":
 fun()
then again for b and then again for c then d and so on i have to apply the
code for the specific variable ,
i want to run the function whenever in the code input is "hello"
i am wondering is there is any way like
if input=="hello":
 fun()
i hope you get my point.. Help me out please
Thanks in advance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/f952cf4b/attachment.html>

From christopher.henk at allisontransmission.com  Mon Sep 13 23:14:29 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Mon, 13 Sep 2010 17:14:29 -0400
Subject: [Tutor] input problem
In-Reply-To: <AANLkTi=vKtZ5NLJqQi68Cx+iAaiiuh5_cp6xFAGVmHBk@mail.gmail.com>
Message-ID: <OFD2209778.55D544DF-ON8525779D.0073EA94-8525779D.0074E69A@mail.ati.int>

ANKUR AGGARWAL wrote on 09/13/2010 04:45:41 PM:

> Suppose i am taking input or various variables like
> a=raw_input("...............") //hello
> b=raw_input("................")//hi
> c=raw_input("...............")//hello
> d=raw_input("..........")//hello
> but i want to run a common function when input is hello
> 
> so instead of
> if a=="hello":
>  fun()
> then again for b and then again for c then d and so on i have to apply 
the code for the specific variable , 
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
>  fun()
> i hope you get my point.. Help me out please

You put your inputs into a list and see if "hello" is in the list.
 
    inputlist=[a,b,c,d]
    if "hello" in inputlist:
        fun()

or if you want to run fun() once for every "hello" you can then loop over 
the list.

    inputlist=[a,b,c,d]
    for inputitem in inputlist: 
        if "hello" == inputitem:
            fun()

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/f3b0ffa3/attachment.html>

From prologic at shortcircuit.net.au  Mon Sep 13 23:16:47 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Tue, 14 Sep 2010 07:16:47 +1000
Subject: [Tutor] input problem
In-Reply-To: <AANLkTi=vKtZ5NLJqQi68Cx+iAaiiuh5_cp6xFAGVmHBk@mail.gmail.com>
References: <AANLkTi=vKtZ5NLJqQi68Cx+iAaiiuh5_cp6xFAGVmHBk@mail.gmail.com>
Message-ID: <AANLkTimjzewg+V+3gPZFWC88HzJ++_s7NDo3ZQ3zT9KU@mail.gmail.com>

On Tue, Sep 14, 2010 at 6:45 AM, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
> Suppose i am taking input or various variables like
> a=raw_input("...............") //hello
> b=raw_input("................")//hi
> c=raw_input("...............")//hello
> d=raw_input("..........")//hello
> but i want to run a common function when input is hello
> so instead of
> if a=="hello":
> ?fun()
> then again for b and then again for c then d and so on i have to apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
> ?fun()
> i hope you get my point.. Help me out please
> Thanks in advance

How about this design pattern:

def hello():
   print "Hello World!"

prompt = "..."
s = raw_input(prompt)
while s:
   if s == "hello":
      hello()
   elif s == "quit":
      break
   s = raw_input(prompt)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From bgailer at gmail.com  Tue Sep 14 00:05:33 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 13 Sep 2010 18:05:33 -0400
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<i6ln0f$36j$1@dough.gmane.org>,
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>,
	<4C8E68AE.2050301@gmail.com>,
	<SNT118-W5892FA3C52ECA6AAF3BE46AE770@phx.gbl>
	<SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>
Message-ID: <4C8EA02D.2070004@gmail.com>

  On 9/13/2010 2:21 PM, Roelof Wobben wrote:
>
>
>
> ----------------------------------------
>> From: rwobben at hotmail.com
>> To: bgailer at gmail.com
>> Subject: RE: [Tutor] wierd replace problem
>> Date: Mon, 13 Sep 2010 18:19:43 +0000
>>> I suggest you give a clear, complete and correct problem statement.
>>> Right now we are shooting in the dark at a moving target.
>>>
>>> Something like.
>>>
>>> Given the file alice_in_wonderland.txt, copied from url so-and-so
>>>
>>> Remove these characters ...
>>>
>>> Split into words (not letters?) where word is defined as
>>>
>>> Count the frequency of each word. =
>> Hello,
>>
>> The problem as stated in the book is :
>>
> 3.Write a program called alice_words.py that creates a text file named alice_words.txt containing an alphabetical listing of all the words found in alice_in_wonderland.txt together with the number of times each word occurs. The first 10 lines of your output file should look something like this:
> Word Count
> =======================
> a 631
> a-piece 1
> abide 1
> able 1
> about 94
> above 3
> absence 1
> absurd 2
> How many times does the word, alice, occur in the book?

We still do not have a definition of "word". Only some examples.

> The text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
>
> So I open the file.
> Read the first rule.
>
> This is no problem for me.
>
> Then I want to remove some characters like ' , " when the word in the text begins with these characters.
> And there is the problem. The ' and " can't be removed with replace.

Not true. replace() will replace any character. You wrote in your other post

>  letter2 = letter.strip('`")

>  SyntaxError: EOL while scanning string literal

>  Change it to (''`"") do not help either.

Do you understand the error? strip expects a string.
'`" and ''`"" are NOT strings. Please review Python syntax for string literals.
Here again we bump into a fundamental problem - your not understanding some of the basics of Python.

> So in the output you will see something like this "dark instead of dark
>
> word is the words of the sentence which is read in from the text-file.
>
> Am i now clear what the problem is Im facing.
Somewhat clearer. We need a definition of "word". Examples help but are 
not definitions.

Example - word is a string of characters including a-z and -. The first 
and last characters must be in a-z. Your definition may be different.

BTW see http://dictionary.reference.com/browse/%27tis where 'tis IS a word.

Your original program (what DID become of the backslash???) is WAY off 
the mark. You must process one character at a time, decide whether it is 
the beginning of a word, the end of a word, within a word, or outside 
any word.

Take the beginning of the alice file, and BY HAND decide which category 
the first character is in. Then the 2nd. etc. That gives you the 
algorithm, Then translate that to Python.

Keep fishing. One day the struggle will be over.

HTH

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From steve at pearwood.info  Tue Sep 14 00:41:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 08:41:28 +1000
Subject: [Tutor] wierd replace problem
In-Reply-To: <AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8E68AE.2050301@gmail.com>
	<AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>
Message-ID: <201009140841.29357.steve@pearwood.info>

On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:

> How about using str.split() to put words in a list, then run strip()
> over each word with the required characters to be removed ('`")


Doesn't work. strip() only removes characters at the beginning and end 
of the word, not in the middle:


>>> "'I can't do this'".strip("'")
"I can't do this"

If the aim is to remove all quotation marks, replace() is the right way 
to go about it. It's not that hard either.

text = text.replace("'", "").replace('"', "").replace("`", "")

will remove all "standard" quotation marks, although if the source text 
contains non-English or unusual unicode quotes, you will need to do 
more work.

Or if you prefer something more easily extendable to other characters:

for c in "\"'`":
    text = text.replace(c, "")



-- 
Steven D'Aprano

From joel.goldstick at gmail.com  Tue Sep 14 01:08:24 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 13 Sep 2010 19:08:24 -0400
Subject: [Tutor] wierd replace problem
In-Reply-To: <201009140841.29357.steve@pearwood.info>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8E68AE.2050301@gmail.com>
	<AANLkTin9VrmYNZ_GdKLpDJZwUAfAc8KWoZJX6c_DZo75@mail.gmail.com>
	<201009140841.29357.steve@pearwood.info>
Message-ID: <AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>

On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
>
> > How about using str.split() to put words in a list, then run strip()
> > over each word with the required characters to be removed ('`")
>
>
> Doesn't work. strip() only removes characters at the beginning and end
> of the word, not in the middle:
>


Exactly, you first split the words into a list of words, then strip each
word



> >>> "'I can't do this'".strip("'")
> "I can't do this"
>
> If the aim is to remove all quotation marks, replace() is the right way
> to go about it. It's not that hard either.
>
> text = text.replace("'", "").replace('"', "").replace("`", "")
>
> will remove all "standard" quotation marks, although if the source text
> contains non-English or unusual unicode quotes, you will need to do
> more work.
>
> Or if you prefer something more easily extendable to other characters:
>
> for c in "\"'`":
>    text = text.replace(c, "")
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/bf2e436e/attachment-0001.html>

From steve at pearwood.info  Tue Sep 14 01:17:16 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 09:17:16 +1000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <4C8EA02D.2070004@gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>
	<4C8EA02D.2070004@gmail.com>
Message-ID: <201009140917.17048.steve@pearwood.info>

On Tue, 14 Sep 2010 08:05:33 am bob gailer wrote:

> > 3.Write a program called alice_words.py that creates a text file
> > named alice_words.txt containing an alphabetical listing of all the
> > words found in alice_in_wonderland.txt together with the number of
> > times each word occurs. The first 10 lines of your output file
> > should look something like this: Word Count
> > =======================
> > a 631
> > a-piece 1
> > abide 1
> > able 1
> > about 94
> > above 3
> > absence 1
> > absurd 2
> > How many times does the word, alice, occur in the book?
>
> We still do not have a definition of "word". Only some examples.

Nor do we have a definition of "text", "file", "alphabetical", "first", 
"10", "lines", "definition", or "overly pedantic".

A reasonable person would use the common meaning of all of these words, 
unless otherwise told differently. In this case, the only ambiguity is 
whether hyphenated words like "a-piece" should count as two words or 
one, but fortunately the example above clearly shows that it should 
count as a single word.

This is an exercise, not a RFC. Be reasonable.


-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 01:39:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 09:39:29 +1000
Subject: [Tutor] wierd replace problem
In-Reply-To: <AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<201009140841.29357.steve@pearwood.info>
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>
Message-ID: <201009140939.29985.steve@pearwood.info>

On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano 
<steve at pearwood.info>wrote:
> > On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
> > > How about using str.split() to put words in a list, then run
> > > strip() over each word with the required characters to be removed
> > > ('`")
> >
> > Doesn't work. strip() only removes characters at the beginning and
> > end of the word, not in the middle:
>
> Exactly, you first split the words into a list of words, then strip
> each word

Of course, if you don't want to remove ALL punctuation marks, but only 
those at the beginning and end of words, then strip() is a reasonable 
approach. But if the aim is to strip out all punctuation, no matter 
where, then it can't work.

Since the aim is to count words, a better approach might be a hybrid -- 
remove all punctuation marks like commas, fullstops, etc. no matter 
where they appear, keep internal apostrophes so that words like "can't" 
are different from "cant", but remove external ones. Although that 
loses information in the case of (e.g.) dialect speech:

    "'e said 'e were going to kill the lady, Mister Holmes!" 
    cried the lad excitedly.

You probably want to count the word as 'e rather than just e.

And hyphenation is tricky to. A lone hyphen - like these - should be 
deleted. But double-dashes--like these--are word separators, so need to 
be replaced by a space. Otherwise, single hyphens should be kept. If a 
word begins or ends with a hyphen, it should be be joined up with the 
previous or next word. But then it gets more complicated, because you 
don't know whether to keep the hyphen after joining or not.

E.g. if the line ends with: 

blah blah blah blah some-
thing blah blah blah.

should the joined up word become the compound word "some-thing" or the 
regular word "something"? In general, there's no way to be sure, 
although you can make a good guess by looking it up in a dictionary and 
assuming that regular words should be preferred to compound words. But 
that will fail if the word has changed over time, such as "cooperate", 
which until very recently used to be written "co-operate", and before 
that as "co?perate".



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 01:54:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 09:54:30 +1000
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
	<3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
Message-ID: <201009140954.30518.steve@pearwood.info>

On Tue, 14 Sep 2010 05:07:03 am Evert Rol wrote:
> Note 2: the directory can exist, but not have write access to your
> process. So between the try-except for creating a directory and the
> try-except for creating a file, you may put in a try-except for
> chmod.

If some application tried changing permissions I had set on a directory 
or file without my direct say-so, I would dump that application 
immediately.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 01:54:50 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 09:54:50 +1000
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
Message-ID: <201009140954.50499.steve@pearwood.info>

On Tue, 14 Sep 2010 04:31:00 am Brian Jones wrote:
> I've been coding Python long enough that 'asking forgiveness instead
> of permission' is my first instinct, but the resulting code is
> sometimes clumsy, and I wonder if someone can suggest something I'm
> missing, or at least validate what's going on here in some way.
>
> What I'm trying to do is write a file to a directory. However, the
> directory may not exist the first time I try to write a file there,
> so I'm going to first try to write the file, and if I get an
> exception, create the directory (er, *try* to), and *then* write the
> file there. Here's my first shot at the code:

Obviously this needs to go into an independent function or method for 
ease of testing, and so that you don't have to repeat yourself each 
time you write to a file.


>         try:
>             self.save_file(picfile_fullpath, picdata)
>         except IOError as err:

Since you don't use err, there's no need for it. But since you have it, 
you might as well use it, and inspect the error code. E.g. if the error 
is permission denied, then you can bail immediately because nothing 
else will succeed either. (Well, technically it could succeed if the 
permissions change between the first failure and the subsequent attempt 
to create the directories, but you probably don't care about that.)


>             # directory doesn't exist. Try to create it.
>             try:
>                 os.makedirs(picfile_fullpath)
>             except OSError as oserr:
>                 logging.error("Can't create file path: %s (%s)" %
> (picfile_fullpath, oserr))
>             else:
>                 # Created dir, now write file.
>                 try:
>                     self.save_file(picfile_fullpath, picdata)
>                 except IOError as err:
>                     logging.error("Bailing. Couldn't save file %s
> (%s)" % (picfile_fullpath, err))
>                     return False
>
> Doesn't this seem less readable than the 'ask permission' equivalent?

Yes, but that's because the "ask permission" equivalent is fatally 
flawed -- permission can be revoked at any time, including a 
microsecond after you've been told "Yes" but before you actually get to 
save the file.

You've got more or less the right approach here, although you can 
streamline it so you're only trying to write the file once rather than 
twice. Put this in a utility function or method, where all the 
complication is hidden, just as os.makedirs hides a lot of complexity.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 02:03:35 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 10:03:35 +1000
Subject: [Tutor] What's the best way to ask forgiveness here?
In-Reply-To: <AANLkTimcaJJ69DkjFmH_pbT0PxzxwF9n9COK4-tdv-C-@mail.gmail.com>
References: <AANLkTikrXaCerqPfFVC2aqV_WDAnSmfAFY5j+vAd_PFD@mail.gmail.com>
	<3F62F0B3-169C-4AF6-940F-9ECF5370F65D@gmail.com>
	<AANLkTimcaJJ69DkjFmH_pbT0PxzxwF9n9COK4-tdv-C-@mail.gmail.com>
Message-ID: <201009141003.35530.steve@pearwood.info>

On Tue, 14 Sep 2010 05:12:12 am Brian Jones wrote:
> Thanks for the replies so far. One thing that's probably relevant:
> once a directory is created, I can expect to write a couple of
> hundred files to it, so doing a 'try os.makedirs' right off the bat
> strikes me as coding for the *least* common case instead of the
> *most* common (which is that the directory exists and the file write
> succeeds). If this were a one-off file write.... well then things get
> easier, but I'd like to avoid attempting a makedirs 100 times when 99
> of those times I know it'll give me an error.

Why? Do you know how much time it will save? The extra scaffolding code, 
setting up the try...except block, takes time too. Unless you've 
profiled the code, you have no idea how wasteful 100 calls to makedirs 
will be, compared to the alternatives of:

look to see if the directory exists 100 times

or 

setting up 100 extra try...except blocks.

In any case, the time it takes to call makedirs() unnecessarily will 
probably be so small compared to the time you actually spending writing 
data to disk that you won't notice -- who cares if you reduce the time 
to save 100 files from 1.302 seconds to 1.293 seconds? But don't 
believe me, because I'm only guessing. Write both versions and time 
them with *realistic* amounts of data. If you normally write 100 five 
gigabyte files over a network share, why are we even having this 
conversation??? *wink*

Write for the reader (that would be you, in six months time) first, and 
then only optimize when you have to.


-- 
Steven D'Aprano

From pedrooconnell at gmail.com  Tue Sep 14 02:11:05 2010
From: pedrooconnell at gmail.com (Pete O'Connell)
Date: Tue, 14 Sep 2010 09:41:05 +0930
Subject: [Tutor] How to numerically sort strings that start with numbers?
Message-ID: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>

theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete

From adam.jtm30 at gmail.com  Tue Sep 14 03:11:33 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 14 Sep 2010 02:11:33 +0100
Subject: [Tutor] How to numerically sort strings that start with numbers?
In-Reply-To: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
Message-ID: <4C8ECBC5.80807@gmail.com>

On 14/09/10 01:11, Pete O'Connell wrote:
> theList = ["21 trewuuioi","3zxc","134445"]
> print sorted(theList)
>
> Hi, the result of the sorted list above doesn't print in the order I
> want. Is there a straight forward way of getting python to print
> ['3zxc','21 trewuuioi','134445']
> rather than ['134445', '21 trewuuioi', '3zxc']?
>
> Any help would be greatly appreciated
> Pete
>    
print sorted(theList)[::-1]

as list indices go [start:end:step] what this means is the whole list 
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you 
can use theList.reverse() if you want to reverse in place ie.

 >>> l = ["21 trewuuioi","3zxc","134445"]
 >>> l.reverse()
 >>> print l
['134445', '3zxc', '21 trewuuioi']


HTH

From smokefloat at gmail.com  Tue Sep 14 03:25:02 2010
From: smokefloat at gmail.com (David Hutto)
Date: Mon, 13 Sep 2010 21:25:02 -0400
Subject: [Tutor] How to numerically sort strings that start with numbers?
In-Reply-To: <4C8ECBC5.80807@gmail.com>
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
	<4C8ECBC5.80807@gmail.com>
Message-ID: <AANLkTinGWKPp22B94jgUQdMr93Q9Md=yqCt-vJfO8Mk3@mail.gmail.com>

On Mon, Sep 13, 2010 at 9:11 PM, Adam Bark <adam.jtm30 at gmail.com> wrote:
> On 14/09/10 01:11, Pete O'Connell wrote:
>>
>> theList = ["21 trewuuioi","3zxc","134445"]
>> print sorted(theList)
>>
>> Hi, the result of the sorted list above doesn't print in the order I
>> want. Is there a straight forward way of getting python to print
>> ['3zxc','21 trewuuioi','134445']
>> rather than ['134445', '21 trewuuioi', '3zxc']?
>>
>> Any help would be greatly appreciated
>> Pete
>>
>
> print sorted(theList)[::-1]
>
> as list indices go [start:end:step] what this means is the whole list
> starting from the end and working backwards.
> You can also have a look at reversed() if you want an iterator or you can
> use theList.reverse() if you want to reverse in place ie.
>
>>>> l = ["21 trewuuioi","3zxc","134445"]
>>>> l.reverse()
>>>> print l
> ['134445', '3zxc', '21 trewuuioi']
>
>
> HTH
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Thanks from me too, because I kept getting None when trying
to directly print theList.reverse()

>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> theList.reverse()
>>> print theList
['134445', '3zxc', '21 trewuuioi']
>>> print theList.reverse()
None
>>> print type(theList.reverse())
<type 'NoneType'>
>>> print type(theList)
<type 'list'>
>>>

From adam.jtm30 at gmail.com  Tue Sep 14 03:35:03 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 14 Sep 2010 02:35:03 +0100
Subject: [Tutor] How to numerically sort strings that start with numbers?
In-Reply-To: <AANLkTinE=m4DuY72RDAkGEkr_OkBj1uBVV9jcV4PTiqZ@mail.gmail.com>
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>	<4C8ECBC5.80807@gmail.com>
	<AANLkTinE=m4DuY72RDAkGEkr_OkBj1uBVV9jcV4PTiqZ@mail.gmail.com>
Message-ID: <4C8ED147.8000102@gmail.com>

On 14/09/10 02:24, Pete O'Connell wrote:
> Hi I don't actaully need the list printed reversed, I need it printed
> from smallest number to largest
>
>    
Just sorting gives you the list from smallest to largest.
> For example:
> #############
>
> theList = ["21 trewuuioi","374zxc","13447"]
> print sorted(theList)
>    
>>>> ['13447', '21 trewuuioi', '374zxc']
>>>>          
> #the rabove result is not what I want
> ################
>
> If I reverse that I still don't get the items in numerical order. The
> result I want is:
>    
>>>> ['21 trewuuioi','374zxc','13447']
>>>>          
Before you said you wanted it like this:  ['3zxc','21 trewuuioi','134445']

The order above isn't in any obvious numerical order.
Anyway I think I see where you are coming from. In my previous example I 
forgot to assign the sorted list back to theList. Hopefully the 
following will make this clear.

 >>> theList = ["21 trewuuioi","3zxc","134445"]
 >>> sorted(theList)
['134445', '21 trewuuioi', '3zxc']
 >>> theList
['21 trewuuioi', '3zxc', '134445']
 >>> theList = sorted(theList)
 >>> theList
['134445', '21 trewuuioi', '3zxc']
 >>> theList[::-1]
['3zxc', '21 trewuuioi', '134445']
 >>> theList.reverse()
 >>> theList
['3zxc', '21 trewuuioi', '134445']

as you can see sorted makes a new list rather than modifying your original.
> On Tue, Sep 14, 2010 at 10:41 AM, Adam Bark<adam.jtm30 at gmail.com>  wrote:
>    
>> On 14/09/10 01:11, Pete O'Connell wrote:
>>      
>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> print sorted(theList)
>>>
>>> Hi, the result of the sorted list above doesn't print in the order I
>>> want. Is there a straight forward way of getting python to print
>>> ['3zxc','21 trewuuioi','134445']
>>> rather than ['134445', '21 trewuuioi', '3zxc']?
>>>
>>> Any help would be greatly appreciated
>>> Pete
>>>
>>>        
>> print sorted(theList)[::-1]
>>
>> as list indices go [start:end:step] what this means is the whole list
>> starting from the end and working backwards.
>> You can also have a look at reversed() if you want an iterator or you can
>> use theList.reverse() if you want to reverse in place ie.
>>
>>      
>>>>> l = ["21 trewuuioi","3zxc","134445"]
>>>>> l.reverse()
>>>>> print l
>>>>>            
>> ['134445', '3zxc', '21 trewuuioi']
>>
>>
>> HTH
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>      
>
>
>    


From aeneas24 at priest.com  Tue Sep 14 05:58:07 2010
From: aeneas24 at priest.com (aeneas24 at priest.com)
Date: Mon, 13 Sep 2010 23:58:07 -0400
Subject: [Tutor] If/elif/else when a list is empty
Message-ID: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>


Hi,

I'm parsing IMDB movie reviews (each movie is in its own text file). In my script, I'm trying to extract genre information. Movies have up to three categories of genres--but not all have a "genre" tag and that fact is making my script abort whenever it encounters a movie text file that doesn't have a "genre" tag. 

I thought the following should solve it, but it doesn't. The basic question is how I say "if genre information doesn't at all, just make rg1=rg2=rg3="NA"?

rgenre = re.split(r';', rf.info["genre"]) # When movies have genre information they store it as <genre>Drama;Western;Thriller</genre>

if len(rgenre)>0:
          if len(rgenre)>2:
              rg1=rgenre[0]
              rg2=rgenre[1]
              rg3=rgenre[2]
          elif len(rgenre)==2:
              rg1=rgenre[0]
              rg2=rgenre[1]
              rg3="NA"
          elif len(rgenre)==1:
              rg1=rgenre[0]
              rg2="NA"
              rg3="NA"
   else len(rgenre)<1: # I was hoping this would take care of the "there is no genre information" scenario but it doesn't
           rg1=rg2=rg3="NA"

This probably does a weird nesting thing, but even simpler version I have tried don't work. 

Thanks very much for any help!

Tyler
      



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/b4b1efc3/attachment.html>

From vince at vinces.ca  Tue Sep 14 06:08:43 2010
From: vince at vinces.ca (Vince Spicer)
Date: Mon, 13 Sep 2010 22:08:43 -0600
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
Message-ID: <AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>

On Mon, Sep 13, 2010 at 9:58 PM, <aeneas24 at priest.com> wrote:

>  Hi,
>
> I'm parsing IMDB movie reviews (each movie is in its own text file). In my
> script, I'm trying to extract genre information. Movies have up to three
> categories of genres--but not all have a "genre" tag and that fact is making
> my script abort whenever it encounters a movie text file that doesn't have a
> "genre" tag.
>
> I thought the following should solve it, but it doesn't. The basic question
> is how I say "if genre information doesn't at all, just make
> rg1=rg2=rg3="NA"?
>
> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre
> information they store it as <genre>Drama;Western;Thriller</genre>
>
> if len(rgenre)>0:
>           if len(rgenre)>2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3=rgenre[2]
>           elif len(rgenre)==2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3="NA"
>           elif len(rgenre)==1:
>               rg1=rgenre[0]
>               rg2="NA"
>               rg3="NA"
>    else len(rgenre)<1: # I was hoping this would take care of the "there is
> no genre information" scenario but it doesn't
>            rg1=rg2=rg3="NA"
>
> This probably does a weird nesting thing, but even simpler version I have
> tried don't work.
>
> Thanks very much for any help!
>
> Tyler
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Hey Tyler you can simplify this with a onliner.

rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))

Hope that helps, if you have any questions feel free to ask.

Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/3ca15bbb/attachment.html>

From prologic at shortcircuit.net.au  Tue Sep 14 06:09:59 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Tue, 14 Sep 2010 14:09:59 +1000
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
Message-ID: <AANLkTikKKsMdjXR9Q1LsXyLzk7Z-9n__nK-RSF6z8682@mail.gmail.com>

On Tue, Sep 14, 2010 at 1:58 PM,  <aeneas24 at priest.com> wrote:
> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre

First question. Why are you not using an XML parser (it looks like
your IMDB data files _are_ XML). e.g: elementree (in the standard
library).

> ???else len(rgenre)<1: # I was hoping this would take care of the "there is
> no genre information" scenario but it doesn't
> ?????????? rg1=rg2=rg3="NA"

the "else" statement does not expect (nor accept) an expression after
it, just write:

else:
   ...

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From aeneas24 at priest.com  Tue Sep 14 06:46:36 2010
From: aeneas24 at priest.com (aeneas24 at priest.com)
Date: Tue, 14 Sep 2010 00:46:36 -0400
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
	<AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
Message-ID: <8CD21DEF28CE7FF-9A8-4A7B@web-mmc-m01.sysops.aol.com>


Hi Vince,

Thanks very much for the one-line version--unfortunately, I still get errors. The overall script runs over every text file in a directory, but as soon as it hits a text file without a <genre> tag, it gives this error:

Traceback (most recent call last):
  File "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 168, in <module>
    main(".","output.csv")
  File "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 166, in main
    os.path.walk(top_level_dir, reviewDirectory, writer )
  File "C:\Python26\lib\ntpath.py", line 259, in walk
    func(arg, top, names)
  File "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 162, in reviewDirectory
    reviewFile( dirname+'/'+fileName, args )
  File "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py", line 74, in reviewFile
    rgenre = re.split(r';', rf.info["genre"])
KeyError: 'genre'

I'm about to give what may be too much information--I really thought there must be a way to say "don't choke if you don't find any rgenres because rf.info["genre"] was empty". But maybe I need to define the "None" condition earlier?

Basically a text file has this structure:
<info>
<title>High Noon</title>
<genre>Drama;Western</genre> # But this tag doesn't exist for all text files
# etc
</info>
<review>
<author>u493498</author>
<rating>9 out of 10</rating>
<summary>A great flick</summary>
<text>blah blah blah</text>
# etc
</review>
# next review--all about the movie featured in the info tags






-----Original Message-----
From: Vince Spicer <vince at vinces.ca>
To: aeneas24 at priest.com
Cc: tutor at python.org
Sent: Mon, Sep 13, 2010 9:08 pm
Subject: Re: [Tutor] If/elif/else when a list is empty





On Mon, Sep 13, 2010 at 9:58 PM, <aeneas24 at priest.com> wrote:

Hi,
 
I'm parsing IMDB movie reviews (each movie is in its own text file). In my script, I'm trying to extract genre information. Movies have up to three categories of genres--but not all have a "genre" tag and that fact is making my script abort whenever it encounters a movie text file that doesn't have a "genre" tag. 
 
I thought the following should solve it, but it doesn't. The basic question is how I say "if genre information doesn't at all, just make rg1=rg2=rg3="NA"?
 
rgenre = re.split(r';', rf.info["genre"]) # When movies have genre information they store it as <genre>Drama;Western;Thriller</genre>
 
if len(rgenre)>0:
          if len(rgenre)>2:
              rg1=rgenre[0]
              rg2=rgenre[1]
              rg3=rgenre[2]
          elif len(rgenre)==2:
              rg1=rgenre[0]
              rg2=rgenre[1]
              rg3="NA"
          elif len(rgenre)==1:
              rg1=rgenre[0]
              rg2="NA"
              rg3="NA"
   else len(rgenre)<1: # I was hoping this would take care of the "there is no genre information" scenario but it doesn't
           rg1=rg2=rg3="NA"
 
This probably does a weird nesting thing, but even simpler version I have tried don't work. 
 
Thanks very much for any help!
 
Tyler
      




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




Hey Tyler you can simplify this with a onliner.


rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))


Hope that helps, if you have any questions feel free to ask.


Vince

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/22227a90/attachment.html>

From vince at vinces.ca  Tue Sep 14 06:56:38 2010
From: vince at vinces.ca (Vince Spicer)
Date: Mon, 13 Sep 2010 22:56:38 -0600
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <8CD21DEF28CE7FF-9A8-4A7B@web-mmc-m01.sysops.aol.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
	<AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
	<8CD21DEF28CE7FF-9A8-4A7B@web-mmc-m01.sysops.aol.com>
Message-ID: <AANLkTinLmb+NDBSSPY3O1s73s1jBdquautRh2NOZiNRB@mail.gmail.com>

Tyler,

This is a simple error the KeyError is caused because the key isn't in the
dictionary
http://docs.python.org/library/exceptions.html#exceptions.KeyError and easy
fix you can either check for the key prior to using or use the get method

1) rgenre = re.split(r';', rf.info["genre"]) if "genre" in rf.info else []
the regex will never get executed here and an empty list will be returned if
genre not present

2) rgenre = re.split(r';', rf.info.get("genre", ''))
the get will not throw this error and return '' if ''genre' is not found in
the dictionary

Hope that helps,

Vince
<http://docs.python.org/library/exceptions.html#exceptions.KeyError>

On Mon, Sep 13, 2010 at 10:46 PM, <aeneas24 at priest.com> wrote:

> Hi Vince,
>
> Thanks very much for the one-line version--unfortunately, I still get
> errors. The overall script runs over every text file in a directory, but as
> soon as it hits a text file without a <genre> tag, it gives this error:
>
> Traceback (most recent call last):
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 168, in <module>
>     main(".","output.csv")
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 166, in main
>     os.path.walk(top_level_dir, reviewDirectory, writer )
>   File "C:\Python26\lib\ntpath.py", line 259, in walk
>     func(arg, top, names)
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 162, in reviewDirectory
>     reviewFile( dirname+'/'+fileName, args )
>   File
> "C:\Users\tylersc\Desktop\Tyler2\Tyler\words_per_review_IMDB_9-13-10.py",
> line 74, in reviewFile
>
>     rgenre = re.split(r';', rf.info["genre"])
> KeyError: 'genre'
>  I'm about to give what may be too much information--I really thought
> there must be a way to say "don't choke if you don't find any rgenres
> because rf.info["genre"] was empty". But maybe I need to define the "None"
> condition earlier?
>
> Basically a text file has this structure:
> <info>
> <title>High Noon</title>
> <genre>Drama;Western</genre> # But this tag doesn't exist for all text
> files
> # etc
> </info>
> <review>
> <author>u493498</author>
> <rating>9 out of 10</rating>
> <summary>A great flick</summary>
> <text>blah blah blah</text>
> # etc
> </review>
> # next review--all about the movie featured in the info tags
>
>
>
>
> -----Original Message-----
> From: Vince Spicer <vince at vinces.ca>
> To: aeneas24 at priest.com
> Cc: tutor at python.org
> Sent: Mon, Sep 13, 2010 9:08 pm
> Subject: Re: [Tutor] If/elif/else when a list is empty
>
>
>
> On Mon, Sep 13, 2010 at 9:58 PM, <aeneas24 at priest.com> wrote:
>
>> Hi,
>>
>> I'm parsing IMDB movie reviews (each movie is in its own text file). In my
>> script, I'm trying to extract genre information. Movies have up to three
>> categories of genres--but not all have a "genre" tag and that fact is making
>> my script abort whenever it encounters a movie text file that doesn't have a
>> "genre" tag.
>>
>> I thought the following should solve it, but it doesn't. The basic
>> question is how I say "if genre information doesn't at all, just make
>> rg1=rg2=rg3="NA"?
>>
>> rgenre = re.split(r';', rf.info["genre"]) # When movies have genre
>> information they store it as <genre>Drama;Western;Thriller</genre>
>>
>> if len(rgenre)>0:
>>           if len(rgenre)>2:
>>               rg1=rgenre[0]
>>               rg2=rgenre[1]
>>               rg3=rgenre[2]
>>           elif len(rgenre)==2:
>>               rg1=rgenre[0]
>>               rg2=rgenre[1]
>>               rg3="NA"
>>           elif len(rgenre)==1:
>>               rg1=rgenre[0]
>>               rg2="NA"
>>               rg3="NA"
>>    else len(rgenre)<1: # I was hoping this would take care of the "there
>> is no genre information" scenario but it doesn't
>>            rg1=rg2=rg3="NA"
>>
>> This probably does a weird nesting thing, but even simpler version I have
>> tried don't work.
>>
>> Thanks very much for any help!
>>
>> Tyler
>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> Hey Tyler you can simplify this with a onliner.
>
>  rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))
>
>  Hope that helps, if you have any questions feel free to ask.
>
>  Vince
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100913/2300e61c/attachment-0001.html>

From prologic at shortcircuit.net.au  Tue Sep 14 06:59:39 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Tue, 14 Sep 2010 14:59:39 +1000
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <8CD21DEF28CE7FF-9A8-4A7B@web-mmc-m01.sysops.aol.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
	<AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
	<8CD21DEF28CE7FF-9A8-4A7B@web-mmc-m01.sysops.aol.com>
Message-ID: <AANLkTimctGnLdpSxhmCN9=NhYJ4CE+p5C76CrfvjEO--@mail.gmail.com>

On Tue, Sep 14, 2010 at 2:46 PM,  <aeneas24 at priest.com> wrote:
> ?? rgenre = re.split(r';', rf.info["genre"])
> KeyError: 'genre'

Use something like this:

if "genre" in rf.info:
   rgenre = re.split(..., ...)
else:
   # ... no genre

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"

From rwobben at hotmail.com  Tue Sep 14 09:28:22 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 07:28:22 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<201009140841.29357.steve@pearwood.info>,
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>,
	<201009140939.29985.steve@pearwood.info>,
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
Message-ID: <SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>




Hello,

Strip ('"'') does not work.
Still this message : SyntaxError: EOL while scanning string literal

So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character.

 Roelof


> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Tue, 14 Sep 2010 09:39:29 +1000
>> Subject: Re: [Tutor] wierd replace problem
>>
>> On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
>>> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano
>> wrote:
>>>> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
>>>>> How about using str.split() to put words in a list, then run
>>>>> strip() over each word with the required characters to be removed
>>>>> ('`")
>>>>
>>>> Doesn't work. strip() only removes characters at the beginning and
>>>> end of the word, not in the middle:
>>>
>>> Exactly, you first split the words into a list of words, then strip
>>> each word
>>
>> Of course, if you don't want to remove ALL punctuation marks, but only
>> those at the beginning and end of words, then strip() is a reasonable
>> approach. But if the aim is to strip out all punctuation, no matter
>> where, then it can't work.
>>
>> Since the aim is to count words, a better approach might be a hybrid --
>> remove all punctuation marks like commas, fullstops, etc. no matter
>> where they appear, keep internal apostrophes so that words like "can't"
>> are different from "cant", but remove external ones. Although that
>> loses information in the case of (e.g.) dialect speech:
>>
>> "'e said 'e were going to kill the lady, Mister Holmes!"
>> cried the lad excitedly.
>>
>> You probably want to count the word as 'e rather than just e.
>>
>> And hyphenation is tricky to. A lone hyphen - like these - should be
>> deleted. But double-dashes--like these--are word separators, so need to
>> be replaced by a space. Otherwise, single hyphens should be kept. If a
>> word begins or ends with a hyphen, it should be be joined up with the
>> previous or next word. But then it gets more complicated, because you
>> don't know whether to keep the hyphen after joining or not.
>>
>> E.g. if the line ends with:
>>
>> blah blah blah blah some-
>> thing blah blah blah.
>>
>> should the joined up word become the compound word "some-thing" or the
>> regular word "something"? In general, there's no way to be sure,
>> although you can make a good guess by looking it up in a dictionary and
>> assuming that regular words should be preferred to compound words. But
>> that will fail if the word has changed over time, such as "cooperate",
>> which until very recently used to be written "co-operate", and before
>> that as "co?perate".
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor 		 	   		  

From timomlists at gmail.com  Tue Sep 14 09:32:38 2010
From: timomlists at gmail.com (Timo)
Date: Tue, 14 Sep 2010 09:32:38 +0200
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<201009140841.29357.steve@pearwood.info>,
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>,
	<201009140939.29985.steve@pearwood.info>,
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
Message-ID: <4C8F2516.4060906@gmail.com>

On 14-09-10 09:28, Roelof Wobben wrote:
>
>
> Hello,
>
> Strip ('"'') does not work.
> Still this message : SyntaxError: EOL while scanning string literal
>    
Review it again, see how many quotes you are using.

For example, this won't work either:
 >>> s = 'foo'bar'

You need to escape the quotes with a backslash, like:
 >>> s = 'foo\'bar'
 >>> print s
foo'bar


Cheers,
Timo

> So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character.
>
>   Roelof
>
>
>    
>> ----------------------------------------
>>      
>>> From: steve at pearwood.info
>>> To: tutor at python.org
>>> Date: Tue, 14 Sep 2010 09:39:29 +1000
>>> Subject: Re: [Tutor] wierd replace problem
>>>
>>> On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
>>>        
>>>> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano
>>>>          
>>> wrote:
>>>        
>>>>> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
>>>>>            
>>>>>> How about using str.split() to put words in a list, then run
>>>>>> strip() over each word with the required characters to be removed
>>>>>> ('`")
>>>>>>              
>>>>> Doesn't work. strip() only removes characters at the beginning and
>>>>> end of the word, not in the middle:
>>>>>            
>>>> Exactly, you first split the words into a list of words, then strip
>>>> each word
>>>>          
>>> Of course, if you don't want to remove ALL punctuation marks, but only
>>> those at the beginning and end of words, then strip() is a reasonable
>>> approach. But if the aim is to strip out all punctuation, no matter
>>> where, then it can't work.
>>>
>>> Since the aim is to count words, a better approach might be a hybrid --
>>> remove all punctuation marks like commas, fullstops, etc. no matter
>>> where they appear, keep internal apostrophes so that words like "can't"
>>> are different from "cant", but remove external ones. Although that
>>> loses information in the case of (e.g.) dialect speech:
>>>
>>> "'e said 'e were going to kill the lady, Mister Holmes!"
>>> cried the lad excitedly.
>>>
>>> You probably want to count the word as 'e rather than just e.
>>>
>>> And hyphenation is tricky to. A lone hyphen - like these - should be
>>> deleted. But double-dashes--like these--are word separators, so need to
>>> be replaced by a space. Otherwise, single hyphens should be kept. If a
>>> word begins or ends with a hyphen, it should be be joined up with the
>>> previous or next word. But then it gets more complicated, because you
>>> don't know whether to keep the hyphen after joining or not.
>>>
>>> E.g. if the line ends with:
>>>
>>> blah blah blah blah some-
>>> thing blah blah blah.
>>>
>>> should the joined up word become the compound word "some-thing" or the
>>> regular word "something"? In general, there's no way to be sure,
>>> although you can make a good guess by looking it up in a dictionary and
>>> assuming that regular words should be preferred to compound words. But
>>> that will fail if the word has changed over time, such as "cooperate",
>>> which until very recently used to be written "co-operate", and before
>>> that as "co?perate".
>>>
>>>
>>>
>>> --
>>> Steven D'Aprano
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor 		 	   		
>>>        
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


From rwobben at hotmail.com  Tue Sep 14 09:38:18 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 07:38:18 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <4C8F2516.4060906@gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<201009140841.29357.steve@pearwood.info>, ,
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>, ,
	<201009140939.29985.steve@pearwood.info>, ,
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>,
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>,
	<4C8F2516.4060906@gmail.com>
Message-ID: <SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>




----------------------------------------
> Date: Tue, 14 Sep 2010 09:32:38 +0200
> From: timomlists at gmail.com
> To: tutor at python.org
> Subject: Re: [Tutor] FW: wierd replace problem
>
> On 14-09-10 09:28, Roelof Wobben wrote:
>>
>>
>> Hello,
>>
>> Strip ('"'') does not work.
>> Still this message : SyntaxError: EOL while scanning string literal
>>
> Review it again, see how many quotes you are using.
>
> For example, this won't work either:
>>>> s = 'foo'bar'
>
> You need to escape the quotes with a backslash, like:
>>>> s = 'foo\'bar'
>>>> print s
> foo'bar
>
>
> Cheers,
> Timo

 
Hello Timo,
 
I understand what you mean but we're talking about a text-file which will be read in a string.
So I can't escape the quotes. As far as I know I can't control  how Python is reading a text-file with quotes.
 
Roelof
 
 
 
>
>> So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character.
>>
>> Roelof
>>
>>
>>
>>> ----------------------------------------
>>>
>>>> From: steve at pearwood.info
>>>> To: tutor at python.org
>>>> Date: Tue, 14 Sep 2010 09:39:29 +1000
>>>> Subject: Re: [Tutor] wierd replace problem
>>>>
>>>> On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
>>>>
>>>>> On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano
>>>>>
>>>> wrote:
>>>>
>>>>>> On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
>>>>>>
>>>>>>> How about using str.split() to put words in a list, then run
>>>>>>> strip() over each word with the required characters to be removed
>>>>>>> ('`")
>>>>>>>
>>>>>> Doesn't work. strip() only removes characters at the beginning and
>>>>>> end of the word, not in the middle:
>>>>>>
>>>>> Exactly, you first split the words into a list of words, then strip
>>>>> each word
>>>>>
>>>> Of course, if you don't want to remove ALL punctuation marks, but only
>>>> those at the beginning and end of words, then strip() is a reasonable
>>>> approach. But if the aim is to strip out all punctuation, no matter
>>>> where, then it can't work.
>>>>
>>>> Since the aim is to count words, a better approach might be a hybrid --
>>>> remove all punctuation marks like commas, fullstops, etc. no matter
>>>> where they appear, keep internal apostrophes so that words like "can't"
>>>> are different from "cant", but remove external ones. Although that
>>>> loses information in the case of (e.g.) dialect speech:
>>>>
>>>> "'e said 'e were going to kill the lady, Mister Holmes!"
>>>> cried the lad excitedly.
>>>>
>>>> You probably want to count the word as 'e rather than just e.
>>>>
>>>> And hyphenation is tricky to. A lone hyphen - like these - should be
>>>> deleted. But double-dashes--like these--are word separators, so need to
>>>> be replaced by a space. Otherwise, single hyphens should be kept. If a
>>>> word begins or ends with a hyphen, it should be be joined up with the
>>>> previous or next word. But then it gets more complicated, because you
>>>> don't know whether to keep the hyphen after joining or not.
>>>>
>>>> E.g. if the line ends with:
>>>>
>>>> blah blah blah blah some-
>>>> thing blah blah blah.
>>>>
>>>> should the joined up word become the compound word "some-thing" or the
>>>> regular word "something"? In general, there's no way to be sure,
>>>> although you can make a good guess by looking it up in a dictionary and
>>>> assuming that regular words should be preferred to compound words. But
>>>> that will fail if the word has changed over time, such as "cooperate",
>>>> which until very recently used to be written "co-operate", and before
>>>> that as "co?perate".
>>>>
>>>>
>>>>
>>>> --
>>>> Steven D'Aprano
>>>> _______________________________________________
>>>> Tutor maillist - Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor 		 	   		  

From __peter__ at web.de  Tue Sep 14 09:43:56 2010
From: __peter__ at web.de (Peter Otten)
Date: Tue, 14 Sep 2010 09:43:56 +0200
Subject: [Tutor] How to numerically sort strings that start with numbers?
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
Message-ID: <i6n919$ps8$1@dough.gmane.org>

Pete O'Connell wrote:

> theList = ["21 trewuuioi","3zxc","134445"]
> print sorted(theList)
> 
> Hi, the result of the sorted list above doesn't print in the order I
> want. Is there a straight forward way of getting python to print
> ['3zxc','21 trewuuioi','134445']
> rather than ['134445', '21 trewuuioi', '3zxc']?

You have to write a function that extracts the number and use it as the key 
argument for sorted() or list.sort():

>>> import re
>>> def extract_number(s):
...     m = re.compile(r"-?\d+").match(s)
...     if m is not None:
...             return int(m.group())
...
>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> sorted(theList, key=extract_number)
['3zxc', '21 trewuuioi', '134445']

Have a look as str.isdigit() if you want to write such a function without 
regular expressions.

Peter


From wprins at gmail.com  Tue Sep 14 11:42:49 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 14 Sep 2010 10:42:49 +0100
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<201009140841.29357.steve@pearwood.info>
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>
	<201009140939.29985.steve@pearwood.info>
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
Message-ID: <AANLkTikCg9=CFLorOfNPmJCJ-xX+aTx=tPiTG_rf6LdY@mail.gmail.com>

On 14 September 2010 08:38, Roelof Wobben <rwobben at hotmail.com> wrote:

>
> I understand what you mean but we're talking about a text-file which will
> be read in a string.
> So I can't escape the quotes. As far as I know I can't control  how Python
> is reading a text-file with quotes.
>
>
Putting a value into a string via Python source code is not the same as
putting a value into a string by reading a file.  When you read a file it's
implicit that whatever's in the file (including quotes) will end up in the
string.  There's no ambiguity so no need to worry about escaping.

In Python source code however, quotes have meaning implied by context, so
you have to encode/write strings differently *in source* in order to
disambiguate your intention.  In other words, when Python encounters a first
quote in source code, it interprets this as the start of a string.  When it
encounters the next quote of the same type, it interprets this as the end of
the string, and so on.  If you therefore want to put a quote of the same
type you're using to delineate a string inside of that same string, you need
to "escape" the quote, e.g. tell Python to not interpret the quote as it
normally would and to rather take it literally and as part of the current
string value being read.  This you do by putting a backslash (e.g. \ )
before it.  Of course, the same problem happens when you want to put
backslash itself in a string, so the backslash itself also need to be
escaped in order to be put inside a string in Python.

HTH

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/2231ccc4/attachment.html>

From prologic at shortcircuit.net.au  Tue Sep 14 12:09:42 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Tue, 14 Sep 2010 20:09:42 +1000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<201009140841.29357.steve@pearwood.info>
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>
	<201009140939.29985.steve@pearwood.info>
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
Message-ID: <AANLkTikjwxuMCzQAz2Hiv_ugpxri+L3-Q9G_c0R0xfH1@mail.gmail.com>

On Tue, Sep 14, 2010 at 5:28 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
> Strip ('"'') does not work.
> Still this message : SyntaxError: EOL while scanning string literal
>
> So I think I go for the suggestion of Bob en develop a programm which deletes all the ' and " by scanning it character by character.

I seriously don't understand why you're having so much trouble with this
and why this thread has gotten as long as it has :/

Look here:

$ python
Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
[GCC 4.4.4 (CRUX)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "foo\"bar'"
>>> s
'foo"bar\''
>>> s.replace("\"", "").replace("'", "")
'foobar'
>>>

Surely you can use the same approach ?

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From wprins at gmail.com  Tue Sep 14 12:41:28 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 14 Sep 2010 11:41:28 +0100
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTikjwxuMCzQAz2Hiv_ugpxri+L3-Q9G_c0R0xfH1@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<201009140841.29357.steve@pearwood.info>
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>
	<201009140939.29985.steve@pearwood.info>
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>
	<AANLkTikjwxuMCzQAz2Hiv_ugpxri+L3-Q9G_c0R0xfH1@mail.gmail.com>
Message-ID: <AANLkTinq4JjxpWM436y9D1v25a_VWcqznqNP3VV2hTdE@mail.gmail.com>

On 14 September 2010 11:09, James Mills <prologic at shortcircuit.net.au>wrote:

> $ python
> Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
> [GCC 4.4.4 (CRUX)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> s = "foo\"bar'"
> >>> s
> 'foo"bar\''
>

I'd like to point something out here.  Typing "s" as James showed here at
the prompt outputs a version of the string that Python will understand if
fed again, consequently it's encoded to do the same escaping of characters
as you would have to do if you put that expression into your python source
yourself.  If however you entered:

print s

... then Python would've print the value of s as it really is, withou any
escape characters or anything else, e.g.:

>>> print s
foo"bar'

So, even though you see a \' in the output posted by James above, the \ that
was output by Python isn't actually part of the string (e.g. it's not really
there as such), it was only output that way by Python to disambiguate the
value of the string.

So, at the risk of belaboring this point to death, if you do:

s = '\'\'\''

then the contents of the string s in memory is '''

The string does not contain the slashes.  The slashes are only there to help
you make Python understand that the quotes must not be interpreted as the
end of the string, but rather as part of the string.  You could get the
exact same result by doing:

s = "'''"

Here there's no ambiguity and consequently no need for slashes since the
string is delineated by double quotes and not single quotes.

Hope that helps.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/ce922f98/attachment.html>

From fal at libero.it  Tue Sep 14 12:56:06 2010
From: fal at libero.it (Francesco Loffredo)
Date: Tue, 14 Sep 2010 12:56:06 +0200
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<i6ln0f$36j$1@dough.gmane.org>,
	<SNT118-W26B202F5B1B90B0A678174AE770@phx.gbl>,
	<4C8E68AE.2050301@gmail.com>,
	<SNT118-W5892FA3C52ECA6AAF3BE46AE770@phx.gbl>
	<SNT118-W34B71A63A25FCD069DB01AAE770@phx.gbl>
Message-ID: <4C8F54C6.3020108@libero.it>

On 13/09/2010 20.21, Roelof Wobben wrote:
>...
>> The problem as stated in the book is :
>
> 3.Write a program called alice_words.py that creates a text file named alice_words.txt containing an alphabetical listing of all the words found in alice_in_wonderland.txt together with the number of times each word occurs. The first 10 lines of your output file should look something like this:
> Word Count
> =======================
> a 631
> a-piece 1
> abide 1
> able 1
> about 94
> above 3
> absence 1
> absurd 2How many times does the word, alice, occur in the book?
>
> The text can be found here : http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
>
> So I open the file.
> Read the first rule.
>
> This is no problem for me.
>
> Then I want to remove some characters like ' , " when the word in the text begins with these characters.
> And there is the problem. The ' and " can't be removed with replace.
Not true. Your problem with replace() and strip() lies in the way you 
gave them the characters to remove, not in the file nor in the functions 
themselves. For example, you said:
> Strip ('"'') does not work.
> Still this message : SyntaxError: EOL while scanning string literal
Let's take a look into your argument:
(  parens to start the argument
'  first quote begins a string literal;
"  first character to remove, you want to delete all double quotes. OK.
'  ... what is this? Is it the end of the string, or is it another 
character to remove?
' This solves the doubt: '' means that the first string is over, and 
another has started. OK. (maybe not what you expected...)
)  OUCH! The argument has finished, but the string has not! So, End Of 
Line has been reached while your argument string was still open. Error.

The correct syntax (and you know where to look to read it!) should be:
MyText.strip('"\'')
The backslash tells Python that you want to include the following single 
quote in your string without terminating it, then the next single quote 
gives a proper end to the string itself.

Earlier, you said:
> I have tried that but then I see this message :
>
>  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 8
>     letter2 = letter.strip('`")
>                               ^
> SyntaxError: EOL while scanning string literal
>
> Change it to (''`"") do not help either.
Sure: as some pointed out before, those arguments are NOT proper string 
literals, as the first one doesn't start and end with the SAME quoting 
character, while the second is made from two empty strings with a 
floating backquote ` between them.
If you want to strip (or replace) the three quoting characters
' " and ` , you should enclose them in a properly formatted string 
literal, that is one that starts and ends with the same quoting 
character and that, if must contain the same character, has it quoted by 
backslash:
.strip("'\"`")

> Am i now clear what the problem is Im facing.
>
> Roelof

I hope so. After having cut away all unwanted characters, you still have 
to face the main request from your tutorial, and THE question:(Sorry, 
Hamlet!) How many times does the word "alice" occur in the book?

I would guess... none!

Keep up your "fishing"
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 -  Data di rilascio: 09/13/10 08:35:00

From rwobben at hotmail.com  Tue Sep 14 12:56:57 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 10:56:57 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTinq4JjxpWM436y9D1v25a_VWcqznqNP3VV2hTdE@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<201009140841.29357.steve@pearwood.info>,
	<AANLkTikeeftwggBMLanX4NZXAxbxxnvn=850Xt0mB64=@mail.gmail.com>,
	<201009140939.29985.steve@pearwood.info>,
	<SNT118-W17EAD8073E253626EECBC3AE780@phx.gbl>,
	<SNT118-W42B579DC2490F4FF286C75AE780@phx.gbl>,
	<AANLkTikjwxuMCzQAz2Hiv_ugpxri+L3-Q9G_c0R0xfH1@mail.gmail.com>,
	<AANLkTinq4JjxpWM436y9D1v25a_VWcqznqNP3VV2hTdE@mail.gmail.com>
Message-ID: <SNT118-W353181F6C33587163F9793AE780@phx.gbl>


Oke, 
 
Can this also be the same problem.
 
In the text is this :
 
'tis is represent as  "'this
 
And this
 
part is represent as part.
 
 
Roelof


________________________________
> Date: Tue, 14 Sep 2010 11:41:28 +0100
> From: wprins at gmail.com
> To: tutor at python.org
> Subject: Re: [Tutor] FW: wierd replace problem
>
>
>
> On 14 September 2010 11:09, James Mills
>>
> wrote:
> $ python
> Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
> [GCC 4.4.4 (CRUX)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> s = "foo\"bar'"
>>>> s
> 'foo"bar\''
>
> I'd like to point something out here. Typing "s" as James showed here
> at the prompt outputs a version of the string that Python will
> understand if fed again, consequently it's encoded to do the same
> escaping of characters as you would have to do if you put that
> expression into your python source yourself. If however you entered:
>
> print s
>
> ... then Python would've print the value of s as it really is, withou
> any escape characters or anything else, e.g.:
>
>>>> print s
> foo"bar'
>
> So, even though you see a \' in the output posted by James above, the \
> that was output by Python isn't actually part of the string (e.g. it's
> not really there as such), it was only output that way by Python to
> disambiguate the value of the string.
>
> So, at the risk of belaboring this point to death, if you do:
>
> s = '\'\'\''
>
> then the contents of the string s in memory is '''
>
> The string does not contain the slashes. The slashes are only there to
> help you make Python understand that the quotes must not be interpreted
> as the end of the string, but rather as part of the string. You could
> get the exact same result by doing:
>
> s = "'''"
>
> Here there's no ambiguity and consequently no need for slashes since
> the string is delineated by double quotes and not single quotes.
>
> Hope that helps.
>
> Walter
>
> _______________________________________________ Tutor maillist -
> Tutor at python.org To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor 		 	   		  

From steve at pearwood.info  Tue Sep 14 13:30:01 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 21:30:01 +1000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
Message-ID: <201009142130.02459.steve@pearwood.info>

On Tue, 14 Sep 2010 05:38:18 pm Roelof Wobben wrote:

> >> Strip ('"'') does not work.
> >> Still this message : SyntaxError: EOL while scanning string
> >> literal
[...]
> I understand what you mean but we're talking about a text-file which
> will be read in a string. So I can't escape the quotes. As far as I
> know I can't control  how Python is reading a text-file with quotes.

The text file has nothing to do with this. The text file is fine. The 
error is in the strings that YOU type, not the text file.

Strings must have MATCHING quotation marks:

This is okay: "abcd"
So is this: 'abcd'

But this is not: "abcd'

You need to *look carefully* at strings you type and make sure that the 
start and end quotes match. Likewise you can't insert the SAME 
quotation mark in a string unless you escape it first:

This is okay: "'Hello,' he said."
So is this: '"Goodbye," she replied.'

But this is not: 'He said "I can't see you."'

But this is okay: 'He said "I can\'t see you."'




-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 13:32:23 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 21:32:23 +1000
Subject: [Tutor] How to numerically sort strings that start with numbers?
In-Reply-To: <4C8ECBC5.80807@gmail.com>
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
	<4C8ECBC5.80807@gmail.com>
Message-ID: <201009142132.23399.steve@pearwood.info>

On Tue, 14 Sep 2010 11:11:33 am Adam Bark wrote:
> On 14/09/10 01:11, Pete O'Connell wrote:
> > theList = ["21 trewuuioi","3zxc","134445"]
> > print sorted(theList)
> >
> > Hi, the result of the sorted list above doesn't print in the order
> > I want. Is there a straight forward way of getting python to print
> > ['3zxc','21 trewuuioi','134445']
> > rather than ['134445', '21 trewuuioi', '3zxc']?
> >
> > Any help would be greatly appreciated
> > Pete
>
> print sorted(theList)[::-1]

That's a very inefficient way of doing it. First it makes a copy of the 
list, then it sorts it, then it makes *another* copy in reverse.

A better way is:

sorted(theList, reverse=True)



-- 
Steven D'Aprano

From michael at trollope.org  Tue Sep 14 13:42:15 2010
From: michael at trollope.org (Michael Powe)
Date: Tue, 14 Sep 2010 07:42:15 -0400
Subject: [Tutor] A Plea for Sensible Quoting
Message-ID: <20100914114215.GK2670@cecilia>

Hello,

I read this list in a linux console using mutt. I dunno, maybe I'm the
only idiot left still using a console mail client.  I write my emails
and email replies in emacs, too, which may make me even weirder.

Few elements make a mail harder to read than 130 lines of nested
quoting, into which has been inserted 3 or 5 lines of comment.  Mutt
does a good job of identifying the quote nesting and highlighting the
quoted material; and I can use the `T' command to remove the quoting.
But sometimes, "context" in the sense of what was being replied to is
useful.  When a thread reponse is quoting 3 other respondents plus the
OP, "context" turns into "what everybody is saying," which is more
like standing in a crowded train terminal, where everybody is
shouting, than having a quiet, private conversation among 4 people.
Then, I have to page down four screens to find the 5 lines of new
comment, and try to figure out what portion of that three-level-nested
dialog that preceeds it was the trigger for the response.

Just a plea to remember to take the time to `C-k' or `dd' or whatever
is required to get that extraneous material out of the mail.  A little
formatting goes a long way.

Thanks.

mp

<dons flameproof asbestos suit/>

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
Fun experiments:
  Get a can of shaving cream, throw it in a freezer for about a week.
  Then take it out, peel the metal off and put it where you want...
  bedroom, car, etc.  As it thaws, it expands an unbelievable amount.

From steve at pearwood.info  Tue Sep 14 13:45:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 21:45:29 +1000
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
	<AANLkTin+XLfp=p78hgqwzqW+G6ejvRhE0Qiti8LaGMXd@mail.gmail.com>
Message-ID: <201009142145.30448.steve@pearwood.info>

On Tue, 14 Sep 2010 02:08:43 pm Vince Spicer wrote:

> Hey Tyler you can simplify this with a onliner.
>
> rg1, rg2, rg3 = rgenre + ["NA"]*(3-len(rgenre[:3]))

There's no real need to calculate the exact length that you want:

rg1, rg2, rg3 = (rgenre + ["NA"]*3)[:3]

For small numbers of items -- and three is pretty small -- that will be 
plenty efficient enough. If you had thousands of items, perhaps not, 
but for three, it's not worth the effort to try to be more clever.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 13:54:59 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 21:54:59 +1000
Subject: [Tutor] A Plea for Sensible Quoting
In-Reply-To: <20100914114215.GK2670@cecilia>
References: <20100914114215.GK2670@cecilia>
Message-ID: <201009142155.00590.steve@pearwood.info>

On Tue, 14 Sep 2010 09:42:15 pm Michael Powe wrote:

> Just a plea to remember to take the time to `C-k' or `dd' or whatever
> is required to get that extraneous material out of the mail.  A
> little formatting goes a long way.

Seconded, thirded, fourthed and fifthed.

For those using a GUI email reader, select the unnecessary text with 
your mouse or keyboard, and press the backspace or delete key. See, not 
hard, was it?

I find myself deleting more and more emails unread. After paging down 
through two or three pages of quoting, without seeing a single new 
word, I just give up and press delete.

There is absolutely no reason to include the entire history of the 
discussion every single time you post. Take a little bit of care in 
your responses please -- you're learning to be a programmer, you're 
supposed to be smarter and more capable than the average Myspacer or 
Facebooker.


Thank you.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 14 14:29:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 22:29:47 +1000
Subject: [Tutor] wierd replace problem
In-Reply-To: <i6ln0f$36j$1@dough.gmane.org>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<i6ln0f$36j$1@dough.gmane.org>
Message-ID: <201009142229.48660.steve@pearwood.info>

On Tue, 14 Sep 2010 03:28:46 am Alan Gauld wrote:
> "Roelof Wobben" <rwobben at hotmail.com> wrote
>
> > Now I want to get rid of the \\ so I do this : test2 = test.replace
> > ('\\', '')
> > And I get at the python prompt this answer : 'het is een wonder
> > TIS' So that's right.
>
> OK,. Thats replacing a double slash in the data

Er, surely not... I think you've confused backslashes and forward 
slashes. Or something. '\\' is a single backslash, not a double, 
because the first backslash is the escape character.

A double backslash can be written '\\\\'.



-- 
Steven D'Aprano

From joel.goldstick at gmail.com  Tue Sep 14 14:41:26 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 14 Sep 2010 08:41:26 -0400
Subject: [Tutor] How to numerically sort strings that start with numbers?
In-Reply-To: <201009142132.23399.steve@pearwood.info>
References: <AANLkTimLg4o=jLmdatFjN_f7c-Ss-MTK_qyCd1d2jOfW@mail.gmail.com>
	<4C8ECBC5.80807@gmail.com> <201009142132.23399.steve@pearwood.info>
Message-ID: <AANLkTi=Jq65WDMiYNOHEg5ii4Y4EM89yuRrVKeS3KZa=@mail.gmail.com>

> > ['3zxc','21 trewuuioi','134445']
> > > rather than ['134445', '21 trewuuioi', '3zxc']?
> > >
> > > Any help would be greatly appreciated
> > > Pete
>
> There seem to be two different ways of understand the OP sort order.
>

The way I took it, 3zxc comes first because the number is 3 which is smaller
than 21 which is smaller than 134445.

It happened to be a coincidence that the list reversed was in that same
order.

So, if I am right about the definition of how to sort, the method I would
use is to strip each string of anything beyond its leading digits, save that
as a key, use the string as the value.  Then sort by key

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/4a932579/attachment.html>

From steve at pearwood.info  Tue Sep 14 14:45:31 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 14 Sep 2010 22:45:31 +1000
Subject: [Tutor] If/elif/else when a list is empty
In-Reply-To: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
References: <8CD21D82CB6D020-9A8-48FE@web-mmc-m01.sysops.aol.com>
Message-ID: <201009142245.32947.steve@pearwood.info>

On Tue, 14 Sep 2010 01:58:07 pm aeneas24 at priest.com wrote:

> if len(rgenre)>0:
>           if len(rgenre)>2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3=rgenre[2]
>           elif len(rgenre)==2:
>               rg1=rgenre[0]
>               rg2=rgenre[1]
>               rg3="NA"
>           elif len(rgenre)==1:
>               rg1=rgenre[0]
>               rg2="NA"
>               rg3="NA"
>    else len(rgenre)<1: # I was hoping this would take care of the
> "there is no genre information" scenario but it doesn't
> rg1=rg2=rg3="NA"

The above will give a SyntaxError, because you can't have a condition 
immediately after an else.

This is a neater way to write the above:

n = len(rgenre)
if n == 0:
    rg1 = rg2 = rg3 = "NA"
elif n == 1:
    rg1 = rgenre[0]
    rg2 = rg3 = "NA"
elif n == 2:
    rg1, rg2 = rgenre[0:2]
    rg3 = "NA"
else:
    rg1, rg2, rg3 = rgenre[:3]

which in turn can be shortened to the slightly cryptic one-liner:

rg1, rg2, rg3 = (rgenre + ["NA"]*3)[:3]

as already discussed earlier.




-- 
Steven D'Aprano

From fal at libero.it  Tue Sep 14 16:11:09 2010
From: fal at libero.it (Francesco Loffredo)
Date: Tue, 14 Sep 2010 16:11:09 +0200
Subject: [Tutor] list index out of range
In-Reply-To: <283313442.1436289.1284069140597.JavaMail.root@ksu-mailstore04.merit.edu>
References: <283313442.1436289.1284069140597.JavaMail.root@ksu-mailstore04.merit.edu>
Message-ID: <4C8F827D.1050303@libero.it>

My humble guess: (sure, the full traceback would help A LOT!)

On 09/09/2010 23.52, Todd Ballard wrote:
> y=[daily_solar_radiation["MJ"][0]]
> for i in xrange(0,275):
>      y=[daily_solar_radiation["MJ"]][i]+y[i-1] # <--THIS y[i-1] is out of bounds when i=0 !!!

Hope that helps

Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 -  Data di rilascio: 09/13/10 08:35:00

From rwobben at hotmail.com  Tue Sep 14 16:29:10 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 14:29:10 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <201009142130.02459.steve@pearwood.info>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>
Message-ID: <SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>




----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Tue, 14 Sep 2010 21:30:01 +1000
> Subject: Re: [Tutor] FW: wierd replace problem
>
> On Tue, 14 Sep 2010 05:38:18 pm Roelof Wobben wrote:
>
>>>> Strip ('"'') does not work.
>>>> Still this message : SyntaxError: EOL while scanning string
>>>> literal
> [...]
>> I understand what you mean but we're talking about a text-file which
>> will be read in a string. So I can't escape the quotes. As far as I
>> know I can't control how Python is reading a text-file with quotes.
>
> The text file has nothing to do with this. The text file is fine. The
> error is in the strings that YOU type, not the text file.
>
> Strings must have MATCHING quotation marks:
>
> This is okay: "abcd"
> So is this: 'abcd'
>
> But this is not: "abcd'
>
> You need to *look carefully* at strings you type and make sure that the
> start and end quotes match. Likewise you can't insert the SAME
> quotation mark in a string unless you escape it first:
>
> This is okay: "'Hello,' he said."
> So is this: '"Goodbye," she replied.'
>
> But this is not: 'He said "I can't see you."'
>
> But this is okay: 'He said "I can\'t see you."'
>
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Oke, 
 
I see the problem.
 
When I have this sentence : `'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'

And I do string.strip() the output will be :
 
`'This and that one does not fit your explanation.
So I have to strip everything before I strip it. 
 
Roelof
  		 	   		  

From joel.goldstick at gmail.com  Tue Sep 14 17:28:10 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 14 Sep 2010 11:28:10 -0400
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
Message-ID: <AANLkTinMezFNuRMwbMbd0NUv11zRt5pW4QUfM0zYcbix@mail.gmail.com>

On Tue, Sep 14, 2010 at 10:29 AM, Roelof Wobben <rwobben at hotmail.com> wrote:

I offer my solution.  I didn't bother to make every word lower case, and I
think that would improve the result

Please offer critique, improvements


Some explaination:

line 5 -- I read the complete text into full_text, while first replacing --
with a space
line 7 -- I split the full text string into words
lines 8 - 15 -- Word by word I strip all sorts of characters that aren't in
words from the front and back of each 'word'
lines 11 - 14 -- this is EAFP -- try to add one to the bin with that word,
if no such bin, make it and give it 1
lines 16, 17 -- since dicts don't sort, sort on the keys then loop thru the
keys to print out the key (word) and the count


> ----------------------------------------
>
 1 #! /usr/bin/env python
  2
  3 word_count = {}
  4 file = open ('alice_in_wonderland.txt', 'r')
  5 full_text = file.read().replace('--',' ')
  6
  7 full_text_words = full_text.split()
  8 for words in full_text_words:
  9     stripped_words = words.strip(".,!?'`\"- ();:")
 10     ##print stripped_words
 11     try:
 12         word_count[stripped_words] += 1
 13     except KeyError:
 14         word_count[stripped_words] = 1
 15
 16 ordered_keys = word_count.keys()
 17 ordered_keys.sort()
 18 ##print ordered_keys
 19 print "All the words and their frequency in 'alice in wonderland'"
 20 for k in ordered_keys:
 21     print k, word_count[k]
 22
-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/f28b8b0b/attachment.html>

From rwobben at hotmail.com  Tue Sep 14 17:44:18 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 15:44:18 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W53C39AFC169F2083A53E3DAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<AANLkTinMezFNuRMwbMbd0NUv11zRt5pW4QUfM0zYcbix@mail.gmail.com>,
	<SNT118-W53C39AFC169F2083A53E3DAE780@phx.gbl>
Message-ID: <SNT118-W6540E579C934FDEE9A9338AE780@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: joel.goldstick at gmail.com
> Subject: RE: [Tutor] FW: wierd replace problem
> Date: Tue, 14 Sep 2010 15:43:42 +0000
>
>
>
>
> ________________________________
>> Date: Tue, 14 Sep 2010 11:28:10 -0400
>> From: joel.goldstick at gmail.com
>> To: tutor at python.org
>> Subject: Re: [Tutor] FW: wierd replace problem
>>
>>
>>
>> On Tue, Sep 14, 2010 at 10:29 AM, Roelof Wobben
>>> wrote:
>>
>> I offer my solution. I didn't bother to make every word lower case,
>> and I think that would improve the result
>>
>> Please offer critique, improvements
>>
>>
>> Some explaination:
>>
>> line 5 -- I read the complete text into full_text, while first
>> replacing -- with a space
>> line 7 -- I split the full text string into words
>> lines 8 - 15 -- Word by word I strip all sorts of characters that
>> aren't in words from the front and back of each 'word'
>> lines 11 - 14 -- this is EAFP -- try to add one to the bin with that
>> word, if no such bin, make it and give it 1
>> lines 16, 17 -- since dicts don't sort, sort on the keys then loop thru
>> the keys to print out the key (word) and the count
>>
>> ----------------------------------------
>> 1 #! /usr/bin/env python
>> 2
>> 3 word_count = {}
>> 4 file = open ('alice_in_wonderland.txt', 'r')
>> 5 full_text = file.read().replace('--',' ')
>> 6
>> 7 full_text_words = full_text.split()
>> 8 for words in full_text_words:
>> 9 stripped_words = words.strip(".,!?'`\"- ();:")
>> 10 ##print stripped_words
>> 11 try:
>> 12 word_count[stripped_words] += 1
>> 13 except KeyError:
>> 14 word_count[stripped_words] = 1
>> 15
>> 16 ordered_keys = word_count.keys()
>> 17 ordered_keys.sort()
>> 18 ##print ordered_keys
>> 19 print "All the words and their frequency in 'alice in wonderland'"
>> 20 for k in ordered_keys:
>> 21 print k, word_count[k]
>> 22
>> --
>> Joel Goldstick
>>
>>
>> _______________________________________________ Tutor maillist -
>> Tutor at python.org To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Hello Joel,

Your solution works.
Im getting grazy. I tried it two days with strip and get a eof error message and now no messages.

Roelof


  		 	   		  

From fal at libero.it  Tue Sep 14 17:45:35 2010
From: fal at libero.it (Francesco Loffredo)
Date: Tue, 14 Sep 2010 17:45:35 +0200
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
Message-ID: <4C8F989F.6040200@libero.it>

On 14/09/2010 16.29, Roelof Wobben wrote:
>...
> Oke,
>
> I see the problem.
>
> When I have this sentence : `'Tis so,' said the Duchess:  `and the moral of that is--"Oh,
> 'tis love, 'tis love, that makes the world go round!"'
>
> And I do string.strip() the output will be :
>
> `'This and that one does not fit your explanation.
> So I have to strip everything before I strip it.

After some trial and error with the interpreter, I found this:

st = """`'Tis so,' said the Duchess:  `and the moral of that is--"Oh, 
'tis love, 'tis love, that makes the world go round!"'"""  # notice the 
starting and ending triple quotes, just to avoid all the backslashes and 
the ambiguities with quoting characters ;-)

wordlist = [thisone.strip("""'",!` :-""") for thisone in st.replace('"', 
" ").replace("-"," ").split()]

I don't know if you read the chapter regarding "list comprehensions" in 
your tutorial, but this is one of those. First of all, I replace all 
double quotes " and dashes - with spaces:
st.replace('"', " ").replace("-"," ")
then I use split() to divide the long string in a list of almost-words.
At the end, with the for clause in the list comprehension, I strip all 
leading and trailing non-letters (again, I enclose them in a 
triple-quoted string) from each of the elements of the list.

In the end, I have wordlist:

['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of', 
'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes', 
'the', 'world', 'go', 'round', '']

What about this? Was it confusing?
>
> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 -  Data di rilascio: 09/13/10 08:35:00

From rwobben at hotmail.com  Tue Sep 14 18:35:54 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 16:35:54 +0000
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <4C8F989F.6040200@libero.it>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<4C8F2516.4060906@gmail.com>, ,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>, ,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<4C8F989F.6040200@libero.it>
Message-ID: <SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>




----------------------------------------
Date: Tue, 14 Sep 2010 17:45:35 +0200
From: fal at libero.it
To: tutor at python.org
Subject: Re: [Tutor] FW: wierd replace problem


On 14/09/2010 16.29, Roelof Wobben wrote:
>...
> Oke,
>
> I see the problem.
>
> When I have this sentence : `'Tis so,' said the Duchess: `and the moral of that is--"Oh,
> 'tis love, 'tis love, that makes the world go round!"'
>
> And I do string.strip() the output will be :
>
> `'This and that one does not fit your explanation.
> So I have to strip everything before I strip it.

After some trial and error with the interpreter, I found this:

st = """`'Tis so,' said the Duchess: `and the moral of that is--"Oh,
'tis love, 'tis love, that makes the world go round!"'""" # notice the
starting and ending triple quotes, just to avoid all the backslashes and
the ambiguities with quoting characters ;-)

wordlist = [thisone.strip("""'",!` :-""") for thisone in st.replace('"',
" ").replace("-"," ").split()]

I don't know if you read the chapter regarding "list comprehensions" in
your tutorial, but this is one of those. First of all, I replace all
double quotes " and dashes - with spaces:
st.replace('"', " ").replace("-"," ")
then I use split() to divide the long string in a list of almost-words.
At the end, with the for clause in the list comprehension, I strip all
leading and trailing non-letters (again, I enclose them in a
triple-quoted string) from each of the elements of the list.

In the end, I have wordlist:

['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of',
'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes',
'the', 'world', 'go', 'round', '']

What about this? Was it confusing?
>
> Roelof
Francesco
 
hello Franceso,
 
It was not confusing when I read your explanation.
Still im grazy wht with you and Joel the strip works and with me I get errors.
 
But how can I use the triple quotes when reading a textf-file ?
Roelof


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

From mnshtb at gmail.com  Tue Sep 14 18:41:09 2010
From: mnshtb at gmail.com (Michael Scharf)
Date: Tue, 14 Sep 2010 12:41:09 -0400
Subject: [Tutor] re.findall parentheses problem
Message-ID: <AANLkTikhJ1+=v99vOSHq+G1LxDeiqTfdUV8AFs9L0WUw@mail.gmail.com>

Hi all,

I have a regex that matches dates in various formats.  I've tested the regex
in a reliable testbed, and it seems to match what I want (dates in formats
like "1 Jan 2010" and "January 1, 2010" and also "January 2008").  It's just
that using re.findall with it is giving me weird output.  I'm using Python
2.6.5 here, and I've put in line breaks for clarity's sake:

>>> import re

>>> date_regex =
re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])")

>>> test_output = re.findall(date_regex, 'January 1, 2008')

>>> print test_output
[('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '',
'', '', ' ', ' ', '', '20', '', '', '', '08')]

>>> test_output = re.findall(date_regex, 'January 1, 2008')

>>> print test_output
[('', '', '', '', 'January', 'January', '', '', '', '', '', '', '', '', '',
'', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008')]

>>> test_output = re.findall(date_regex, "The date was January 1, 2008.  But
it was not January 2, 2008.")

>>> print test_output
[('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '',
'', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '',
'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ',
'', '2,', ' ', ' ', '', '2008')]

A friend says: " I think that the problem is that every time that you have a
parenthesis you get an output. Maybe there is a way to suppress this."

My friend's explanation speaks to the empties, but maybe not to the two
Januaries.  Either way, what I want is for re.finall, or some other re
method that perhaps I haven't properly explored, to return the matches and
just the matches.

I've read the documentation, googled various permutations etc, and I can't
figure it out.  Any help much appreciated.

Thanks,
Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/427eb084/attachment-0001.html>

From timomlists at gmail.com  Tue Sep 14 18:50:45 2010
From: timomlists at gmail.com (Timo)
Date: Tue, 14 Sep 2010 18:50:45 +0200
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W6540E579C934FDEE9A9338AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<AANLkTinMezFNuRMwbMbd0NUv11zRt5pW4QUfM0zYcbix@mail.gmail.com>,
	<SNT118-W53C39AFC169F2083A53E3DAE780@phx.gbl>
	<SNT118-W6540E579C934FDEE9A9338AE780@phx.gbl>
Message-ID: <4C8FA7E5.8050404@gmail.com>

On 14-09-10 17:44, Roelof Wobben wrote:
>>> 9 stripped_words = words.strip(".,!?'`\"- ();:")
>>>
>>>        
>>
>>      
> Hello Joel,
>
> Your solution works.
> Im getting grazy. I tried it two days with strip and get a eof error message and now no messages.
>    
Look at the backslash! It doesn't strip the backslash in the string, but 
it escapes the double quote following it.

I don't know how people can explain it any better.

You *do* see that this doesn't work, right?
 >>> s = "foo"bar"

So you can't do this either:
 >>> word.strip(",.!";:")

You need to escape the quote between the quotes:
 >>> word.strip(".,!\";:")

Timo

> Roelof
>
>
>    		 	   		
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


From joel.goldstick at gmail.com  Tue Sep 14 18:51:32 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 14 Sep 2010 12:51:32 -0400
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
	<4C8F989F.6040200@libero.it>
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
Message-ID: <AANLkTinfXFAznmxvKnfUWL82B-9Gx+=RNCuPnX5rrw9-@mail.gmail.com>

On Tue, Sep 14, 2010 at 12:35 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

>
>
>
>
> But how can I use the triple quotes when reading a textf-file ?
> Roelof
>

The triple quotes let you put quotes inside them... for instance if you want
to check for single and double quotes, and ) you can do this:
 """'")"""

its hard to make out.. so with double spacing (you can't do this.. just to
illustrate:):      """ ' " ) """

>
>
>

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/eadcf0e7/attachment.html>

From evert.rol at gmail.com  Tue Sep 14 18:56:11 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 14 Sep 2010 18:56:11 +0200
Subject: [Tutor] re.findall parentheses problem
In-Reply-To: <AANLkTikhJ1+=v99vOSHq+G1LxDeiqTfdUV8AFs9L0WUw@mail.gmail.com>
References: <AANLkTikhJ1+=v99vOSHq+G1LxDeiqTfdUV8AFs9L0WUw@mail.gmail.com>
Message-ID: <90F8D7CE-BE27-4FCD-BAD8-1741BA50C6DA@gmail.com>

> I have a regex that matches dates in various formats.  I've tested the regex in a reliable testbed, and it seems to match what I want (dates in formats like "1 Jan 2010" and "January 1, 2010" and also "January 2008").  It's just that using re.findall with it is giving me weird output.  I'm using Python 2.6.5 here, and I've put in line breaks for clarity's sake:
> 
> >>> import re
> 
> >>> date_regex = re.compile(r"([0-3]?[0-9])?((\s*)|(\t*))((Jan\.?u?a?r?y?)|(Feb\.?r?u?a?r?y?)|(Mar\.?c?h?)|(Apr\.?i?l?)|(May)|(Jun[e.]?)|(Jul[y.]?)|(Aug\.?u?s?t?)|(Sep[t.]?\.?e?m?b?e?r?)|(Oct\.?o?b?e?r?)|(Nov\.?e?m?b?e?r?)|(Dec\.?e?m?b?e?r?))((\s*)|(\t*))(2?0?[0-3]?[0-9]\,?)?((\s*)|(\t*))(2?0?[01][0-9])")

This will also match '1 Janry 2010'. 
Not sure if it should?


<snip>two examples</snip>

> >>> test_output = re.findall(date_regex, "The date was January 1, 2008.  But it was not January 2, 2008.")
> 
> >>> print test_output
> [('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), ('', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')]
> 
> A friend says: " I think that the problem is that every time that you have a parenthesis you get an output. Maybe there is a way to suppress this."
> 
> My friend's explanation speaks to the empties, but maybe not to the two Januaries.  Either way, what I want is for re.finall, or some other re method that perhaps I haven't properly explored, to return the matches and just the matches.       
> 
> I've read the documentation, googled various permutations etc, and I can't figure it out.  Any help much appreciated.

The docs say: " If one or more groups are present in the pattern, return a list of groups". So your friend is right.

In fact, your last example shows exactly this: it shows a list of two tuples. The tuples contain individual group matches, the two list elements are your two date matches.
You could solve this by grouping the entire regex (so r"(([0-3 .... [0-9]))" ; I would even use a named group), and then picking out the first tuple element of each list element:
[(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'), (' January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '', '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')]


Hth,

  Evert


From mnshtb at gmail.com  Tue Sep 14 19:09:21 2010
From: mnshtb at gmail.com (Michael Scharf)
Date: Tue, 14 Sep 2010 13:09:21 -0400
Subject: [Tutor] re.findall parentheses problem
In-Reply-To: <90F8D7CE-BE27-4FCD-BAD8-1741BA50C6DA@gmail.com>
References: <AANLkTikhJ1+=v99vOSHq+G1LxDeiqTfdUV8AFs9L0WUw@mail.gmail.com>
	<90F8D7CE-BE27-4FCD-BAD8-1741BA50C6DA@gmail.com>
Message-ID: <AANLkTineFtvGwXN2uEKPnhJHacNsrvweMcJ3uoBydAsH@mail.gmail.com>

Hi Evert,

Thank you.  I should have figured "groups" were the paren groups.  I see it
clearly now.  And your solution will work for the larger thing I'm trying to
do --- thanks.

And yes: I know this matches some non-date-like dates, but the data is such
that it should work out ok.

Thanks again,
Mike



> This will also match '1 Janry 2010'.
> Not sure if it should?
>
>
> > A friend says: " I think that the problem is that every time that you
> have a parenthesis you get an output. Maybe there is a way to suppress
> this."
> >
>
The docs say: " If one or more groups are present in the pattern, return a
> list of groups". So your friend is right.
>
> In fact, your last example shows exactly this: it shows a list of two
> tuples. The tuples contain individual group matches, the two list elements
> are your two date matches.
> You could solve this by grouping the entire regex (so r"(([0-3 ....
> [0-9]))" ; I would even use a named group), and then picking out the first
> tuple element of each list element:
> [(' January 1, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '',
> '', '', '', '', '', '', '', '', ' ', ' ', '', '1,', ' ', ' ', '', '2008'),
> (' January 2, 2008', '', ' ', ' ', '', 'January', 'January', '', '', '', '',
> '', '', '', '', '', '', '', ' ', ' ', '', '2,', ' ', ' ', '', '2008')]
>
>
> Hth,
>
>  Evert
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/2a552936/attachment.html>

From bill at celestial.net  Tue Sep 14 18:59:20 2010
From: bill at celestial.net (Bill Campbell)
Date: Tue, 14 Sep 2010 09:59:20 -0700
Subject: [Tutor] A Plea for Sensible Quoting
In-Reply-To: <20100914114215.GK2670@cecilia>
References: <20100914114215.GK2670@cecilia>
Message-ID: <20100914165920.GA13891@ayn.mi.celestial.com>

On Tue, Sep 14, 2010, Michael Powe wrote:
>Hello,
>
>I read this list in a linux console using mutt. I dunno, maybe I'm the
>only idiot left still using a console mail client.  I write my emails
>and email replies in emacs, too, which may make me even weirder.

Mutt in xterms here with vi (I've never been able to get my
fingers retrained for emacs after almost 30 years of vi :-).

Agreed on the quoting.  Interspersing new information between
quoted sections is great, but quoting an entire message only to
add ``ditto'' at the end is idiotic.

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

Democracy extends the sphere of individual freedom,  Democracy attaches
all possible value to each man, while socialism makes each man a mere
agent, a mere number. Democracy and socialism have nothing in common but
one word: equality. But notice the difference: while democracy seeks
equality in liberty, socialism seeks equality in restraint and servitude.
   Alexis de Tocqueville == 1848

From sander.sweers at gmail.com  Tue Sep 14 19:28:28 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Tue, 14 Sep 2010 19:28:28 +0200
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <4C8FA7E5.8050404@gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	, <4C8F2516.4060906@gmail.com>
	, <SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	, <201009142130.02459.steve@pearwood.info>
	, <SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
	, <AANLkTinMezFNuRMwbMbd0NUv11zRt5pW4QUfM0zYcbix@mail.gmail.com>
	, <SNT118-W53C39AFC169F2083A53E3DAE780@phx.gbl>
	<SNT118-W6540E579C934FDEE9A9338AE780@phx.gbl>
	<4C8FA7E5.8050404@gmail.com>
Message-ID: <1284485308.30519.2.camel@Nokia-N900>


----- Original message -----
> Look at the backslash! It doesn't strip the backslash in the string, but 
> it escapes the double quote following it.
> 
> I don't know how people can explain it any better.

Maybe the link below makes it clear what backslash really does.

http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/

Greets
sander 

From rwobben at hotmail.com  Tue Sep 14 19:41:36 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 17:41:36 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W2543BB20B16DEC4E8739D7AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, , ,
	<4C8F2516.4060906@gmail.com>, , ,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>, , ,
	<201009142130.02459.steve@pearwood.info>, , ,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>, , ,
	<AANLkTinMezFNuRMwbMbd0NUv11zRt5pW4QUfM0zYcbix@mail.gmail.com>, ,
	, <SNT118-W53C39AFC169F2083A53E3DAE780@phx.gbl>,
	<SNT118-W6540E579C934FDEE9A9338AE780@phx.gbl>,
	<4C8FA7E5.8050404@gmail.com>,
	<1284485308.30519.2.camel@Nokia-N900>,
	<SNT118-W2543BB20B16DEC4E8739D7AE780@phx.gbl>
Message-ID: <SNT118-W26AF7602CE1FAB8BF8E83FAE780@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: sander.sweers at gmail.com
> Subject: RE: [Tutor] FW: wierd replace problem
> Date: Tue, 14 Sep 2010 17:40:28 +0000
>
>
>
>
> ----------------------------------------
>> From: sander.sweers at gmail.com
>> To: tutor at python.org
>> Date: Tue, 14 Sep 2010 19:28:28 +0200
>> Subject: Re: [Tutor] FW: wierd replace problem
>>
>>
>> ----- Original message -----
>>> Look at the backslash! It doesn't strip the backslash in the string, but
>>> it escapes the double quote following it.
>>>
>>> I don't know how people can explain it any better.
>>
>> Maybe the link below makes it clear what backslash really does.
>>
>> http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/
>>
>> Greets
>> sander
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>

Oke,

I get it.
When I want to delete a " I have to use a backslash.

For me case closed. Everyone thanks for the patience and explanations.

Roelof 		 	   		  

From fal at libero.it  Tue Sep 14 20:11:04 2010
From: fal at libero.it (Francesco Loffredo)
Date: Tue, 14 Sep 2010 20:11:04 +0200
Subject: [Tutor] FW:  wierd replace problem
In-Reply-To: <SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>, ,
	<4C8F2516.4060906@gmail.com>, ,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>, ,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<4C8F989F.6040200@libero.it>
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
Message-ID: <4C8FBAB8.9020804@libero.it>

On 14/09/2010 18.35, Roelof Wobben wrote:
> ...
> It was not confusing when I read your explanation.
> Still im grazy wht with you and Joel the strip works and with me I get errors.
>
> But how can I use the triple quotes when reading a textf-file ?
Very easy: YOU DON'T NEED TO USE ANY QUOTES.
All the quoting stuff is ONLY needed for literals, that is for those 
strings you directly write in a program. For example:

MyString = """ these are my favourite quoting characters: "'` """  # 
here you need to avoid ambiguities, because quoting chars are also used 
to start and end the string.
You could obtain EXACTLY the same string with backslash-quoting:

YourString = ' these are my favourite quoting characters: "\'` '  # here 
I had to quote the single-quote char

HerString = " these are my favourite quoting characters: \"'` "  # and 
here the double quote had to be quoted by backslash

But when you DON'T write the string yourself, you don't need any quoting:
ThisString = MyString + YourString + HerString  # no quoting required
ThatString = file.read() # again, NO QUOTING REQUIRED.

> Roelof
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3132 -  Data di rilascio: 09/13/10 08:35:00

From michael at trollope.org  Tue Sep 14 20:49:27 2010
From: michael at trollope.org (Michael Powe)
Date: Tue, 14 Sep 2010 14:49:27 -0400
Subject: [Tutor] re.findall parentheses problem
In-Reply-To: <AANLkTineFtvGwXN2uEKPnhJHacNsrvweMcJ3uoBydAsH@mail.gmail.com>
References: <AANLkTikhJ1+=v99vOSHq+G1LxDeiqTfdUV8AFs9L0WUw@mail.gmail.com>
	<90F8D7CE-BE27-4FCD-BAD8-1741BA50C6DA@gmail.com>
	<AANLkTineFtvGwXN2uEKPnhJHacNsrvweMcJ3uoBydAsH@mail.gmail.com>
Message-ID: <20100914184927.GL2670@cecilia>

On Tue, Sep 14, 2010 at 01:09:21PM -0400, Michael Scharf wrote:

> Thank you.  I should have figured "groups" were the paren groups.  I see it
> clearly now.  And your solution will work for the larger thing I'm trying to
> do --- thanks.
 
> And yes: I know this matches some non-date-like dates, but the data is such
> that it should work out ok.

Hello,

I second the advice to use named groups.  This option makes it sooo
much easier to retrieve your captures; especially, if you have nested
groups. No more working out if the capture you want is in group 1 or
group 3.  Just matcher.group('January').

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"We had pierced the veneer of outside things.  We had `suffered,
starved, and triumphed, groveled down yet grasped at glory, grown
bigger in the bigness of the whole.'  We had seen God in his
splendors, heard the text that Nature renders.  We had reached the
naked soul of man." -- Sir Ernest Shackleton, <South>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/888e1c75/attachment.pgp>

From wprins at gmail.com  Tue Sep 14 22:05:06 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 14 Sep 2010 21:05:06 +0100
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
	<4C8F989F.6040200@libero.it>
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
Message-ID: <AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>

Roelof,

On 14 September 2010 17:35, Roelof Wobben <rwobben at hotmail.com> wrote:

> But how can I use the triple quotes when reading a textf-file ?
>

To repeat what I said before, obviously not clearly enough:  All the quoting
stuff, escaping stuff, all of that ONLY APPLIES TO STRINGS/DATA INSIDE OF
YOUR PYTHON CODE.  It does NOT APPLY TO DATA INSIDE OF FILES!  Why not to
files?  Because there's no ambiguity in data inside a file.  It's understood
that everything in a file is just data.  By contrast, in Python code, quote
characters have *meaning*.  Specifically they indicate the start and end of
string literals.  So when they themselves are part of teh string you have to
write them specially to indicate their meaning, either as closing the
string, or as part of the string data.

In a file by contrast, every character is presumed to be just a piece of
data, and so quotes have no special inherent meaning to Python, so they just
represent themselves and always just form part of the data being read from
the file.   Do you understand what I'm saying?  If you have any doubt please
respond so we can try to get this cleared up -- Unless and until you realise
there's a difference between data in a file and string literals in your
python source code you're not going to undertand what you're doing here.

Regards,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/573c9c82/attachment.html>

From rwobben at hotmail.com  Tue Sep 14 22:10:10 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 14 Sep 2010 20:10:10 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<4C8F989F.6040200@libero.it>,
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>,
	<AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>
Message-ID: <SNT118-W39C18507CC2D7253B68FA7AE780@phx.gbl>




________________________________
> Date: Tue, 14 Sep 2010 21:05:06 +0100
> Subject: Re: [Tutor] FW: wierd replace problem
> From: wprins at gmail.com
> To: rwobben at hotmail.com
> CC: tutor at python.org
>
> Roelof,
>
> On 14 September 2010 17:35, Roelof Wobben
>> wrote:
> But how can I use the triple quotes when reading a textf-file ?
>
> To repeat what I said before, obviously not clearly enough: All the
> quoting stuff, escaping stuff, all of that ONLY APPLIES TO STRINGS/DATA
> INSIDE OF YOUR PYTHON CODE. It does NOT APPLY TO DATA INSIDE OF
> FILES! Why not to files? Because there's no ambiguity in data inside
> a file. It's understood that everything in a file is just data. By
> contrast, in Python code, quote characters have *meaning*.
> Specifically they indicate the start and end of string literals. So
> when they themselves are part of teh string you have to write them
> specially to indicate their meaning, either as closing the string, or
> as part of the string data.
>
> In a file by contrast, every character is presumed to be just a piece
> of data, and so quotes have no special inherent meaning to Python, so
> they just represent themselves and always just form part of the data
> being read from the file. Do you understand what I'm saying? If you
> have any doubt please respond so we can try to get this cleared up --
> Unless and until you realise there's a difference between data in a
> file and string literals in your python source code you're not going to
> undertand what you're doing here.
>
> Regards,
>
> Walter

 
I understand it but I try to understand why in a file there is this 'word python makes a "'word.
I know that a file is just data but I thought that if that data is read in a string I could work with the quoting stuff.
But im very wrong here.
 
Roelof
 
  		 	   		  

From ranceh at gmail.com  Tue Sep 14 22:11:50 2010
From: ranceh at gmail.com (Rance Hall)
Date: Tue, 14 Sep 2010 15:11:50 -0500
Subject: [Tutor] how best to implement paginated data in CLI
Message-ID: <AANLkTi=J0jCuOgFHVcr=CbHJhEX831i1vtTW0e7YX0pZ@mail.gmail.com>

I'm using python 3.1 with py-postgresql (located at
http://python.projects.postgresql.org/

I need to work through how best to paginate larger sql result sets.

my SELECT statement returns a list, I can get its len() to find out
that X records were returned

What I want to do is print the first N records and include a
Previous/Next Choice at the bottom.

I know I'll be making some use of the start and stop optional
parameters in the for loop that processes the list.

I think that I'll need variables for the page size (#of records per
screen) and a start position for where to begin in the list.

I want to make this a function so that its reusable code

Here is a first draft of the idea: (untested)

def paginate_stuff(list,start)
    pagesize = 10
    for row in list[start:start+pagesize]
        print(row["column"])
    print ("\n")
    message = ""
    prompt = ""
    if not start == 0:
        message = message + "Previous"
        prompt = prompt + "P"
    if not start ==0 and not start+pagesize >= len(list):
        message = message + " or "
        prompt = prompt + " or "
     if not start+pagesize >= len(list):
         message = message + "Next"
         prompt = prompt + "N"
     print((message+"\n")
     choice = input(prompt+"? ")
     if choice == "n' or "N":
         paginate_stuff(list,start + pagesize)
     if choice == "p" or "P":
         paginate_stuff(list,start - pagesize)
return

I'm not certain at this writing of the proper syntax of the if
statement conditions, I will look that up to be sure the syntax is
right.

What I want to ask about is the logic flow, does this make sense?  Am
I thinking about the problem the right way? Is there a better way to
pull this off?

From wprins at gmail.com  Tue Sep 14 23:15:40 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 14 Sep 2010 22:15:40 +0100
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <SNT118-W39C18507CC2D7253B68FA7AE780@phx.gbl>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
	<4C8F989F.6040200@libero.it>
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
	<AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>
	<SNT118-W39C18507CC2D7253B68FA7AE780@phx.gbl>
Message-ID: <AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>

On 14 September 2010 21:10, Roelof Wobben <rwobben at hotmail.com> wrote:

> I understand it but I try to understand why in a file there is this 'word
> python makes a "'word.
>

Python doesn't change what it reads from the file.  However, depending on
how you ask Python to tell you what it's read (or what the contents of a
string variable is), it might display it quoted, and/or include escape
charaters, or not as the case may be.  If what you've read from the file
contains quotes, then obviously you need to be careful to not mistake
Python's quoting of the value of a string as being *part* of that string.
Neither must you mistake the escape character (if applicable) from being
actually part of the string.

For example, consider the following exchange in the Python shell (please try
all of this yourself and experiment):

>>> s = 'blah'
>>> s
'blah'
>>> print s
blah
>>>

I assign the value of 'blah' to the string s. So far simple enough.
Obviosuly the quotes used int the assignment of the string does not form
part of the string itself.  Their utility is only to delineate to Python the
start of the string, and the end of the string.

In the next line I ask Python to evaluate the expression s, which it duly
reporst as 'blah'.  Again, it's using normal Python convention to format the
data as a string, because that's what s is, a string object.  But the quotes
are formatting, they're not really part of the string.

In the next line I ask Python to *print *s.  Now, the true content of s is
printed as it is, and hence you can see that the quotes are not part of the
string.

Now consider the following exchange in the Python shell where I open a file
and write some text to it to prove this point:
>>> f = open('test.txt', 'w+')
>>> f.write('blah')
>>> f.close()
>>> import os
>>> os.system('notepad test.txt')

The last line above opens the text file test.txt in Notepad so you can see
the contents.  As you can see, no quotes or anything else.  Now, while open,
suppose we put a single quote in the file, so it reads:
'blah
...and suppose we then save it and exit notepad so you're back in the Python
shell.  Then we do:

>>> f=open('test.txt','r+')
>>> s=f.read()
>>> f.close()
>>> s
"'blah"

Now I've read the contents of the file back into a string variable s, and
asked Python to evaluate (output) this string object.

Notice, Python is now formatting the string with *doube* quotes (previously
it defaulted to single quotes) to avoid having to escape the single quote
that forms part of the string.  If Python had used single quotes instead,
then there would've been an ambiguity with the single quote that's part of
the string and so it would've had to escape that too.  So consequently it
formats the string with double quotes, which is valid Python syntax and
avoids the backslash. (Stating the obvious, strings can be quoted with
double or single quotes.)  As before, the double quotes, as with the single
quotes earlier, are not part of the string.  They are merely formatting
since Python is being asked to display a string and hence it must indicate
the start and end of the string with suitable quote characters.

Now, as before do:

>>> print s
'blah

As before, with print you see the contents of the string as it is (and as
indeed it is also in the file that you saved). Just the single quote you
added at the front of Blah. No double or single quotes or anything else.

Now finally, let's try something a bit more elaborate.  Do again:

>>> os.system('notepad test.txt')

Then put into the file the following 2 lines of text (notice the file now
contains 2 lines, and both single and double quotes...):
+++"+++This line is double quoted in the file and the quotes have + symbols
around them.+++"+++
---'---This line is single quoted in the file and the quotes have - symbols
around them.---'---

Save it, exit Notepad, then do:
>>> f=open('test.txt', 'r+')
>>> s=f.read()
>>> f.close()
>>> s
'+++"+++This line is double quoted in the file and the quotes have + symbols
around them.+++"+++\n---\'---This line is single quoted in the file and the
quotes have - symbols around them.---\'---\n'
>>> print s
+++"+++This line is double quoted in the file and the quotes have + symbols
around them.+++"+++
---'---This line is single quoted in the file and the quotes have - symbols
around them.---'---

Notice we read both lines in the file into one single string.  See how
Python formats that as a string object, and escapes not only the single
quotes but also the line break characters (\n).  See also when Python is
asked to "print" the string, you can see the escape characters really there.
See what's happened?  Do you understand why?

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/46f2b432/attachment.html>

From wprins at gmail.com  Tue Sep 14 23:20:33 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 14 Sep 2010 22:20:33 +0100
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<4C8F2516.4060906@gmail.com>
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>
	<201009142130.02459.steve@pearwood.info>
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>
	<4C8F989F.6040200@libero.it>
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>
	<AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>
	<SNT118-W39C18507CC2D7253B68FA7AE780@phx.gbl>
	<AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>
Message-ID: <AANLkTin74wbpV5zpvFqrnqLtH=E4Y1uYx2oKtTqGbHVz@mail.gmail.com>

Correction on my last paragraph on my last mail:
"See also when Python is asked to "print" the string, you can see the escape
characters really there." -> "See also when Python is asked to "print" the
string, you can see the escape characters aren't part of the actual contents
of the string."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/d6f9f95e/attachment.html>

From steve at pearwood.info  Tue Sep 14 23:37:06 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 15 Sep 2010 07:37:06 +1000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTin74wbpV5zpvFqrnqLtH=E4Y1uYx2oKtTqGbHVz@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>
	<AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>
	<AANLkTin74wbpV5zpvFqrnqLtH=E4Y1uYx2oKtTqGbHVz@mail.gmail.com>
Message-ID: <201009150737.07527.steve@pearwood.info>

On Wed, 15 Sep 2010 07:20:33 am Walter Prins wrote:
> Correction on my last paragraph on my last mail:
> "See also when Python is asked to "print" the string, you can see the
> escape characters really there." -> "See also when Python is asked to
> "print" the string, you can see the escape characters aren't part of
> the actual contents of the string."

I think that half of the confusion here is that people are confused 
about what escape characters are. When you read text from a file, and 
Python sees a backslash, it DOESN'T add a second backslash to escape 
it. Nor does it add quotation marks at the start or end.

Text is text. The characters you read from a text file -- or the bytes 
you read from any file -- remain untouched, exactly as they existed in 
the file. But what changes is the DISPLAY of the text.

When you have the four characters abcd (with no quotation marks) and you 
ask Python to display it on the command line, the display includes 
punctuation, in this case quotation marks, just like a list includes 
punctuation [,] and a dict {:,}. If the string includes certain special 
characters like newlines, tabs, backslashes and quotation marks, the 
display uses escape codes \n \t \\ \' or \" as punctuation to the 
display only. But the extra backslashes don't exist in the string, any 
more than lists include items [ and ].

When you enter string literals, the way to enter them is by typing the 
display form. The display form includes matching quotation marks at the 
beginning and end, and escaping special characters. But that 
punctuation isn't part of the string.



-- 
Steven D'Aprano

From sunny_ashi1 at hotmail.com  Tue Sep 14 22:08:19 2010
From: sunny_ashi1 at hotmail.com (Sukhpal Saini)
Date: Tue, 14 Sep 2010 20:08:19 +0000
Subject: [Tutor] (no subject)
Message-ID: <BLU138-W310B8CE4B1063F47145717CD780@phx.gbl>


Hi! I have a problem. I just started python. when I use (open) function, is the file supposed to open? Because it doesn't.  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/c42164ac/attachment.html>

From anand.shashwat at gmail.com  Wed Sep 15 01:39:27 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Wed, 15 Sep 2010 05:09:27 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <BLU138-W310B8CE4B1063F47145717CD780@phx.gbl>
References: <BLU138-W310B8CE4B1063F47145717CD780@phx.gbl>
Message-ID: <AANLkTi=YS6G8rpt5O7GsfNAjcm_nDyO6caQpGfmVX8zj@mail.gmail.com>

On Wed, Sep 15, 2010 at 1:38 AM, Sukhpal Saini <sunny_ashi1 at hotmail.com>wrote:

>  Hi! I have a problem. I just started python. when I use (open) function,
> is the file supposed to open? Because it doesn't.
>

f = open('filename', 'r')  opens the file in read-only format. There are
others like binary, write, append etc. Check the manual for that.
To read it you need to use read() or readline()
Ex, s = f.read()
Now s will be a string containing the contents of file.


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/97da31ae/attachment.html>

From alan.gauld at btinternet.com  Wed Sep 15 01:48:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 00:48:05 +0100
Subject: [Tutor] (no subject)
References: <BLU138-W310B8CE4B1063F47145717CD780@phx.gbl>
Message-ID: <i6p1jn$dnf$1@dough.gmane.org>


"Sukhpal Saini" <sunny_ashi1 at hotmail.com> wrote
> Hi! I have a problem. I just started python. when I
> use (open) function, is the file supposed to open?
> Because it doesn't.

How do you know? Are you also new to programming?
Or do you know another programming language?

Assuming that you are new to programming....
Are you expecting a window to appear with the file displayed?
If so you will be disappointed, open() simply makes the file available
to your program to manipulate. Any display of the file is down
to you as the programmer.

See the Handling Files topic of my tutorial for more information.

OTOH If you realized that but genuinely believe that open()
is not returning an open file object then you will need to give
us some more context - ideally some sample code and
any error messages. Please tell us which OS you are
using too.


HTH,

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





From alan.gauld at btinternet.com  Wed Sep 15 01:51:34 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 00:51:34 +0100
Subject: [Tutor] wierd replace problem
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl><i6ln0f$36j$1@dough.gmane.org>
	<201009142229.48660.steve@pearwood.info>
Message-ID: <i6p1q8$ebi$1@dough.gmane.org>


"Steven D'Aprano" <steve at pearwood.info> wrote 

>> OK,. Thats replacing a double slash in the data
> 
> Er, surely not... I think you've confused backslashes and forward 
> slashes. Or something. '\\' is a single backslash, not a double, 
> because the first backslash is the escape character.
> 
> A double backslash can be written '\\\\'.

Erk, you are right of course, he would need to use a raw string 
to do it with a literal double slash. Silly me.

However, based on his post I still think his issue may be one 
of represention not content.

Alan G.


From alan.gauld at btinternet.com  Wed Sep 15 01:57:35 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 00:57:35 +0100
Subject: [Tutor] input problem
References: <AANLkTi=vKtZ5NLJqQi68Cx+iAaiiuh5_cp6xFAGVmHBk@mail.gmail.com>
Message-ID: <i6p25i$fe7$1@dough.gmane.org>


"ANKUR AGGARWAL" <coolankur2006 at gmail.com> wrote

> Suppose i am taking input or various variables like
> a=raw_input("...............") //hello
> b=raw_input("................")//hi
> but i want to run a common function when input is hello
>
> so instead of
> if a=="hello":
> fun()
> then again for b and then again for c then d and so on i have to 
> apply the
> code for the specific variable ,
> i want to run the function whenever in the code input is "hello"
> i am wondering is there is any way like
> if input=="hello":
> fun()

I don;t see how that changes from the previous example except
you changed a to input?

However I think you are asking about processing a collection
of data values (which happen to have been produced by raw_input()
but could equally have been read from a file).

The pattern for that case is the for loop:

for data in data_collection:
     if data == "hello":
         fun()

Or if you want to collect the results:

results = [fun() for data in data_collection if data == "hello"]

How you get the data into data_collecton I leave as an excercise! :-)


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



From alan.gauld at btinternet.com  Wed Sep 15 02:15:53 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 01:15:53 +0100
Subject: [Tutor] how best to implement paginated data in CLI
References: <AANLkTi=J0jCuOgFHVcr=CbHJhEX831i1vtTW0e7YX0pZ@mail.gmail.com>
Message-ID: <i6p37s$j07$1@dough.gmane.org>


"Rance Hall" <ranceh at gmail.com> wrote

> I'm using python 3.1 with py-postgresql (located at
> http://python.projects.postgresql.org/
>
> I need to work through how best to paginate larger sql result sets.

Its usually best to do that at the SQL level by controlling the 
cursor.
I don't know PostGres but most SQL dialects allow you to control
the number of result rows returned to the cursor then fetch the next
group and the next etc. This will also potentially save a lot of 
network
bandwidth (you only fetch the results you need which may not be
all of them) and get your results back quicker for a big result set.

HTH,


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



From cjo1555 at gmail.com  Wed Sep 15 02:00:54 2010
From: cjo1555 at gmail.com (Ciera Jones)
Date: Tue, 14 Sep 2010 19:00:54 -0500
Subject: [Tutor] help with integers
Message-ID: <6275663A-EEAF-4172-89D5-618A40FA38C8@gmail.com>

Hi
When I enter myvar= raw_input ("Please excuse a number of movies: ")
and I try and convert it to an integer it gives me an error message. 
I put in:
movietotal=  int("myvar")* 3 and I get an error message 
Ciera 

From joel.goldstick at gmail.com  Wed Sep 15 02:22:11 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 14 Sep 2010 20:22:11 -0400
Subject: [Tutor] help with integers
In-Reply-To: <6275663A-EEAF-4172-89D5-618A40FA38C8@gmail.com>
References: <6275663A-EEAF-4172-89D5-618A40FA38C8@gmail.com>
Message-ID: <AANLkTim7S_Jf4f-_BgXNsd_npCbz2GVWO2VgMOyMazUK@mail.gmail.com>

On Tue, Sep 14, 2010 at 8:00 PM, Ciera Jones <cjo1555 at gmail.com> wrote:

> Hi
> When I enter myvar= raw_input ("Please excuse a number of movies: ")
> and I try and convert it to an integer it gives me an error message.
> I put in:
> movietotal=  int("myvar")* 3 and I get an error message
> Ciera
>

post your code.. and also windows/linux/mac?

if you post code and error message it will be easier to help

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/cece4ec0/attachment-0001.html>

From alan.gauld at btinternet.com  Wed Sep 15 02:23:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 01:23:05 +0100
Subject: [Tutor] help with integers
References: <6275663A-EEAF-4172-89D5-618A40FA38C8@gmail.com>
Message-ID: <i6p3lc$ka6$1@dough.gmane.org>


"Ciera Jones" <cjo1555 at gmail.com> wrote

> When I enter myvar= raw_input ("Please excuse a number of movies: ")
> and I try and convert it to an integer it gives me an error message.
> I put in:
> movietotal=  int("myvar")* 3 and I get an error message

Don't put quotes around the variable name.
Python is trying to convert the string "myvar" to an int, which it 
can't.

BTW When posting it is best to send the code plus entire error 
message,
it greatly helps us debug the problem.


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



From kb1pkl at aim.com  Wed Sep 15 02:30:39 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Tue, 14 Sep 2010 20:30:39 -0400
Subject: [Tutor] Writing to Sound
Message-ID: <4C9013AF.6050802@aim.com>

  Greetings tutors.

First off, here is what I'm doing. I'm taking pi (3.141592 etc. etc. 
etc.), taking two values at a time, and then mapping the two values to 
pitch and length. I'm then using winsound.Beep to beep for x ms, at y 
frequency. What I want to do, is write that to file. Judging from 
http://codingmess.blogspot.com/2008/07/how-to-make-simple-wav-file-with-python.html, 
it seems to be more complex than I care to undertake without exploring 
the possibilities. Are there any simpler or higher level ways? I 
wouldn't mind something like sound_file.write(freq, length) like Beep 
does, but that may or may not exist. I dunno, a simple google doesn't 
yield anything.

Thanks!

From mehgcap at gmail.com  Wed Sep 15 03:43:49 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Tue, 14 Sep 2010 21:43:49 -0400
Subject: [Tutor] list dll functions?
Message-ID: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>

Hi all,
Out of curiosity: I know I can call dll functions from python using
the win32 lib, but is there any way to simply "examine" a loaded dll
to see all of the functions and attributes it exposes for use? I would
do no good with a hex editor since I have no idea what all the numbers
mean, so I am hoping for a plaintext representation of a dll's
possibilities and am most comfortable in Python. I am running the
latest 2.6 on win7. TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From amonroe at columbus.rr.com  Wed Sep 15 03:53:14 2010
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Tue, 14 Sep 2010 21:53:14 -0400
Subject: [Tutor] list dll functions?
In-Reply-To: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>
References: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>
Message-ID: <147280350512.20100914215314@columbus.rr.com>

> the win32 lib, but is there any way to simply "examine" a loaded dll
> to see all of the functions and attributes it exposes for use? I would

http://www.dependencywalker.com/


From ranceh at gmail.com  Wed Sep 15 03:57:13 2010
From: ranceh at gmail.com (Rance Hall)
Date: Tue, 14 Sep 2010 20:57:13 -0500
Subject: [Tutor] how best to implement paginated data in CLI
In-Reply-To: <i6p37s$j07$1@dough.gmane.org>
References: <AANLkTi=J0jCuOgFHVcr=CbHJhEX831i1vtTW0e7YX0pZ@mail.gmail.com>
	<i6p37s$j07$1@dough.gmane.org>
Message-ID: <AANLkTikc_L0fkWYFwjVbr0VbNpqZpMxnnuKThFxgGGOn@mail.gmail.com>

On Tue, Sep 14, 2010 at 7:15 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Rance Hall" <ranceh at gmail.com> wrote
>
>> I'm using python 3.1 with py-postgresql (located at
>> http://python.projects.postgresql.org/
>>
>> I need to work through how best to paginate larger sql result sets.
>
> Its usually best to do that at the SQL level by controlling the cursor.
> I don't know PostGres but most SQL dialects allow you to control
> the number of result rows returned to the cursor then fetch the next
> group and the next etc. This will also potentially save a lot of network
> bandwidth (you only fetch the results you need which may not be
> all of them) and get your results back quicker for a big result set.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/

Alan:

I think I need to refine my definition of large in my original question.

You are correct, but I think some more context might be in order.

A standard windows terminal window opens to run my app and it has
anywhere between 15 and 20 lines of text available for output.  (that
can be altered I know, but that has limits)

Some of those lines are taken up with formatting and the question and
input prompt at the bottom, so you have only room for 10 data elements
from your list,

In my case large is any recordset larger than the ten there is room
for on a single screen.

So the real question is how large is large?

I'm operating under the assumption that the size of the datasets Im
talking about are "small" in terms of what I usually think of when I
think of databases and networking, bandwidth and the like.  But large
in terms of the delivery mechanism (the windows terminal window)

I suspect that the extra network activity required to manage cursors
on a remote database is in my case meaningful.

I hope this sort of helps explain why I went where I went with my OP.

In reviewing the app I'm hoping to replace I found the size of the
client list is under 100 records.

Given this new information, do you still think that db cursors is the way to go?

From ilhs_hs at yahoo.com  Wed Sep 15 04:10:59 2010
From: ilhs_hs at yahoo.com (Hs Hs)
Date: Tue, 14 Sep 2010 19:10:59 -0700 (PDT)
Subject: [Tutor] selecting elements from dictionary
Message-ID: <777963.88618.qm@web111208.mail.gq1.yahoo.com>


dear group:

I have a dictionary object that looks like this:



xdic
{11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 11135699: [1, 
2], 11135702: [1, 3], 11135901: [1]}


I want to print only those items that have [1,2] and [1,3]  in any order, such 
as [1,2] or [2,1], [3,1] or [1,3]


>>> for item in xdic.keys():
...     if [1,2] in xdic[item]:
...             print item


I get a wrong answer, I know the values are there. How can I print only those 
item that have [1,2] and [1,3]

Thank you. 
h


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100914/f89e9410/attachment.html>

From mehgcap at gmail.com  Wed Sep 15 04:37:57 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Tue, 14 Sep 2010 22:37:57 -0400
Subject: [Tutor] list dll functions?
In-Reply-To: <147280350512.20100914215314@columbus.rr.com>
References: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>
	<147280350512.20100914215314@columbus.rr.com>
Message-ID: <AANLkTimdnqVR8TbPnn3Wa1nmRZ9MVh78KfT2e0V_yN7z@mail.gmail.com>

On 9/14/10, R. Alan Monroe <amonroe at columbus.rr.com> wrote:
>> the win32 lib, but is there any way to simply "examine" a loaded dll
>> to see all of the functions and attributes it exposes for use? I would
>
> http://www.dependencywalker.com/
A great program, thanks! Best of all, for me anyway, it works well (so
far) with JAWS, my screen reader. It is increasingly rare to find
fully accessible programs nowadays, and I am glad that this one works.
Now I just have to figure out how to see the expected arguments of a
function, but I am sure that is in the manual somewhere...
>
> _______________________________________________
> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From knacktus at googlemail.com  Wed Sep 15 05:51:48 2010
From: knacktus at googlemail.com (Knacktus)
Date: Wed, 15 Sep 2010 05:51:48 +0200
Subject: [Tutor] selecting elements from dictionary
In-Reply-To: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
References: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
Message-ID: <4C9042D4.20405@googlemail.com>

> xdic
> {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2],
> 11135699: [1, 2], 11135702: [1, 3], 11135901: [1]}
>
>
> I want to print only those items that have [1,2] and [1,3] in any order,
> such as [1,2] or [2,1], [3,1] or [1,3]
>
>
>  >>> for item in xdic.keys():
> ... if [1,2] in xdic[item]:
> ... print item
>
You can loop over the values directly:

xdic = {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 
11135699: [1, 2], 11135702: [1, 3], 11135901: [1]}

for values in xdic.values():
     if len(values) == 2:
         print values

or if you only want values which contain 1 and 2 or 3:

for values in xdic.values():
     if 1 in values and 2 in values or 3 in values:
         print values

or a combination of the above, where you check the length and the 
content of the list.

HTH,

Jan

From rwobben at hotmail.com  Wed Sep 15 09:03:27 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 15 Sep 2010 07:03:27 +0000
Subject: [Tutor] FW: wierd replace problem
In-Reply-To: <AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>
References: <SNT118-W20EE5218594101142C465AAE770@phx.gbl>,
	<4C8F2516.4060906@gmail.com>,
	<SNT118-W19F7837B53FB488EE296EBAE780@phx.gbl>,
	<201009142130.02459.steve@pearwood.info>,
	<SNT118-W2643047ECF9C6D5B71DD40AE780@phx.gbl>,
	<4C8F989F.6040200@libero.it>,
	<SNT118-W5441623F55E6AC7610CCEEAE780@phx.gbl>,
	<AANLkTi=ZWDStanMcT1hw9rQVpT_-N5CbBzj6Qs7ALxmE@mail.gmail.com>,
	<SNT118-W39C18507CC2D7253B68FA7AE780@phx.gbl>,
	<AANLkTimDoQDbCNTe8GU51cnHM5hYEHCUSg=_-ZVid0Dt@mail.gmail.com>
Message-ID: <SNT118-W5823E6405B8CA1A142330EAE790@phx.gbl>




________________________________
> Date: Tue, 14 Sep 2010 22:15:40 +0100
> From: wprins at gmail.com
> To: tutor at python.org
> Subject: Re: [Tutor] FW: wierd replace problem
>
>
>
> On 14 September 2010 21:10, Roelof Wobben
>> wrote:
> I understand it but I try to understand why in a file there is this
> 'word python makes a "'word.
>
> Python doesn't change what it reads from the file. However, depending
> on how you ask Python to tell you what it's read (or what the contents
> of a string variable is), it might display it quoted, and/or include
> escape charaters, or not as the case may be. If what you've read from
> the file contains quotes, then obviously you need to be careful to not
> mistake Python's quoting of the value of a string as being *part* of
> that string. Neither must you mistake the escape character (if
> applicable) from being actually part of the string.
>
> For example, consider the following exchange in the Python shell
> (please try all of this yourself and experiment):
>
>>>> s = 'blah'
>>>> s
> 'blah'
>>>> print s
> blah
>>>>
>
> I assign the value of 'blah' to the string s. So far simple enough.
> Obviosuly the quotes used int the assignment of the string does not
> form part of the string itself. Their utility is only to delineate to
> Python the start of the string, and the end of the string.
>
> In the next line I ask Python to evaluate the expression s, which it
> duly reporst as 'blah'. Again, it's using normal Python convention to
> format the data as a string, because that's what s is, a string
> object. But the quotes are formatting, they're not really part of the
> string.
>
> In the next line I ask Python to print s. Now, the true content of s
> is printed as it is, and hence you can see that the quotes are not part
> of the string.
>
> Now consider the following exchange in the Python shell where I open a
> file and write some text to it to prove this point:
>>>> f = open('test.txt', 'w+')
>>>> f.write('blah')
>>>> f.close()
>>>> import os
>>>> os.system('notepad test.txt')
>
> The last line above opens the text file test.txt in Notepad so you can
> see the contents. As you can see, no quotes or anything else. Now,
> while open, suppose we put a single quote in the file, so it reads:
> 'blah
> ...and suppose we then save it and exit notepad so you're back in the
> Python shell. Then we do:
>
>>>> f=open('test.txt','r+')
>>>> s=f.read()
>>>> f.close()
>>>> s
> "'blah"
>
> Now I've read the contents of the file back into a string variable s,
> and asked Python to evaluate (output) this string object.
>
> Notice, Python is now formatting the string with *doube* quotes
> (previously it defaulted to single quotes) to avoid having to escape
> the single quote that forms part of the string. If Python had used
> single quotes instead, then there would've been an ambiguity with the
> single quote that's part of the string and so it would've had to escape
> that too. So consequently it formats the string with double quotes,
> which is valid Python syntax and avoids the backslash. (Stating the
> obvious, strings can be quoted with double or single quotes.) As
> before, the double quotes, as with the single quotes earlier, are not
> part of the string. They are merely formatting since Python is being
> asked to display a string and hence it must indicate the start and end
> of the string with suitable quote characters.
>
> Now, as before do:
>
>>>> print s
> 'blah
>
> As before, with print you see the contents of the string as it is (and
> as indeed it is also in the file that you saved). Just the single quote
> you added at the front of Blah. No double or single quotes or anything
> else.
>
> Now finally, let's try something a bit more elaborate. Do again:
>
>>>> os.system('notepad test.txt')
>
> Then put into the file the following 2 lines of text (notice the file
> now contains 2 lines, and both single and double quotes...):
> +++"+++This line is double quoted in the file and the quotes have +
> symbols around them.+++"+++
> ---'---This line is single quoted in the file and the quotes have -
> symbols around them.---'---
>
> Save it, exit Notepad, then do:
>>>> f=open('test.txt', 'r+')
>>>> s=f.read()
>>>> f.close()
>>>> s
> '+++"+++This line is double quoted in the file and the quotes have +
> symbols around them.+++"+++\n---\'---This line is single quoted in the
> file and the quotes have - symbols around them.---\'---\n'
>>>> print s
> +++"+++This line is double quoted in the file and the quotes have +
> symbols around them.+++"+++
> ---'---This line is single quoted in the file and the quotes have -
> symbols around them.---'---
>
> Notice we read both lines in the file into one single string. See how
> Python formats that as a string object, and escapes not only the single
> quotes but also the line break characters (\n). See also when Python
> is asked to "print" the string, you can see the escape characters
> really there. See what's happened? Do you understand why?
>
> Walter
>
>
>
>
>
>
> _______________________________________________ Tutor maillist -
> Tutor at python.org To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
hello Walter, 
 
I think I understand why.
 
Python formats the string with a '.
Because there are  ' and " in the string Python has to use escape characters because otherwise Python can never know when the string begins and ends. When you only use ' or " then python uses the other so I knows when a string begins and end.
 
Roelof
  		 	   		  

From jsoares at Safe-mail.net  Wed Sep 15 02:09:25 2010
From: jsoares at Safe-mail.net (jsoares at Safe-mail.net)
Date: Tue, 14 Sep 2010 18:09:25 -0600
Subject: [Tutor] what happened to the cards module
Message-ID: <N1-J8cqcwb_6W@Safe-mail.net>

I downloaded Python 2.6.6 for windows but I can't access the "Cards" module for playing card games.

Did it get renamed? If so, how can I find it?

Thanks.

John Soares
jsoares at safe-mail.net

From zepangolin at gmail.com  Wed Sep 15 10:22:26 2010
From: zepangolin at gmail.com (patrice laporte)
Date: Wed, 15 Sep 2010 10:22:26 +0200
Subject: [Tutor] list dll functions ?
Message-ID: <AANLkTi=cskLQ-sz6o3SAABhmv6rz_vQbrVdc=wMBcf8Z@mail.gmail.com>

Dependdencyy walker is a good tool, but as you have seen it doesn't give you
function's signature. If you explore a MS dll, you should to have a look at
MSDN and read about the function description.

A bit out of subject : There is no way to find the function's signature only
from exploring the binary file (I never found one at least). Following
article explain the MS PE (Portable Executable, no elf format in Windows),
but it doesn't explain more about signature. this is why you need headers
and lib file to link a w32 app.

http://msdn.microsoft.com/en-us/library/ms809762.aspx
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/2b0fd818/attachment.html>

From evert.rol at gmail.com  Wed Sep 15 10:40:34 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 15 Sep 2010 10:40:34 +0200
Subject: [Tutor] what happened to the cards module
In-Reply-To: <N1-J8cqcwb_6W@Safe-mail.net>
References: <N1-J8cqcwb_6W@Safe-mail.net>
Message-ID: <4CA61F01-FB61-4A77-B4C0-4EF8A2226FC4@gmail.com>

> I downloaded Python 2.6.6 for windows but I can't access the "Cards" module for playing card games.
> 
> Did it get renamed? If so, how can I find it?

I don't think there's a Cards module in the standard library. At least, I've never seen it, nor can I find any mention about it on the python documentation page.

Probably this is a module you installed yourself later on, and is now only accessible for your previous Python version? You would have to reinstall it for Python 2.6.
How did you previously use Cards? What Python version.

Btw, I don't know what your upgrade path is, but can't you go to Python 2.7 directly?

  Evert


From alan.gauld at btinternet.com  Wed Sep 15 11:13:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 10:13:46 +0100
Subject: [Tutor] how best to implement paginated data in CLI
References: <AANLkTi=J0jCuOgFHVcr=CbHJhEX831i1vtTW0e7YX0pZ@mail.gmail.com><i6p37s$j07$1@dough.gmane.org>
	<AANLkTikc_L0fkWYFwjVbr0VbNpqZpMxnnuKThFxgGGOn@mail.gmail.com>
Message-ID: <i6q2od$tq9$1@dough.gmane.org>


"Rance Hall" <ranceh at gmail.com> wrote

> In reviewing the app I'm hoping to replace I found the size of the
> client list is under 100 records.
>
> Given this new information, do you still think that db cursors is 
> the way to go?

Using the cursor is a more scaleable solution but if you are sure you 
only
ever have 100 or so rows then I agree that sing a local client side 
windowing
scheme may be as effective.

Using the cursor should not be onerous however, it should look 
something
like:

configure cursor page size
for each page in cursor
      display screen
      process data

The only downside is, as you say that you are now dipping into the 
cursor
for every 10 records which would be a lot of network traffic. I'd 
expect the
"induistrial" solution to this to be something like

set cursor to 100 records (or even 1000 depending on size)
for each page in cursor
     for each screen in page
          display screen
          process data

So if you are sure you will only ever have about 100 records you can
omit the cursor paging.


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



From alan.gauld at btinternet.com  Wed Sep 15 11:18:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 10:18:05 +0100
Subject: [Tutor] list dll functions?
References: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>
Message-ID: <i6q30g$uv8$1@dough.gmane.org>


"Alex Hall" <mehgcap at gmail.com> wrote

> Out of curiosity: I know I can call dll functions from python using
> the win32 lib, but is there any way to simply "examine" a loaded dll
> to see all of the functions and attributes it exposes for use?

There are various tools around to do that and hopefully some
documentation!

But often nowadays DLLs expose a COM object model and
you have a COM browser built into Pythonwin. That will give
you a windows explorer type view of the objects and their
operations.

If the DLL is purely perocedural then that won't help.

HTH,


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



From alan.gauld at btinternet.com  Wed Sep 15 11:24:09 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 10:24:09 +0100
Subject: [Tutor] Writing to Sound
References: <4C9013AF.6050802@aim.com>
Message-ID: <i6q3bt$pv$1@dough.gmane.org>

"Corey Richardson" <kb1pkl at aim.com> wrote

> First off, here is what I'm doing. I'm taking pi (3.141592 etc. etc. 
> etc.), taking two values at a time, and then mapping the two values 
> to pitch and length. I'm then using winsound.Beep to beep for x ms, 
> at y frequency.

So far I understand.

> What I want to do, is write that to file.

Write what?
The sound generated by Beep or the data used to drive Beep?

> Judging from 
> http://codingmess.blogspot.com/2008/07/how-to-make-simple-wav-file-with-python.html, 
> it seems to be more complex than I care to undertake without 
> exploring the possibilities.

That tells you how to make a wav file that will play in any standard 
media
player program. Is that what you want?

> Are there any simpler or higher level ways?

It depends what you want the file to be. What do you intend to do with 
the file?

> wouldn't mind something like sound_file.write(freq, length) like 
> Beep does, but that may or may not exist.

You can write the two values to a file so that you can read it back 
later
and send the values to Beep. Thats trivial. But the file will not play 
in a
standard player.

> I dunno, a simple google doesn't yield anything.

That probably depends on what you are searching for.
I'm not clear from your description what you want to do.

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



From steve at pearwood.info  Wed Sep 15 13:21:42 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 15 Sep 2010 21:21:42 +1000
Subject: [Tutor] what happened to the cards module
In-Reply-To: <N1-J8cqcwb_6W@Safe-mail.net>
References: <N1-J8cqcwb_6W@Safe-mail.net>
Message-ID: <201009152121.43325.steve@pearwood.info>

On Wed, 15 Sep 2010 10:09:25 am jsoares at safe-mail.net wrote:
> I downloaded Python 2.6.6 for windows but I can't access the "Cards"
> module for playing card games.

There is no "Cards" module in the standard library. You'll need to go 
back to wherever you found it in the first place. Google might help.


-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep 15 13:27:05 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 15 Sep 2010 21:27:05 +1000
Subject: [Tutor] selecting elements from dictionary
In-Reply-To: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
References: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
Message-ID: <201009152127.05941.steve@pearwood.info>

On Wed, 15 Sep 2010 12:10:59 pm Hs Hs wrote:

> I want to print only those items that have [1,2] and [1,3]  in any
> order, such as [1,2] or [2,1], [3,1] or [1,3]
>
> >>> for item in xdic.keys():
>
> ...     if [1,2] in xdic[item]:
> ...             print item
>
> I get a wrong answer, 

That's because you ask the wrong question.

[1,2] in xdic[item] doesn't check to see if 1 is in the list, then if 2 
is in the list. It looks to see if one of the items is *exactly* [1,2].

>>> [1,2] in [1,2,3,4]
False
>>> [1,2] in [1,2,3,4, [1,2]]
True


> I know the values are there. How can I print 
> only those item that have [1,2] and [1,3]

for key, value in xdic.items():
    if 1 in value and 2 in value or 3 in value:
        print key




-- 
Steven D'Aprano

From jojo.mwebaze at gmail.com  Wed Sep 15 15:36:54 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Wed, 15 Sep 2010 15:36:54 +0200
Subject: [Tutor] intercepting and recored I/O function calls
Message-ID: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>

Hello Tutor

I would like to intercept and record I/O function calls to a file.. (later
to a database) with probably the names of the files that have been created,
accessed / deleted in my program. I  have not done something like this
before.. Some Guidance is highly appreciated

Johnson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/38eaebc3/attachment.html>

From ilhs_hs at yahoo.com  Wed Sep 15 16:31:54 2010
From: ilhs_hs at yahoo.com (Hs Hs)
Date: Wed, 15 Sep 2010 07:31:54 -0700 (PDT)
Subject: [Tutor] selecting elements from dictionary
In-Reply-To: <201009152127.05941.steve@pearwood.info>
References: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
	<201009152127.05941.steve@pearwood.info>
Message-ID: <454427.17833.qm@web111211.mail.gq1.yahoo.com>

Dear Steven, 
Thanks for your help. 

however I have a question, 

using:

for key, value in xdic.items():
    if 1 in value and 2 in value or 3 in value:
        print key


also print keys that have values such as [1,2,3]. 

In cases where there is [1,2,3] and [1,2] also reported. 

How can I extract those keys that have values only [1,2] and [1,3] exclusively. 


>>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
>>>75797987:[3,1]}
>>> for key, value in xdic.items():
...     if 1 in value and 2 in value or 3 in value:
...             print key
...
75797987
75796988
75797478
75797887


Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and 
75797987:[3,1]
how can I force this. 

thanks again. 








________________________________
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Sent: Wed, September 15, 2010 7:27:05 AM
Subject: Re: [Tutor] selecting elements from dictionary

On Wed, 15 Sep 2010 12:10:59 pm Hs Hs wrote:

> I want to print only those items that have [1,2] and [1,3]  in any
> order, such as [1,2] or [2,1], [3,1] or [1,3]
>
> >>> for item in xdic.keys():
>
> ...     if [1,2] in xdic[item]:
> ...             print item
>
> I get a wrong answer, 

That's because you ask the wrong question.

[1,2] in xdic[item] doesn't check to see if 1 is in the list, then if 2 
is in the list. It looks to see if one of the items is *exactly* [1,2].

>>> [1,2] in [1,2,3,4]
False
>>> [1,2] in [1,2,3,4, [1,2]]
True


> I know the values are there. How can I print 
> only those item that have [1,2] and [1,3]

for key, value in xdic.items():
    if 1 in value and 2 in value or 3 in value:
        print key




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



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/61f794dc/attachment.html>

From evert.rol at gmail.com  Wed Sep 15 16:36:08 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 15 Sep 2010 16:36:08 +0200
Subject: [Tutor] selecting elements from dictionary
In-Reply-To: <454427.17833.qm@web111211.mail.gq1.yahoo.com>
References: <777963.88618.qm@web111208.mail.gq1.yahoo.com>
	<201009152127.05941.steve@pearwood.info>
	<454427.17833.qm@web111211.mail.gq1.yahoo.com>
Message-ID: <161D31C4-6307-4C72-854B-33FCCD54AC51@gmail.com>

> using:
> 
> for key, value in xdic.items():
>     if 1 in value and 2 in value or 3 in value:
>         print key
> 
> 
> also print keys that have values such as [1,2,3]. 
> 
> In cases where there is [1,2,3] and [1,2] also reported. 
> 
> How can I extract those keys that have values only [1,2] and [1,3] exclusively.  

If you know that elements in a list are unique (so only appear once), you may want to look at using sets.

  Evert


> >>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 75797987:[3,1]}
> >>> for key, value in xdic.items():
> ...     if 1 in value and 2 in value or 3 in value:
> ...             print key
> ...
> 75797987
> 75796988
> 75797478
> 75797887
> 
> 
> Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and 75797987:[3,1]
> how can I force this. 
> 
> thanks again. 
> 
> 
> 
> 
> 
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Sent: Wed, September 15, 2010 7:27:05 AM
> Subject: Re: [Tutor] selecting elements from dictionary
> 
> On Wed, 15 Sep 2010 12:10:59 pm Hs Hs wrote:
> 
> > I want to print only those items that have [1,2] and [1,3]  in any
> > order, such as [1,2] or [2,1], [3,1] or [1,3]
> >
> > >>> for item in xdic.keys():
> >
> > ...    if [1,2] in xdic[item]:
> > ...            print item
> >
> > I get a wrong answer, 
> 
> That's because you ask the wrong question.
> 
> [1,2] in xdic[item] doesn't check to see if 1 is in the list, then if 2 
> is in the list. It looks to see if one of the items is *exactly* [1,2].
> 
> >>> [1,2] in [1,2,3,4]
> False
> >>> [1,2] in [1,2,3,4, [1,2]]
> True
> 
> 
> > I know the values are there. How can I print 
> > only those item that have [1,2] and [1,3]
> 
> for key, value in xdic.items():
>     if 1 in value and 2 in value or 3 in value:
>         print key
> 
> 
> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From adam.jtm30 at gmail.com  Wed Sep 15 16:52:56 2010
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Wed, 15 Sep 2010 15:52:56 +0100
Subject: [Tutor] selecting elements from dictionary
In-Reply-To: <454427.17833.qm@web111211.mail.gq1.yahoo.com>
References: <777963.88618.qm@web111208.mail.gq1.yahoo.com>	<201009152127.05941.steve@pearwood.info>
	<454427.17833.qm@web111211.mail.gq1.yahoo.com>
Message-ID: <4C90DDC8.5080903@gmail.com>

On 15/09/10 15:31, Hs Hs wrote:
> Dear Steven,
> Thanks for your help.
>
> however I have a question,
>
> using:
>
> for key, value in xdic.items():
>     if 1 in value and 2 in value or 3 in value:
>         print key
>
>
> also print keys that have values such as [1,2,3].
>
> In cases where there is [1,2,3] and [1,2] also reported.
>
> How can I extract those keys that have values only [1,2] and [1,3] 
> exclusively.
>
>
> >>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
> 75797987:[3,1]}
> >>> for key, value in xdic.items():
> ...     if 1 in value and 2 in value or 3 in value:
> ...             print key
> ...
> 75797987
> 75796988
> 75797478
> 75797887
>
>
> Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and 
> 75797987:[3,1]
> how can I force this.
If you just have a few specific cases you can use "in" to check whether 
the values you are interested in appear in a specified collection, ie:

 >>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
75797987:[3,1]}
 >>> for key, value in xdic.items():
...     if value in ([1,2], [2,1], [1,3], [3,1]):
...             print key
...
75797987
75797887

HTH


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/05f8af41/attachment-0001.html>

From evert.rol at gmail.com  Wed Sep 15 18:24:58 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 15 Sep 2010 18:24:58 +0200
Subject: [Tutor] what happened to the cards module
In-Reply-To: <N1-M3am1ukcgL@Safe-mail.net>
References: <N1-M3am1ukcgL@Safe-mail.net>
Message-ID: <AE4E12EE-8996-497D-8E2E-F2DF8EE30C82@gmail.com>

> Hi Evert:
> 
> I've been looking for a card playing framework for a long time. When I saw "import Cards" and that he was shuffling, dealing cards, etc, I immediately downloaded Python. Could this be available in Pygames?

It depends where you "him" shuffling & dealing cards. 
Pygames doesn't exist, pygame does, but probably doesn't have what you're looking for.

I do remember a set of questions on this list with a Cards example, but that was just some home-written code.

You'll need to check the context of where you saw this, and if it's useful and usable to you.
And I certainly don't know what you mean by a card playing framework: do you mean (library) code, which language, what "card game"?

  Evert



> Thanks.
> 
> John Soares
> jsoares at safe-mail.net
> 
> -------- Original Message --------
> From: Evert Rol <evert.rol at gmail.com>
> To: jsoares at Safe-mail.net
> Cc: tutor at python.org
> Subject: Re: [Tutor] what happened to the cards module
> Date: Wed, 15 Sep 2010 10:40:34 +0200
> 
>> I downloaded Python 2.6.6 for windows but I can't access the "Cards" module for playing card games.
>> 
>> Did it get renamed? If so, how can I find it?
> 
> I don't think there's a Cards module in the standard library. At least, I've never seen it, nor can I find any mention about it on the python documentation page.
> 
> Probably this is a module you installed yourself later on, and is now only accessible for your previous Python version? You would have to reinstall it for Python 2.6.
> How did you previously use Cards? What Python version.
> 
> Btw, I don't know what your upgrade path is, but can't you go to Python 2.7 directly?
> 
>  Evert


From kb1pkl at aim.com  Wed Sep 15 18:48:01 2010
From: kb1pkl at aim.com (kb1pkl at aim.com)
Date: Wed, 15 Sep 2010 12:48:01 -0400 (EDT)
Subject: [Tutor] Writing to Sound
In-Reply-To: <i6q3bt$pv$1@dough.gmane.org>
References: <4C9013AF.6050802@aim.com> <i6q3bt$pv$1@dough.gmane.org>
Message-ID: <8CD230CE4CB8507-1B4C-175D@webmail-d097.sysops.aol.com>




-----Original Message-----
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor <tutor at python.org>
Sent: Wed, Sep 15, 2010 5:26 am
Subject: Re: [Tutor] Writing to Sound


"Corey Richardson" <kb1pkl at aim.com> wrote

> First off, here is what I'm doing. I'm taking pi (3.141592 etc. etc.
> etc.), taking two values at a time, and then mapping the two values
> to pitch and length. I'm then using winsound.Beep to beep for x ms,
> at y frequency.

So far I understand.

> What I want to do, is write that to file.

Write what?
The sound generated by Beep or the data used to drive Beep?

[snip]

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


-----------------------------


  I want to write the sound generated by Beep to file, or sound at the 
same pitch and length. Sorry that that wasn't clear
~Corey RIchardson

From alan.gauld at btinternet.com  Wed Sep 15 19:03:52 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 15 Sep 2010 10:03:52 -0700 (PDT)
Subject: [Tutor] list dll functions?
In-Reply-To: <AANLkTi=+NOsgNtYenZTDt3Ad0D6=QtkJUxjfD9mhjubY@mail.gmail.com>
References: <AANLkTinKVf6C2g9=cG5v7sFu94fh20YuQm+dpKJv4+i_@mail.gmail.com>
	<i6q30g$uv8$1@dough.gmane.org>
	<AANLkTi=+NOsgNtYenZTDt3Ad0D6=QtkJUxjfD9mhjubY@mail.gmail.com>
Message-ID: <242913.84210.qm@web86703.mail.ird.yahoo.com>

Find the Pythonwin IDE executable and run it - its a better IDE than IDLE in my 
opinion, especially if you are on Windows.

Once it is started you can go to the Tools->COM Browser menu item and 
it starts an explorer type Window. The top level "folders" are:

Registered Objects
Running Objects
Registered Type Libraries

You can then drill down and explore as you wish.
For example under Registered Type Libraries there is Accessibility.
Within that there is TypeLibrary-> IAccessible-Dispatch
Within that there are functions such as  AddRef, Invoke, GetTypeInfo etc.

Inside those you can see the parameters etc.


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




----- Original Message ----
> From: Alex Hall <mehgcap at gmail.com>
> To: Alan Gauld <alan.gauld at btinternet.com>
> Sent: Wednesday, 15 September, 2010 15:57:43
> Subject: Re: [Tutor] list dll functions?
> 
> On 9/15/10, Alan Gauld <alan.gauld at btinternet.com>  wrote:
> >
> > "Alex Hall" <mehgcap at gmail.com>  wrote
> >
> >> Out of curiosity: I know I can call dll functions from  python using
> >> the win32 lib, but is there any way to simply "examine"  a loaded dll
> >> to see all of the functions and attributes it exposes  for use?
> >
> > There are various tools around to do that and hopefully  some
> > documentation!
> >
> > But often nowadays DLLs expose a COM  object model and
> > you have a COM browser built into Pythonwin. That will  give
> > you a windows explorer type view of the objects and their
> >  operations.
> How would you go about doing that? I have the pywin  extension
> installed for my python installation.
> >
> > If the DLL is  purely perocedural then that won't help.
> >
> >  HTH,
> >
> >
> > --
> > Alan Gauld
> > Author of the Learn  to Program web site
> > http://www.alan-g.me.uk/
> >
> >
> >  _______________________________________________
> > Tutor maillist   -  Tutor at 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)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> 

From ps_python at yahoo.com  Wed Sep 15 19:14:02 2010
From: ps_python at yahoo.com (kumar s)
Date: Wed, 15 Sep 2010 10:14:02 -0700 (PDT)
Subject: [Tutor] counting elements in list
Message-ID: <935218.23677.qm@web112511.mail.gq1.yahoo.com>

Hi group:

I have a list:

 k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'C', 'T', 
'T', 'T', 'C', 'C', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'T', 'T', 'T']

the allowed elements are A or T or G or C. List can have any number of A or T or 
G or C

My aim is to get a string ouput with counts of each type A or T or G or C.  

A:0\tT:23\tG:0\tC:6  

from the above example, I could count T and C and since there are no A and G, I 
want to print 0 for them. I just dont know how this can be done. 




>>> d = {}
>>> for i in set(k):
...     d[i] = k.count(i)
...
>>> d
{'C': 6, 'T': 23}


>>> for keys,values in d.items():
...     print keys+'\t'+str(d[keys])
...
C       6
T       23

the other way i tried is:
>>> k.count('A'),k.count('T'),k.count('G'),k.count('C')
(0, 23, 0, 6)


 how can I get counts for those elements not represented in list and print 
them.  appreciate your help. 


thanks
kumar



      


From anand.shashwat at gmail.com  Wed Sep 15 19:23:01 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Wed, 15 Sep 2010 13:23:01 -0400
Subject: [Tutor] counting elements in list
In-Reply-To: <935218.23677.qm@web112511.mail.gq1.yahoo.com>
References: <935218.23677.qm@web112511.mail.gq1.yahoo.com>
Message-ID: <AANLkTinbY+oScgid=6JfsXA5Z6CeX6ON3HfDhB-rOed4@mail.gmail.com>

On Wed, Sep 15, 2010 at 1:14 PM, kumar s <ps_python at yahoo.com> wrote:

> Hi group:
>
> I have a list:
>
>  k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'C',
> 'T',
> 'T', 'T', 'C', 'C', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'T', 'T', 'T']
>
> the allowed elements are A or T or G or C. List can have any number of A or
> T or
> G or C
>
> My aim is to get a string ouput with counts of each type A or T or G or C.
>
> A:0\tT:23\tG:0\tC:6
>
> from the above example, I could count T and C and since there are no A and
> G, I
> want to print 0 for them. I just dont know how this can be done.
>

>>> k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T', 'T',
'C', 'T', 'T', 'T', 'C', 'C', 'T', 'T','T', 'C', 'T', 'T', 'T', 'T', 'T',
'T']
>>> "\t".join(x+":"+str(k.count(x)) for x in 'ATGC')
'A:0\tT:23\tG:0\tC:6'



>
>
>
>
> >>> d = {}
> >>> for i in set(k):
> ...     d[i] = k.count(i)
> ...
> >>> d
> {'C': 6, 'T': 23}
>
>
> >>> for keys,values in d.items():
> ...     print keys+'\t'+str(d[keys])
> ...
> C       6
> T       23
>
> the other way i tried is:
> >>> k.count('A'),k.count('T'),k.count('G'),k.count('C')
> (0, 23, 0, 6)
>
>
>  how can I get counts for those elements not represented in list and print
> them.  appreciate your help.
>



>
>
> thanks
> kumar
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/bafe3a35/attachment-0001.html>

From grigor.kolev at gmail.com  Wed Sep 15 20:31:45 2010
From: grigor.kolev at gmail.com (=?UTF-8?Q?=D0=93=D1=80=D0=B8=D0=B3=D0=BE=D1=80_=D0=9A=D0=BE=D0=BB?= =?UTF-8?Q?=D0=B5=D0=B2?=)
Date: Wed, 15 Sep 2010 21:31:45 +0300
Subject: [Tutor] First complexity program
Message-ID: <1284575505.2199.33.camel@dedal>

Hi.
I try to make a program to connect my POS system with Geovision video
server. I can connect directly with serial port but on the POS no have
free serial. 
My POS can send information like file on video server. 
I can read this file with Python.

It is first problem:
My script can looking the directory every 10 second and if have new file
can opens it but I think have better way to making it.
 
Next problem is:
If I send the data must open port but port is already open by Geovision.
And second I must take data like input not like output.

Every idea is welcome.
Give me only guidelines.
Who modules i can use and where can read some information. 
-- 
?????? ????? <grigor.kolev at gmail.com>


From voice at root.ua  Wed Sep 15 20:44:51 2010
From: voice at root.ua (Viacheslav Chumushuk)
Date: Wed, 15 Sep 2010 21:44:51 +0300
Subject: [Tutor] First complexity program
In-Reply-To: <1284575505.2199.33.camel@dedal>
References: <1284575505.2199.33.camel@dedal>
Message-ID: <20100915184451.GA1588@laptop>

On Wed, Sep 15, 2010 at 09:31:45PM +0300, ?????? ????? <grigor.kolev at gmail.com> wrote:
> Hi.

Hi, Grigoriy.

> I try to make a program to connect my POS system with Geovision video
> server. I can connect directly with serial port but on the POS no have
> free serial. 
> My POS can send information like file on video server. 
> I can read this file with Python.
> 
> It is first problem:
> My script can looking the directory every 10 second and if have new file
> can opens it but I think have better way to making it.

For monitoring FS try to use pynotify library (http://pyinotify.sourceforge.net/).

-- 
Please, use plain text message format contacting me, and
don't use proprietary formats for attachments (such as DOC, XLS)
use PDF, TXT, ODT, HTML instead. Thanks.

From steve at pearwood.info  Wed Sep 15 22:36:51 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 16 Sep 2010 06:36:51 +1000
Subject: [Tutor] counting elements in list
In-Reply-To: <AANLkTinbY+oScgid=6JfsXA5Z6CeX6ON3HfDhB-rOed4@mail.gmail.com>
References: <935218.23677.qm@web112511.mail.gq1.yahoo.com>
	<AANLkTinbY+oScgid=6JfsXA5Z6CeX6ON3HfDhB-rOed4@mail.gmail.com>
Message-ID: <201009160636.52219.steve@pearwood.info>

On Thu, 16 Sep 2010 03:23:01 am Shashwat Anand wrote:
> On Wed, Sep 15, 2010 at 1:14 PM, kumar s <ps_python at yahoo.com> wrote:
> > Hi group:
> >
> > I have a list:
> >
> >  k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T',
> > 'T', 'C', 'T',
> > 'T', 'T', 'C', 'C', 'T', 'T', 'T', 'C', 'T', 'T', 'T', 'T', 'T',
> > 'T']
> >
> > the allowed elements are A or T or G or C. List can have any number
> > of A or T or
> > G or C
> >
> > My aim is to get a string ouput with counts of each type A or T or
> > G or C.
> >
> > A:0\tT:23\tG:0\tC:6
> >
> > from the above example, I could count T and C and since there are
> > no A and G, I
> > want to print 0 for them. I just dont know how this can be done.
> >
> >>> k = ['T', 'C', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'C', 'T', 'T',
> >>> 'T',
>
> 'C', 'T', 'T', 'T', 'C', 'C', 'T', 'T','T', 'C', 'T', 'T', 'T', 'T',
> 'T', 'T']
>
> >>> "\t".join(x+":"+str(k.count(x)) for x in 'ATGC')
> 'A:0\tT:23\tG:0\tC:6'

Given the extremely low-level of knowledge which the Original Poster's 
question reveals, I think a one-liner like that will probably look 
completely cryptic and mysterious.

I suggest a simple modification of the OP's code:

d = {}
for i in set(k):
    d[i] = k.count(i)

for key in 'ATGC':
    print key + '\t' + str(d.get(key, 0))



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Wed Sep 15 23:37:33 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 15 Sep 2010 22:37:33 +0100
Subject: [Tutor] intercepting and recored I/O function calls
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
Message-ID: <i6reb1$h7l$1@dough.gmane.org>


"Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote

> I would like to intercept and record I/O function calls to a file.. 
> (later
> to a database) with probably the names of the files that have been 
> created,
> accessed / deleted in my program. I  have not done something like 
> this
> before.. Some Guidance is highly appreciated

Are you talking about I/O calls in your own app? If so thats fairly
straightforward to do. OTOH If you are talking about capturing all
I/O calls that's a lot harder.... and if it's a multi-user OS will 
need
administrator privileges.

But this is extremely dependant on the Operating System - you will 
basically
have to intercept the system calls. So, which OS are you using?
And how familiar are you with its API?

Al;so, While you can probably do this in Python but its likely to have
a serious impact on the OS performance, it will slow down the 
performamce
quite noticeably. I'd normally recommend using C for something like 
this.

HTH,

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



From rdmoores at gmail.com  Thu Sep 16 05:25:31 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 15 Sep 2010 20:25:31 -0700
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to run
	at command line?
Message-ID: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>

64-bit Vista.

I have no problem running 3.1 scripts at the command line. However 2.6
scripts seems to require 2.x. For example, I get this error showing that the
old 2.x print won't do:

C:\P26Working\Finished>solveCubicEquation.py
  File "C:\P26Working\Finished\solveCubicEquation.py", line 19
   print "a is", a
               ^
SyntaxError: invalid syntax

Dick Moores
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/abdfb9ab/attachment.html>

From smokefloat at gmail.com  Thu Sep 16 05:35:17 2010
From: smokefloat at gmail.com (David Hutto)
Date: Wed, 15 Sep 2010 23:35:17 -0400
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
Message-ID: <AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>

print("a is", a)
or
from future import *

From wallenpb at gmail.com  Thu Sep 16 06:02:12 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Wed, 15 Sep 2010 23:02:12 -0500
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>
Message-ID: <AANLkTimwWpsh=HOSYMzN+GfYtduMHc71kr3kgSe_yz0p@mail.gmail.com>

On Wed, Sep 15, 2010 at 10:35 PM, David Hutto <smokefloat at gmail.com> wrote:

> print("a is", a)
> or
> from future import *
> _______________________________________________
>

Other than the Python 3 style print function, what else is contained in the
future module?

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/7125ae4b/attachment-0001.html>

From smokefloat at gmail.com  Thu Sep 16 06:04:49 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 16 Sep 2010 00:04:49 -0400
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTimwWpsh=HOSYMzN+GfYtduMHc71kr3kgSe_yz0p@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>
	<AANLkTimwWpsh=HOSYMzN+GfYtduMHc71kr3kgSe_yz0p@mail.gmail.com>
Message-ID: <AANLkTimdsU9TKJSaZXy_0OAbxr3KzZQZ+9--CLTe7GxP@mail.gmail.com>

On Thu, Sep 16, 2010 at 12:02 AM, Bill Allen <wallenpb at gmail.com> wrote:
>
>
> On Wed, Sep 15, 2010 at 10:35 PM, David Hutto <smokefloat at gmail.com> wrote:
>>
>> print("a is", a)
>> or
>> from future import *
>> _______________________________________________
>
> Other than the Python 3 style print function, what else is contained in the
> future module?

>>> import __future__
>>> help(__future__)

>
> --Bill
>

From ranceh at gmail.com  Thu Sep 16 06:05:52 2010
From: ranceh at gmail.com (Rance Hall)
Date: Wed, 15 Sep 2010 23:05:52 -0500
Subject: [Tutor] working with empty lists
Message-ID: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>

Im working on a little piece of test code to test an idea for a larger script.

Here is what I've got so far:

l = []

for i in range(0,10)
    l.append(i)

for i in range(0,10)
    print('%s. %s' % (i, l[i])


This gives me:

0. 0
1. 1
2. 2 .... etc

which is what I expect, but what I want is to get something like

0. 1
1. 2
2. 3 .....

so that the output is clearly different on either side of the "."

I tried changing the append to l.append(i+1)

which almost worked but the output started with 1. 2  I was curious
what happend to the 0. 1 line

I know this means that I'm not understanding exactly what append actually does.

I know that my ide shows that the list as other functions like insert, etc.

Can someone explain to me whats the best way to add a value to a list
that is not long enough to accept it, without playing with the
indexes, it appears I currently am playing with them.

I know generally that we aren't supposed to care about the indexes but
this is eventually going to be part of a menuing system that displays
the index, so I do have a legit need to care about what is happening
to the list index.

From rdmoores at gmail.com  Thu Sep 16 06:11:02 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 15 Sep 2010 21:11:02 -0700
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
Message-ID: <AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>

On Wed, Sep 15, 2010 at 20:25, Richard D. Moores <rdmoores at gmail.com> wrote:

> 64-bit Vista.
>
> I have no problem running 3.1 scripts at the command line. However 2.6
> scripts seems to require 2.x. For example, I get this error showing that the
> old 2.x print won't do:
>
> C:\P26Working\Finished>solveCubicEquation.py
>   File "C:\P26Working\Finished\solveCubicEquation.py", line 19
>    print "a is", a
>                ^
> SyntaxError: invalid syntax
>
> Dick Moores
>

Seems I was misunderstood.

Some of the scripts written for 2.6 use libraries not yet available for 3.x.
So I want to know not how to modify them, but how to run them at the command
line.

Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100915/b15f58dc/attachment.html>

From bgailer at gmail.com  Thu Sep 16 06:33:02 2010
From: bgailer at gmail.com (bob gailer)
Date: Thu, 16 Sep 2010 00:33:02 -0400
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
Message-ID: <4C919DFE.6030908@gmail.com>

  On 9/16/2010 12:05 AM, Rance Hall wrote:
> Im working on a little piece of test code to test an idea for a larger script.
>
> Here is what I've got so far:
>
> l = []
>
> for i in range(0,10)
>      l.append(i)
>
> for i in range(0,10)
>      print('%s. %s' % (i, l[i])
>
>
> This gives me:
>
> 0. 0
> 1. 1
> 2. 2 .... etc
>
> which is what I expect, but what I want is to get something like
>
> 0. 1
> 1. 2
> 2. 3 .....
>
> so that the output is clearly different on either side of the "."
>
> I tried changing the append to l.append(i+1)
>
> which almost worked but the output started with 1. 2  I was curious
> what happend to the 0. 1 line

It works for me (after adding : at the end of the for statements, and a 
parenthesis at the end of the print call).

 >>> l = []
 >>> for i in range(0,10)
...    l.append(i+1)
...
 >>> for i in range(0,10)
...    print('%s. %s' % (i, l[i]))
...
0. 1
1. 2
2. 3
3. 4

etc.

[snip]

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From smokefloat at gmail.com  Thu Sep 16 07:02:38 2010
From: smokefloat at gmail.com (David Hutto)
Date: Thu, 16 Sep 2010 01:02:38 -0400
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>
Message-ID: <AANLkTinHN44syce4P1iGbgKBOjdNxzENoRJLt1twAEa+@mail.gmail.com>

On Thu, Sep 16, 2010 at 12:11 AM, Richard D. Moores <rdmoores at gmail.com> wrote:
>
>
> On Wed, Sep 15, 2010 at 20:25, Richard D. Moores <rdmoores at gmail.com> wrote:
>>
>> 64-bit Vista.
>>
>> I have no problem running 3.1 scripts at the command line. However 2.6
>> scripts seems to require 2.x. For example, I get this error showing that the
>> old 2.x print won't do:
>>
>> C:\P26Working\Finished>solveCubicEquation.py
>> ?File "C:\P26Working\Finished\solveCubicEquation.py", line 19
>> ? ?print "a is", a
>> ? ? ? ? ? ? ? ^
>> SyntaxError: invalid syntax
>>
>> Dick Moores
>
> Seems I was misunderstood.
>
> Some of the scripts written for 2.6 use libraries not yet available for 3.x.
> So I want to know not how to modify them, but how to run them at the command
> line.
>
> Dick
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

I'm not experienced enough to have utilized all features but it does
seem there would be a way to import and after a quick google search I
think this might be the answer:

http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP

>From my brief review of it, it should call from future automatically
in each interactive session

I'll probably look further because it interests me as well.

From c.t.matsumoto at gmail.com  Thu Sep 16 09:13:21 2010
From: c.t.matsumoto at gmail.com (C.T. Matsumoto)
Date: Thu, 16 Sep 2010 09:13:21 +0200
Subject: [Tutor] quick speed question
Message-ID: <4C91C391.4060603@gmail.com>

Hello Tutors,

I was just wondering if you have a dictionary key is it faster to do:

if dict['key'] == 'foo':
     ...

or is this faster:

if 'foo' in dict['key']:
     ...

Or is there any difference and I'm chasing ghosts?

Thanks,

T
-- 
C.T. Matsumoto
Claes de Vrieselaan 60a III
3021 JR Rotterdam
The Netherlands

tel.: +31 (0)6 41 45 08 54

From evert.rol at gmail.com  Thu Sep 16 09:16:41 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 16 Sep 2010 09:16:41 +0200
Subject: [Tutor] quick speed question
In-Reply-To: <4C91C391.4060603@gmail.com>
References: <4C91C391.4060603@gmail.com>
Message-ID: <DC6394E4-226D-4F00-888F-B198DA5932A7@gmail.com>

> Hello Tutors,
> 
> I was just wondering if you have a dictionary key is it faster to do:
> 
> if dict['key'] == 'foo':
>    ...
> 
> or is this faster:
> 
> if 'foo' in dict['key']:
>    ...
> 
> Or is there any difference and I'm chasing ghosts?

The latter: they are not the same:

>>> d = {'key': 'food'}
>>> d['key'] == 'foo'
False
>>> 'foo' in d['key']
True


Btw, generally don't use a reserved Python word for a variable, such as dict in this case (I know it's an example, but it's still unsafe practice).

Cheers,

  Evert

> 
> Thanks,
> 
> T
> -- 
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
> 
> tel.: +31 (0)6 41 45 08 54
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From timomlists at gmail.com  Thu Sep 16 09:18:58 2010
From: timomlists at gmail.com (Timo)
Date: Thu, 16 Sep 2010 09:18:58 +0200
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
Message-ID: <4C91C4E2.50106@gmail.com>

On 16-09-10 06:05, Rance Hall wrote:
> Im working on a little piece of test code to test an idea for a larger script.
>
> Here is what I've got so far:
>
> l = []
>
> for i in range(0,10)
>      l.append(i)
>
> for i in range(0,10)
>      print('%s. %s' % (i, l[i])
>
>
> This gives me:
>
> 0. 0
> 1. 1
> 2. 2 .... etc
>
> which is what I expect, but what I want is to get something like
>
> 0. 1
> 1. 2
> 2. 3 .....
>
> so that the output is clearly different on either side of the "."
>    
You could do this:
 >>> l = []
 >>> for i in range(1, 11):
...   l.append(i)
...
 >>> for index, i in enumerate(l):
...   print('%s. %s' %(index, i))
...
0. 1
1. 2
2. 3
3. 4
etc.

Cheers,
Timo

> I tried changing the append to l.append(i+1)
>
> which almost worked but the output started with 1. 2  I was curious
> what happend to the 0. 1 line
>
> I know this means that I'm not understanding exactly what append actually does.
>
> I know that my ide shows that the list as other functions like insert, etc.
>
> Can someone explain to me whats the best way to add a value to a list
> that is not long enough to accept it, without playing with the
> indexes, it appears I currently am playing with them.
>
> I know generally that we aren't supposed to care about the indexes but
> this is eventually going to be part of a menuing system that displays
> the index, so I do have a legit need to care about what is happening
> to the list index.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    


From alan.gauld at btinternet.com  Thu Sep 16 09:47:49 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 Sep 2010 08:47:49 +0100
Subject: [Tutor] working with empty lists
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
Message-ID: <i6si39$ckp$1@dough.gmane.org>


"Rance Hall" <ranceh at gmail.com> wrote

> Here is what I've got so far:
>
> l = []
> for i in range(0,10)
>    l.append(i)
>
> for i in range(0,10)
>    print('%s. %s' % (i, l[i])
>
> I tried changing the append to l.append(i+1)
>
> which almost worked but the output started with 1. 2  I was curious
> what happend to the 0. 1 line

You made a mistake somewhere, it works as you expected
if you only make that one change.

> I know generally that we aren't supposed to care about the indexes 
> but
> this is eventually going to be part of a menuing system that 
> displays
> the index, so I do have a legit need to care about what is happening
> to the list index.

That's probably a bad idea. It's confusing for users if the number of 
their
favourite command changes, as it would if you added a new command
into the list etc. (One of the big advantages of menu driven CLIs is 
that
users learn the sequences they use regularly and start to "type ahead"
which makes for a very efficient operation.) It's usually better to 
keep
the command number as part of the menu data and then sort the
command in order based on that.

Just a thought,


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



From jojo.mwebaze at gmail.com  Thu Sep 16 09:51:04 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Thu, 16 Sep 2010 09:51:04 +0200
Subject: [Tutor] intercepting and recored I/O function calls
In-Reply-To: <i6reb1$h7l$1@dough.gmane.org>
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
	<i6reb1$h7l$1@dough.gmane.org>
Message-ID: <AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>

On Wed, Sep 15, 2010 at 11:37 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> "Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote
>
>
>  I would like to intercept and record I/O function calls to a file.. (later
>> to a database) with probably the names of the files that have been
>> created,
>> accessed / deleted in my program. I  have not done something like this
>> before.. Some Guidance is highly appreciated
>>
>
> Are you talking about I/O calls in your own app? If so thats fairly
> straightforward to do. OTOH If you are talking about capturing all
> I/O calls that's a lot harder.... and if it's a multi-user OS will need
> administrator privileges.
>

I could begin with tracing I/O calls in my App.. if its sufficient enough i
may not need i/o calls for the OS.

>
> But this is extremely dependant on the Operating System - you will
> basically
> have to intercept the system calls. So, which OS are you using?
> And how familiar are you with its API?
>

I am using centos, however i don't even have admin privileges.   Which API
are you referring to?

 Al;so, While you can probably do this in Python but its likely to have
> a serious impact on the OS performance, it will slow down the performamce
> quite noticeably. I'd normally recommend using C for something like this.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/e9e3aace/attachment.html>

From alan.gauld at btinternet.com  Thu Sep 16 09:54:43 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 Sep 2010 08:54:43 +0100
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
	run at command line?
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>
Message-ID: <i6sig7$ebe$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

> Some of the scripts written for 2.6 use libraries not yet available 
> for 3.x.
> So I want to know not how to modify them, but how to run them at the 
> command
> line.

Install 2.x.
This is why we keep recommending that beginners stick with 2.x.
Its why the 2.x line has not died out and still gets new releases.

Eventually the library owners will port their code but until then
you need to use the version of python they are written for.
You cannot mix them reliably.


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



From alan.gauld at btinternet.com  Thu Sep 16 09:52:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 Sep 2010 08:52:24 +0100
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
	runat command line?
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
Message-ID: <i6sibs$dp7$1@dough.gmane.org>


"Richard D. Moores" <rdmoores at gmail.com> wrote

> I have no problem running 3.1 scripts at the command line. However 
> 2.6
> scripts seems to require 2.x. For example, I get this error showing 
> that the
> old 2.x print won't do:

Thats correct, there are several big changes between V2 and V3.
They are not compatible. You can do some things to make a script
compatible but in the general case you cannot run 2.x scripts in 3.x

If you have the latest 2.x release you can run some 3.x code in
them by importing from future but its not fullproof. Similarly there 
is
a convertion script from 2 to 3 but again its not follprooof, it just
handles the most common cases. See the documentation for v3
for more details.


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



From modulok at gmail.com  Thu Sep 16 10:40:59 2010
From: modulok at gmail.com (Modulok)
Date: Thu, 16 Sep 2010 02:40:59 -0600
Subject: [Tutor] quick speed question
In-Reply-To: <4C91C391.4060603@gmail.com>
References: <4C91C391.4060603@gmail.com>
Message-ID: <AANLkTi=gCtf0wv6gi1XVUQgJ88Ju23PmPYF5oEyUY80d@mail.gmail.com>

This is faster:

    if dict['key'] == 'foo':
        pass

...But just slightly. (About 9% faster on my machine. This may differ
depending on the implementation, but I doubt it. See the 'timeit'
module.) Whether it's a big deal depends on what you're doing.
Accessing the dict - a million times - with either method took less
than a second. Visually, this makes more sense to me:

    if dict['key'] == 'foo':
        pass

Regardless, you should be aware that while they look similar, they
differ in their semantics:

    # Something to work with:
    dic = {'a': "Big", 'b': "Bigger"}

    # This is true:
    if dic['a'] == "Big":
        print True

    # And this is true:
    if "Big" in dic['a']:
        print True

    # But this is also true!
    if "Big" in dic['b']:
        print True

As far as speed is concerned: Don't worry about it unless has already
become a problem. Premature optimization wastes time you should be
spending solving the actual problem. For example, if you wrote an MP3
player that sorted playlists in 0.00001 seconds instead of 0.00002
seconds (100% faster!), but you wasted 3 days doing it - you haven't
accomplished much.

When you're done and you find you need a faster solution, optimize
your algorithms. If that still isn't enough, ask somebody smarter than
yourself to look at it. (This list is great for that!) If that too
fails, start think about writing a few critical bits in C, but only as
a last resort.

"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil" -Donald knuth-

-Modulok-

On 9/16/10, C.T. Matsumoto <c.t.matsumoto at gmail.com> wrote:
> Hello Tutors,
>
> I was just wondering if you have a dictionary key is it faster to do:
>
> if dict['key'] == 'foo':
>      ...
>
> or is this faster:
>
> if 'foo' in dict['key']:
>      ...
>
> Or is there any difference and I'm chasing ghosts?
>
> Thanks,
>
> T
> --
> C.T. Matsumoto
> Claes de Vrieselaan 60a III
> 3021 JR Rotterdam
> The Netherlands
>
> tel.: +31 (0)6 41 45 08 54
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From davea at ieee.org  Thu Sep 16 10:46:59 2010
From: davea at ieee.org (Dave Angel)
Date: Thu, 16 Sep 2010 04:46:59 -0400
Subject: [Tutor] quick speed question
In-Reply-To: <4C91C391.4060603@gmail.com>
References: <4C91C391.4060603@gmail.com>
Message-ID: <4C91D983.6010208@ieee.org>



On 2:59 PM, C.T. Matsumoto wrote:
> Hello Tutors,
>
> I was just wondering if you have a dictionary key is it faster to do:
>
> if dict['key'] == 'foo':
>     ...
>
> or is this faster:
>
> if 'foo' in dict['key']:
>     ...
>
> Or is there any difference and I'm chasing ghosts?
>
> Thanks,
>
> T
dict is not a good name for a dictionary, since it's a built-in name.  
But ignoring that,

The two lines you show do different things

Both of them look up a single item in the dictionary, so that part takes 
the same time.  But then the first compares the resulting string to 
exactly 'foo', while the second searches in the string to see if 'foo' 
is a substring.

If you need one of them, the other will get the wrong answer.  So 
knowing that the first is faster is irrelevant.

DaveA


From rdmoores at gmail.com  Thu Sep 16 11:28:13 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 16 Sep 2010 02:28:13 -0700
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <i6sig7$ebe$1@dough.gmane.org>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>
	<i6sig7$ebe$1@dough.gmane.org>
Message-ID: <AANLkTika_F=Ts21CHB6NnJ5DzGwamJ0L7dTi=u5nYAtN@mail.gmail.com>

On Thu, Sep 16, 2010 at 00:54, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Richard D. Moores" <rdmoores at gmail.com> wrote
>
>> Some of the scripts written for 2.6 use libraries not yet available for 3.x.
>> So I want to know not how to modify them, but how to run them at the command
>> line.
>
> Install 2.x.
> This is why we keep recommending that beginners stick with 2.x.
> Its why the 2.x line has not died out and still gets new releases.
>
> Eventually the library owners will port their code but until then
> you need to use the version of python they are written for.
> You cannot mix them reliably.

I should have stated that I have 2.6, 2.7, and 3.1  installed. The
scripts are in 2 groups. One written in 2.6, the other in 3.1. Most
run fine in the appropriate version of IDLE, or in Wing when I change
between c:\Python31\pythonw31.exe and c:\Python26\python.exe .  But
some 2.6 scripts must be run at the command line. All the 3.1 scripts
do, but not the 2.6's.

So my problem and question is how to set up a command line that will
run not just the 2.6 scripts that must be run there, but all of them.

And you know what? In thinking through again what my problem was, I
got the idea to try this, and it worked:

==================================================
C:\P26Working\Finished>c:\Python26\python.exe solveCubicEquation.py
Enter real coefficients a,b,c: 3,2,1
a is 3.0
b is 2.0
c is 1.0
equation is (x**3) + (3.000000*x**2) + (2.000000*x) + (1.000000) = 0

roots: [(-2.3247179572447463+0j),
(-0.33764102137762697+0.56227951206230142j),
(-0.33764102137762697-0.56227951206230142j)]

    After ignoring very small root.real and root.imag,
    and rounding to 4 significant figures:

root1 is -2.325
root2 is -0.3376+0.5623j
root3 is -0.3376-0.5623j

Press Enter to solve another; n to close:
==============================================

So thanks to all for trying to help. Without your tries I wouldn't
have figured it out!

Dick

From rdmoores at gmail.com  Thu Sep 16 12:18:25 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 16 Sep 2010 03:18:25 -0700
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
 run at command line?
In-Reply-To: <AANLkTika_F=Ts21CHB6NnJ5DzGwamJ0L7dTi=u5nYAtN@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimEx2wybLjmrOHXbkRk6sS4vWHtVRQRewEiK9SN@mail.gmail.com>
	<i6sig7$ebe$1@dough.gmane.org>
	<AANLkTika_F=Ts21CHB6NnJ5DzGwamJ0L7dTi=u5nYAtN@mail.gmail.com>
Message-ID: <AANLkTinuzi_Wq-EgDeVkBYTdt6syauS+NrEkGgMmU_zY@mail.gmail.com>

I forgot to mention that I didn't write that solveCubicEquation.py
script. I paid a pittance to mathtalk-ga at the old Google Answers to
not only write it, but to explain it. I recommend these 2 pages to
those with a mathematical bent:

<http://answers.google.com/answers/threadview?id=433886>
<http://answers.google.com/answers/threadview?id=441538>

And here's "my" solveCubicEquation.py script:
<http://tutoree7.pastebin.com/7v934g6r>


On Thu, Sep 16, 2010 at 02:28, Richard D. Moores <rdmoores at gmail.com> wrote:
> On Thu, Sep 16, 2010 at 00:54, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>
>> "Richard D. Moores" <rdmoores at gmail.com> wrote
>>
>>> Some of the scripts written for 2.6 use libraries not yet available for 3.x.
>>> So I want to know not how to modify them, but how to run them at the command
>>> line.
>>
>> Install 2.x.
>> This is why we keep recommending that beginners stick with 2.x.
>> Its why the 2.x line has not died out and still gets new releases.
>>
>> Eventually the library owners will port their code but until then
>> you need to use the version of python they are written for.
>> You cannot mix them reliably.
>
> I should have stated that I have 2.6, 2.7, and 3.1 ?installed. The
> scripts are in 2 groups. One written in 2.6 (or 2.5), the other in 3.1. Most
> run fine in the appropriate version of IDLE, or in Wing when I change
> between c:\Python31\pythonw31.exe and c:\Python26\python.exe . ?But
> some 2.6 scripts must be run at the command line. All the 3.1 scripts
> do, but not the 2.6's.
>
> So my problem and question is how to set up a command line that will
> run not just the 2.6 scripts that must be run there, but all of them.
>
> And you know what? In thinking through again what my problem was, I
> got the idea to try this, and it worked:
>
> ==================================================
> C:\P26Working\Finished>c:\Python26\python.exe solveCubicEquation.py
> Enter real coefficients a,b,c: 3,2,1
> a is 3.0
> b is 2.0
> c is 1.0
> equation is (x**3) + (3.000000*x**2) + (2.000000*x) + (1.000000) = 0
>
> roots: [(-2.3247179572447463+0j),
> (-0.33764102137762697+0.56227951206230142j),
> (-0.33764102137762697-0.56227951206230142j)]
>
> ? ?After ignoring very small root.real and root.imag,
> ? ?and rounding to 4 significant figures:
>
> root1 is -2.325
> root2 is -0.3376+0.5623j
> root3 is -0.3376-0.5623j
>
> Press Enter to solve another; n to close:
> ==============================================
>
> So thanks to all for trying to help. Without your tries I wouldn't
> have figured it out!
>
> Dick


I forgot to mention that I didn't write that solveCubicEquation.py
script. I paid a pittance to mathtalk-ga at the old Google Answers to
not only write it, but to explain it. I recommend these 2 pages to
those with a mathematical bent:

<http://answers.google.com/answers/threadview?id=433886>
<http://answers.google.com/answers/threadview?id=441538>

And here's "my" solveCubicEquation.py script:
<http://tutoree7.pastebin.com/7v934g6r>

Dick

From michael at trollope.org  Thu Sep 16 12:32:37 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 06:32:37 -0400
Subject: [Tutor] Regex comments
Message-ID: <20100916103237.GA2727@cecilia>

 Hello,

The re module includes the option to comment a regular expression with
the syntax (?#comment).  e.g.

p=r'(.*) (?P<grp>WT.dl)(?#parameter)=(?P<val>[^&]+)(?#value).*'

Is there a mechanism for extracting these values from the match, in
the way that group names are extracted?

I don't see one.

The point would be that in my processing of the match, I could
implement the comments as identifiers for the matched value.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"The most likely way for the world to be destroyed, most experts
agree, is by accident.  That's where we come in. We're computer
professionals. We cause accidents."  -- Nathaniel Borenstein, inventor
of MIME
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/d53fd614/attachment.pgp>

From __peter__ at web.de  Thu Sep 16 13:31:09 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 16 Sep 2010 13:31:09 +0200
Subject: [Tutor] Regex comments
References: <20100916103237.GA2727@cecilia>
Message-ID: <i6sv30$83h$1@dough.gmane.org>

Michael Powe wrote:

> The re module includes the option to comment a regular expression with
> the syntax (?#comment).  e.g.
> 
> p=r'(.*) (?P<grp>WT.dl)(?#parameter)=(?P<val>[^&]+)(?#value).*'
> 
> Is there a mechanism for extracting these values from the match, in
> the way that group names are extracted?
> 
> I don't see one.

You could write a regular expression to extract them ;)

> The point would be that in my processing of the match, I could
> implement the comments as identifiers for the matched value.

But that's what the names are for, e. g.:

>>> re.compile(r'(.*) (?P<parameter>WT.dl)=(?P<value>[^&]+).*').search(
" WTxdl=yadda&ignored").groupdict()
{'parameter': 'WTxdl', 'value': 'yadda'}

Or am I missing something?

Peter


From michael at trollope.org  Thu Sep 16 13:44:22 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 07:44:22 -0400
Subject: [Tutor] Regex comments
In-Reply-To: <i6sv30$83h$1@dough.gmane.org>
References: <20100916103237.GA2727@cecilia> <i6sv30$83h$1@dough.gmane.org>
Message-ID: <20100916114422.GB2727@cecilia>

On Thu, Sep 16, 2010 at 01:31:09PM +0200, Peter Otten wrote:
> Michael Powe wrote:
 
> > The re module includes the option to comment a regular expression with
> > the syntax (?#comment).  e.g.

> > Is there a mechanism for extracting these values from the match, in
> > the way that group names are extracted?

> > I don't see one.
 
> You could write a regular expression to extract them ;)

;-)
 
> > The point would be that in my processing of the match, I could
> > implement the comments as identifiers for the matched value.
> 
> But that's what the names are for, e. g.:
> 
> >>> re.compile(r'(.*) (?P<parameter>WT.dl)=(?P<value>[^&]+).*').search(
> " WTxdl=yadda&ignored").groupdict()
> {'parameter': 'WTxdl', 'value': 'yadda'}

That's right, I forgot about the dictionary.  Thanks!

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/037ea572/attachment.pgp>

From michael at trollope.org  Thu Sep 16 14:02:18 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 08:02:18 -0400
Subject: [Tutor] "Overloading" methods
Message-ID: <20100916120218.GC2727@cecilia>

Hello,

Strictly speaking, this isn't overloading a method in the way we do it
in Java.  But similar.  Maybe.

I am writing a module for processing web server log files and one of
the methods I provide is to extract a given query parameter and its
value. Because there are several types of log files with different
line structures, I had the thought to write methods with descriptive
names that simply returned a generic method that processed the method
arguments. e.g.,

def setpattern_iis(self,pattern,parameter) :
	type='iis'
	return pattern_generator(self,type,pattern,parameter)

In this case, creating a regular expression to parse the log lines for
a query parameter.

This is just a bit more "self documenting" than using the generic
method with the 'type' argument and requiring the user to enter the
type.  At the same time, it allows me to put all the parsing code in
one method.

My question is, is this a bad thing to do in python?

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
War is a sociological safety valve that cleverly diverts popular
hatred for the ruling classes into a happy occasion to mutilate or
kill foreign enemies. - Ernest Becker
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/614213f0/attachment.pgp>

From beachkidken at gmail.com  Thu Sep 16 14:18:45 2010
From: beachkidken at gmail.com (Ken Green)
Date: Thu, 16 Sep 2010 08:18:45 -0400
Subject: [Tutor] Function behavior
Message-ID: <4C920B25.8020405@gmail.com>

I am unclear on the behavior of using a function.  Below is a short code 
I wrote to print an amount out after inputting the number of match.

# TEST Function.py

def change(amount):
     if match == 1:
         amount = 0
     if match == 2:
         amount = 0
     if match == 3:
         amount = 3

match = raw_input("How many matches?: ")
change(match)
print amount

ERROR Message:

How many matches?: 2
Traceback (most recent call last):
   File "/home/ken/Python262/TEST Function.py", line 13, in <module>
     print amount
NameError: name 'amount' is not defined

How do I print out the amount of 0 if I input 2?

Should it be def change(match) instead of def change(amount)?

Perhaps, change(amount) instead of change(match)?

Perhaps, I need to add return somewhere?

Thanking you all in advance for your assistance.

Ken

From ranceh at gmail.com  Thu Sep 16 14:46:44 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 16 Sep 2010 07:46:44 -0500
Subject: [Tutor] working with empty lists
In-Reply-To: <4C919DFE.6030908@gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
	<4C919DFE.6030908@gmail.com>
Message-ID: <AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>

On Wed, Sep 15, 2010 at 11:33 PM, bob gailer <bgailer at gmail.com> wrote:
> ?On 9/16/2010 12:05 AM, Rance Hall wrote:
>>
<snip>

Thanks guys for replying, looks like I do have a bug in my code, but
its not where I thought it was.  Must have been up too late last
night.

The code I provided in my OP does work (with typos corrected) but this
code with one layer of complexity does not.

def paginate_stuff(list,start):
    pagesize = 2
    for i in list[start:start+pagesize]:
        print('%s. %s' % (i,list[i]))
    return

l = []
for i in range(0,10):
    l.append(i+1)

paginate_stuff(l,0)



Idea here is to be able to take N things Y at a time sequentially from
anywhere in the middle of the list.

every time I run this code I start the output one list item in the
sequence ahead of where I want to.

I can change the functional call to paginate_stuff(l,3)

and it will start where the above one leaves off

But I keep losing list[0]

Im reasonably sure that it has something to do with my for loop, but I
don't understand how

From voice at root.ua  Thu Sep 16 14:58:39 2010
From: voice at root.ua (Viacheslav Chumushuk)
Date: Thu, 16 Sep 2010 15:58:39 +0300
Subject: [Tutor] Function behavior
In-Reply-To: <4C920B25.8020405@gmail.com>
References: <4C920B25.8020405@gmail.com>
Message-ID: <20100916125839.GA21933@laptop>

On Thu, Sep 16, 2010 at 08:18:45AM -0400, Ken Green <beachkidken at gmail.com> wrote:
> I am unclear on the behavior of using a function.  Below is a short
> code I wrote to print an amount out after inputting the number of
> match.
> 
> # TEST Function.py
> 
> def change(amount):
>     if match == 1:
>         amount = 0
>     if match == 2:
>         amount = 0
>     if match == 3:
>         amount = 3
> 
> match = raw_input("How many matches?: ")
> change(match)
> print amount
> 
> ERROR Message:
> 
> How many matches?: 2
> Traceback (most recent call last):
>   File "/home/ken/Python262/TEST Function.py", line 13, in <module>
>     print amount
> NameError: name 'amount' is not defined
> 
> How do I print out the amount of 0 if I input 2?
> 
> Should it be def change(match) instead of def change(amount)?
> 
> Perhaps, change(amount) instead of change(match)?
> 
> Perhaps, I need to add return somewhere?
> 
> Thanking you all in advance for your assistance.
> 
> Ken
If you want to get value from a function you whould return it, from that
function. So, you should use something like next code:

def change(amount):
     amount = -1 #

     if match == 1:
         amount = 0
     if match == 2:
         amount = 0
     if match == 3:
         amount = 3
     
     return amount
 
match = raw_input("How many matches?: ")
amount = change(match)
print amount

And please note next thing. amount variable inside function's body is not the same as amount outside.
You should read about variable scope (local/global variables).

-- 
Please, use plain text message format contacting me, and
don't use proprietary formats for attachments (such as DOC, XLS)
use PDF, TXT, ODT, HTML instead. Thanks.

From evert.rol at gmail.com  Thu Sep 16 14:58:32 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 16 Sep 2010 14:58:32 +0200
Subject: [Tutor] Function behavior
In-Reply-To: <4C920B25.8020405@gmail.com>
References: <4C920B25.8020405@gmail.com>
Message-ID: <FA1197DA-69C8-4A5F-956B-11848A010C5E@gmail.com>

> I am unclear on the behavior of using a function.  Below is a short code I wrote to print an amount out after inputting the number of match.
> 
> # TEST Function.py
> 
> def change(amount):
>    if match == 1:
>        amount = 0
>    if match == 2:
>        amount = 0
>    if match == 3:
>        amount = 3
> 
> match = raw_input("How many matches?: ")
> change(match)
> print amount
> 
> ERROR Message:
> 
> How many matches?: 2
> Traceback (most recent call last):
>  File "/home/ken/Python262/TEST Function.py", line 13, in <module>
>    print amount
> NameError: name 'amount' is not defined

Variables are only local to the their direct surroundings: in this case, amount is only local to the 'change' function, not outside it.

You might want to read through http://docs.python.org/tutorial/controlflow.html#defining-functions first.


  Evert


> How do I print out the amount of 0 if I input 2?
> 
> Should it be def change(match) instead of def change(amount)?
> 
> Perhaps, change(amount) instead of change(match)?
> 
> Perhaps, I need to add return somewhere?
> 
> Thanking you all in advance for your assistance.
> 
> Ken
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From vince at vinces.ca  Thu Sep 16 16:22:56 2010
From: vince at vinces.ca (Vince Spicer)
Date: Thu, 16 Sep 2010 08:22:56 -0600
Subject: [Tutor] "Overloading" methods
In-Reply-To: <20100916120218.GC2727@cecilia>
References: <20100916120218.GC2727@cecilia>
Message-ID: <AANLkTimPA+TA3i2Yf05hqaksXpDEKSxP4g6uye+jHGbH@mail.gmail.com>

On Thu, Sep 16, 2010 at 6:02 AM, Michael Powe <michael at trollope.org> wrote:

> Hello,
>
> Strictly speaking, this isn't overloading a method in the way we do it
> in Java.  But similar.  Maybe.
>
> I am writing a module for processing web server log files and one of
> the methods I provide is to extract a given query parameter and its
> value. Because there are several types of log files with different
> line structures, I had the thought to write methods with descriptive
> names that simply returned a generic method that processed the method
> arguments. e.g.,
>
> def setpattern_iis(self,pattern,parameter) :
>        type='iis'
>        return pattern_generator(self,type,pattern,parameter)
>
> In this case, creating a regular expression to parse the log lines for
> a query parameter.
>
> This is just a bit more "self documenting" than using the generic
> method with the 'type' argument and requiring the user to enter the
> type.  At the same time, it allows me to put all the parsing code in
> one method.
>
> My question is, is this a bad thing to do in python?
>
> Thanks.
>
> mp
>
> --
> Michael Powe            michael at trollope.org            Naugatuck CT USA
> War is a sociological safety valve that cleverly diverts popular
> hatred for the ruling classes into a happy occasion to mutilate or
> kill foreign enemies. - Ernest Becker
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Well I can't comment on right or wrong I would think creating a simple class
with a __call__ method is a
little more pythonic.

Example:

class PatternGenerator(object):
    """Run a regex....."""
    def __init__(self, type_):
        self.type = type_
    def __call__(self, pattern, parameter):
        return pattern_generator(self, self.type, pattern, parameter)

# Initialize class
setpattern_iis = PatternGenerator('iis')

# call the method here
setpattern_iis("pattern", "params")

Hope that helps,

Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/007f6875/attachment.html>

From joel.goldstick at gmail.com  Thu Sep 16 16:24:03 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 16 Sep 2010 10:24:03 -0400
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
	<4C919DFE.6030908@gmail.com>
	<AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>
Message-ID: <AANLkTinW6rEOuNznRoHENFCKbeoNUYrV_a9eGAVri83h@mail.gmail.com>

I typed in this:


  3 l = []
  4
  5 for i in range(0,10):
  6     l.append(i+1)
  7
  8 for i in range(0,10):
  9     print ('%s. %s' % (i, l[i]))
 10
 11 def paginate_stuff(list, start):
 12     pagesize = 2
 13     for i in list[start:start+pagesize]:
 14         print ('%s. %s' % (i,list[i]))
 15     return
 16
 17 paginate_stuff(l,0)

and i get this:
0. 1
1. 2
2. 3
3. 4
4. 5
5. 6
6. 7
7. 8
8. 9
9. 10
1. 2
2. 3


What are you expecting?


But I keep losing list[0]
>
> Im reasonably sure that it has something to do with my for loop, but I
> don't understand how
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>




-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/4505e2cb/attachment.html>

From eduardo.susan at gmail.com  Thu Sep 16 16:47:23 2010
From: eduardo.susan at gmail.com (Eduardo Vieira)
Date: Thu, 16 Sep 2010 08:47:23 -0600
Subject: [Tutor] quick speed question
In-Reply-To: <DC6394E4-226D-4F00-888F-B198DA5932A7@gmail.com>
References: <4C91C391.4060603@gmail.com>
	<DC6394E4-226D-4F00-888F-B198DA5932A7@gmail.com>
Message-ID: <AANLkTimBNAy+3977tcgt75tiNR62-XBVraHrP_5F7X8s@mail.gmail.com>

On Thu, Sep 16, 2010 at 1:16 AM, Evert Rol <evert.rol at gmail.com> wrote:

> The latter: they are not the same:
>
>>>> d = {'key': 'food'}
>>>> d['key'] == 'foo'
> False
>>>> 'foo' in d['key']
> True
>
>
> Btw, generally don't use a reserved Python word for a variable, such as dict in this case (I know it's an example, but it's still unsafe practice).
>
If you want to find out if 'foo' is a key, you can do: 'foo' in d,
which will return False. I'm not sure, but if I recall this can even
be faster than using the if.

Regards,
Eduardo

From rwobben at hotmail.com  Thu Sep 16 17:16:11 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 16 Sep 2010 15:16:11 +0000
Subject: [Tutor] robots question
Message-ID: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>


Hello, 

As a exercise from this book ( Thinking like a computer scientist ) I have to make this programm on this page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
Exercise 11 

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
    # x = random.randint(0, GRID_WIDTH)
    # y = random.randint(0, GRID_HEIGHT)
    x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
    return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
    x = random.randint(0, GRID_WIDTH)
    y = random.randint(0, GRID_HEIGHT)
    return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
    robots = []
    # for i in range(numbots):
    #    x = random.randint(0, GRID_WIDTH)
    #    y = random.randint(0, GRID_HEIGHT)
    #    robots.append(place_robot(x, y))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = False))
    return robots

def move_player(player):
    update_when('key_pressed')
    if key_pressed('escape'):
        return True
    elif key_pressed('4'):
        if player['x'] > 0: player['x'] -= 1
    elif key_pressed('7'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('8'):
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('9'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('6'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
    elif key_pressed('3'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('2'):
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('1'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('0'):
       player['x'] = random.randint(0, GRID_WIDTH)
       player['y'] = random.randint(0, GRID_HEIGHT)
    else:
        return False

    move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

    return False

def collided(thing1, thing2):
    return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
    # check whether player has collided with anything
    for thing in robots + junk:
        if collided(thing, player):
            return True
    return False



def move_robot(robot, player):
    if robot['x'] < player['x']: robot['x'] += 1
    elif robot['x'] > player['x']: robot['x'] -= 1

    if robot['y'] < player['y']: robot['y'] += 1
    elif robot['y'] > player['y']: robot['y'] -= 1

    move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
    for robot in robots:
        move_robot(robot, player)


def play_game(robots):
    begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    player = place_player()
    robot = place_robots(4)
    junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
    defeated = False

    while not defeated:
        quit =  move_player(player)
        if quit:
            break
        move_robots(robot, player)
        defeated = check_collisions(robot, player, junk)

    if defeated:
        remove_from_screen(player['shape'])
        for thing in robots + junk:
            remove_from_screen(thing['shape'])
        Text("They got you!", (240, 240), size=32)
        sleep(3)

    end_graphics()



if __name__ == '__main__':
    play_game(2)

But now Im getting this error message :

Traceback (most recent call last):
  File "/root/workspace/test2/src/test.py", line 120, in <module>
    play_game(2)
  File "/root/workspace/test2/src/test.py", line 106, in play_game
    defeated = check_collisions(robot, player, junk)
  File "/root/workspace/test2/src/test.py", line 73, in check_collisions
    for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

I understand that robots is a dict and junk is a list.

Is that right ?

And why does the book say that when this message is appearing. 

Roelof


 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/0e5feb38/attachment-0001.html>

From ranceh at gmail.com  Thu Sep 16 17:46:43 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 16 Sep 2010 10:46:43 -0500
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTinW6rEOuNznRoHENFCKbeoNUYrV_a9eGAVri83h@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
	<4C919DFE.6030908@gmail.com>
	<AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>
	<AANLkTinW6rEOuNznRoHENFCKbeoNUYrV_a9eGAVri83h@mail.gmail.com>
Message-ID: <AANLkTimMKVS8y0b1chpL26HcLLeRmY=UwOj4oiHfKjs4@mail.gmail.com>

On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:
> I typed in this:
>
>
> ? 3 l = []
> ? 4
> ? 5 for i in range(0,10):
> ? 6???? l.append(i+1)
> ? 7
> ? 8 for i in range(0,10):
> ? 9???? print ('%s. %s' % (i, l[i]))
> ?10
> ?11 def paginate_stuff(list, start):
> ?12???? pagesize = 2
> ?13???? for i in list[start:start+pagesize]:
> ?14???????? print ('%s. %s' % (i,list[i]))
> ?15???? return
> ?16
> ?17 paginate_stuff(l,0)
>
> and i get this:
> 0. 1
> 1. 2
> 2. 3
> 3. 4
> 4. 5
> 5. 6
> 6. 7
> 7. 8
> 8. 9
> 9. 10
> 1. 2
> 2. 3
>
>
> What are you expecting?
>
>

you are getting what I am getting, so good news there, its not my code
(its my understanding instead)

In the above output where the you go from 9. 10 and the next item is 1. 2

I'm expecting the next item to be 0. 1 again.

It appears as if the for loop iterator is iterating BEFORE it executes
stuff as opposed to after like I'm used to.

if I change the print line inside the for loop to:

print('%s. %s) % (i-1,list[i-1]))

I get what I think I should have gotten orginally

Is this the correct understanding, is the for loop iterator iterating
before any of the stuff executes the first time?  This seems odd to me
somehow.

I appear to have fixed it, now I just wish I understood it.

R

From evert.rol at gmail.com  Thu Sep 16 17:57:48 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 16 Sep 2010 17:57:48 +0200
Subject: [Tutor] robots question
In-Reply-To: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
Message-ID: <7D35B5E3-0EF8-4493-9B46-E3CABF30CE18@gmail.com>

> As a exercise from this book ( Thinking like a computer scientist ) I have to make this programm on this page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> Exercise 11 
> 
> #
> # robots.py
> #
> from gasp import *

Argh!
Is that really in the book? 
Bad book, bad.

You can just "import gasp" and type "gasp.<function>" a few times.

<snip>Lot of code</snip>


> def play_game(robots):
>     begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
>     player = place_player()
>     robot = place_robots(4)
>     junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
>     defeated = False
> 
>     while not defeated:
>         quit =  move_player(player)
>         if quit:
>             break
>         move_robots(robot, player)
>         defeated = check_collisions(robot, player, junk)
> 
>     if defeated:
>         remove_from_screen(player['shape'])
>         for thing in robots + junk:
>             remove_from_screen(thing['shape'])
>         Text("They got you!", (240, 240), size=32)
>         sleep(3)
> 
>     end_graphics()
> 
> 
> 
> if __name__ == '__main__':
>     play_game(2)
> 
> But now Im getting this error message :
> 
> Traceback (most recent call last):
>   File "/root/workspace/test2/src/test.py", line 120, in <module>
>     play_game(2)
>   File "/root/workspace/test2/src/test.py", line 106, in play_game
>     defeated = check_collisions(robot, player, junk)
>   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
>     for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> I understand that robots is a dict and junk is a list.
> 
> Is that right ?

I think robots is not even a dict, but I may be wrong here.
Check your variable *names* inside play_game, and your use of '2' and '4'. Aren't you mixing up 'robot' and 'robots'?
Have you tried putting print statements inside the code? Also 'print type(<varname>)' can be variable.
Try more debugging when you get an exception.


> And why does the book say that when this message is appearing. 

A quick glance at those webpages doesn't show any place where the book gives this code. This seems to be code you added.


  Evert


From __peter__ at web.de  Thu Sep 16 18:10:13 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 16 Sep 2010 18:10:13 +0200
Subject: [Tutor] robots question
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
Message-ID: <i6tfe6$r6d$1@dough.gmane.org>

Roelof Wobben wrote:

> As a exercise from this book ( Thinking like a computer scientist ) I have
> to make this programm on this
> page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> Exercise 11

> def check_collisions(robots, junk, player):

>         defeated = check_collisions(robot, player, junk)

Just look at the argument names: check_collisions() is probably expecting a 
/list/ of robots where you are passing it a single one.

> But now Im getting this error message :
> 
> Traceback (most recent call last):
>   File "/root/workspace/test2/src/test.py", line 120, in <module>
>     play_game(2)
>   File "/root/workspace/test2/src/test.py", line 106, in play_game
>     defeated = check_collisions(robot, player, junk)
>   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
>     for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> I understand that robots is a dict and junk is a list.
> 
> Is that right ?

Yes. You are getting a dict because a single robot's state is stored in a 
dictionary.

> And why does the book say that when this message is appearing.

The way the program is presented makes it hard to tell at what point your 
and Eckel's idea of the script start to differ without going through the 
entire chapter.

Aside: that's why real projects use version control systems. When a program 
stops working after a change there is always the option to go back to the 
state of the program before the bug was introduced.

Peter


From joel.goldstick at gmail.com  Thu Sep 16 18:21:23 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 16 Sep 2010 12:21:23 -0400
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTimMKVS8y0b1chpL26HcLLeRmY=UwOj4oiHfKjs4@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
	<4C919DFE.6030908@gmail.com>
	<AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>
	<AANLkTinW6rEOuNznRoHENFCKbeoNUYrV_a9eGAVri83h@mail.gmail.com>
	<AANLkTimMKVS8y0b1chpL26HcLLeRmY=UwOj4oiHfKjs4@mail.gmail.com>
Message-ID: <AANLkTint5pKF=8q00RXG_Y=cjzYeZgimh2kGm=vY3OMg@mail.gmail.com>

On Thu, Sep 16, 2010 at 11:46 AM, Rance Hall <ranceh at gmail.com> wrote:

> On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
> <joel.goldstick at gmail.com> wrote:
> > I typed in this:
> >
> >
> >   3 l = []
> >   4
> >   5 for i in range(0,10):
> >   6     l.append(i+1)
> >   7
> >   8 for i in range(0,10):
> >   9     print ('%s. %s' % (i, l[i]))
> >  10
> >  11 def paginate_stuff(list, start):
> >  12     pagesize = 2
> >  13     for i in list[start:start+pagesize]:
> >  14         print ('%s. %s' % (i,list[i]))
> >  15     return
> >  16
> >  17 paginate_stuff(l,0)
> >
> > and i get this:
> > 0. 1
> > 1. 2
> > 2. 3
> > 3. 4
> > 4. 5
> > 5. 6
> > 6. 7
> > 7. 8
> > 8. 9
> > 9. 10
> > 1. 2
> > 2. 3
> >
> >
> > What are you expecting?
> >
> >
>
> you are getting what I am getting, so good news there, its not my code
> (its my understanding instead)
>
> In the above output where the you go from 9. 10 and the next item is 1. 2
>
> I'm expecting the next item to be 0. 1 again.
>
> It appears as if the for loop iterator is iterating BEFORE it executes
> stuff as opposed to after like I'm used to.
>
> if I change the print line inside the for loop to:
>
> print('%s. %s) % (i-1,list[i-1]))
>
> I get what I think I should have gotten orginally
>
> Is this the correct understanding, is the for loop iterator iterating
> before any of the stuff executes the first time?  This seems odd to me
> somehow.
>
> I appear to have fixed it, now I just wish I understood it.
>
> R
>

This line is illustrative:

>  13     for i in list[start:start+pagesize]:

start is 0, pagesize is 2 so we get list[0:2] which means i gets the value
of what is in list[0], then next time list[1] then it stops

list[0] IS 1, list[1] is 2

so: >  14         print ('%s. %s' % (i,list[i]))

will print 1. list[1] which is 2

then print 2. list[2] which is 3

maybe what you want is this:
  for i, value enumerate(list[start:start+pagesize], start):
      print i, value


_______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/ad15db3f/attachment.html>

From ranceh at gmail.com  Thu Sep 16 18:34:27 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 16 Sep 2010 11:34:27 -0500
Subject: [Tutor] working with empty lists
In-Reply-To: <AANLkTint5pKF=8q00RXG_Y=cjzYeZgimh2kGm=vY3OMg@mail.gmail.com>
References: <AANLkTi=vJx6U=9-gKiaSDLKyhmN2aErn1YjEsZiNi=tz@mail.gmail.com>
	<4C919DFE.6030908@gmail.com>
	<AANLkTin4_oNxsSOryTS7QcThipoT_ES9cYAA_gMtYZkW@mail.gmail.com>
	<AANLkTinW6rEOuNznRoHENFCKbeoNUYrV_a9eGAVri83h@mail.gmail.com>
	<AANLkTimMKVS8y0b1chpL26HcLLeRmY=UwOj4oiHfKjs4@mail.gmail.com>
	<AANLkTint5pKF=8q00RXG_Y=cjzYeZgimh2kGm=vY3OMg@mail.gmail.com>
Message-ID: <AANLkTinLUsG8jY1bACVzqfzn3zT4H8=hFKaZbwchP2As@mail.gmail.com>

On Thu, Sep 16, 2010 at 11:21 AM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:
>
>
> On Thu, Sep 16, 2010 at 11:46 AM, Rance Hall <ranceh at gmail.com> wrote:
>>
>> On Thu, Sep 16, 2010 at 9:24 AM, Joel Goldstick
>> <joel.goldstick at gmail.com> wrote:

<snip>

> This line is illustrative:
>
>> ?13???? for i in list[start:start+pagesize]:
>
> start is 0, pagesize is 2 so we get list[0:2] which means i gets the value
> of what is in list[0], then next time list[1] then it stops
>
> list[0] IS 1, list[1] is 2
>
> so: > ?14???????? print ('%s. %s' % (i,list[i]))
>
> will print 1. list[1] which is 2
>
> then print 2. list[2] which is 3
>
> maybe what you want is this:
> ? for i, value enumerate(list[start:start+pagesize], start):
> ? ? ? print i, value
>

For some reason I wasn't seeing that I was iterating over the list
contents not the list indexes, and because in my sample data both were
numbers it worked but not how I wanted it too,

Damn that dyslexia, oh well.  Thanks for helping me through it.

By the way, this also works as I expect:

for i in range(start, start+pagesize):

also gives me what I want to see.

From rwobben at hotmail.com  Thu Sep 16 19:44:16 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 16 Sep 2010 17:44:16 +0000
Subject: [Tutor] FW:  robots question
In-Reply-To: <SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>,
	<i6tfe6$r6d$1@dough.gmane.org>,
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>
Message-ID: <SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>




From: rwobben at hotmail.com
To: __peter__ at web.de
Subject: RE: [Tutor] robots question
Date: Thu, 16 Sep 2010 17:43:41 +0000








Hello , 

I change everything to this :

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
    # x = random.randint(0, GRID_WIDTH)
    # y = random.randint(0, GRID_HEIGHT)
    x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
    return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
    x = random.randint(0, GRID_WIDTH)
    y = random.randint(0, GRID_HEIGHT)
    return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
    robots = []
    # for i in range(numbots):
    #    x = random.randint(0, GRID_WIDTH)
    #    y = random.randint(0, GRID_HEIGHT)
    #    robots.append(place_robot(x, y))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = False))
    print type(robots)
    return robots

def move_player(player):
    update_when('key_pressed')
    if key_pressed('escape'):
        return True
    elif key_pressed('4'):
        if player['x'] > 0: player['x'] -= 1
    elif key_pressed('7'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('8'):
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('9'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('6'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
    elif key_pressed('3'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('2'):
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('1'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('0'):
       player['x'] = random.randint(0, GRID_WIDTH)
       player['y'] = random.randint(0, GRID_HEIGHT)
    else:
        return False

    move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

    return False

def collided(thing1, thing2):
    return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
    # check whether player has collided with anything
    for thing in robots + junk:
        if collided(thing, player):
            return True
    return False



def move_robot(robot, player):
    if robot['x'] < player['x']: robot['x'] += 1
    elif robot['x'] > player['x']: robot['x'] -= 1

    if robot['y'] < player['y']: robot['y'] += 1
    elif robot['y'] > player['y']: robot['y'] -= 1

    move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
    for robot in robots:
        move_robot(robot, player)


def play_game():
    begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    player = place_player()
    robot = place_robots(4)
    junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
    robots = []
    defeated = False

    while not defeated:
        quit =  move_player(player)
        if quit:
            break
        move_robots(robots, player)
        print "type robots", type(robots)
        print "type junk", type(junk)
        print "type player", type(player)
        defeated = check_collisions(robots, player, junk)

    if defeated:
        remove_from_screen(player['shape'])
        for thing in robots + junk:
            remove_from_screen(thing['shape'])
        Text("They got you!", (240, 240), size=32)
        sleep(3)

    end_graphics()



if __name__ == '__main__':
    play_game()


And now Im getting this message :

** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
<type 'list'>
type robotsTraceback (most recent call last):
 <type 'list'>
type junk <type 'list'>
type player <type 'dict'>
  File "/root/workspace/test2/src/test.py", line 125, in <module>
    play_game()
  File "/root/workspace/test2/src/test.py", line 111, in play_game
    defeated = check_collisions(robots, player, junk)
  File "/root/workspace/test2/src/test.py", line 74, in check_collisions
    for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

So far I can see the problem is that player is a dict and the rest is a list.

Is this the correct conclusion ?

Roelof


> To: tutor at python.org
> From: __peter__ at web.de
> Date: Thu, 16 Sep 2010 18:10:13 +0200
> Subject: Re: [Tutor] robots question
> 
> Roelof Wobben wrote:
> 
> > As a exercise from this book ( Thinking like a computer scientist ) I have
> > to make this programm on this
> > page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> > Exercise 11
> 
> > def check_collisions(robots, junk, player):
> 
> >         defeated = check_collisions(robot, player, junk)
> 
> Just look at the argument names: check_collisions() is probably expecting a 
> /list/ of robots where you are passing it a single one.
> 
> > But now Im getting this error message :
> > 
> > Traceback (most recent call last):
> >   File "/root/workspace/test2/src/test.py", line 120, in <module>
> >     play_game(2)
> >   File "/root/workspace/test2/src/test.py", line 106, in play_game
> >     defeated = check_collisions(robot, player, junk)
> >   File "/root/workspace/test2/src/test.py", line 73, in check_collisions
> >     for thing in robots + junk:
> > TypeError: can only concatenate list (not "dict") to list
> > 
> > I understand that robots is a dict and junk is a list.
> > 
> > Is that right ?
> 
> Yes. You are getting a dict because a single robot's state is stored in a 
> dictionary.
> 
> > And why does the book say that when this message is appearing.
> 
> The way the program is presented makes it hard to tell at what point your 
> and Eckel's idea of the script start to differ without going through the 
> entire chapter.
> 
> Aside: that's why real projects use version control systems. When a program 
> stops working after a change there is always the option to go back to the 
> state of the program before the bug was introduced.
> 
> Peter
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/23624c1c/attachment.html>

From alan.gauld at btinternet.com  Thu Sep 16 19:48:13 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 Sep 2010 18:48:13 +0100
Subject: [Tutor] intercepting and recored I/O function calls
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com><i6reb1$h7l$1@dough.gmane.org>
	<AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
Message-ID: <i6tl92$q65$1@dough.gmane.org>


"Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote


> I am using centos, however i don't even have admin privileges. 
> Which API
> are you referring to?

The OS API - Win32 in Windows or the Unix standard library etc

Alan G 



From __peter__ at web.de  Thu Sep 16 20:10:02 2010
From: __peter__ at web.de (Peter Otten)
Date: Thu, 16 Sep 2010 20:10:02 +0200
Subject: [Tutor] FW:  robots question
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
	<i6tfe6$r6d$1@dough.gmane.org>
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>
	<SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>
Message-ID: <i6tmes$dl$1@dough.gmane.org>

Roelof Wobben wrote:

> I change everything to this :

> def check_collisions(robots, junk, player):

>         defeated = check_collisions(robots, player, junk)

Do you see the problem?

>         print "type robots", type(robots)
>         print "type junk", type(junk)
>         print "type player", type(player)

Adding print statements for debugging purposes is a good approach.

> And now Im getting this message :
> 
> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
> <type 'list'>
> type robotsTraceback (most recent call last):
>  <type 'list'>
> type junk <type 'list'>
> type player <type 'dict'>
>   File "/root/workspace/test2/src/test.py", line 125, in <module>
>     play_game()
>   File "/root/workspace/test2/src/test.py", line 111, in play_game
>     defeated = check_collisions(robots, player, junk)
>   File "/root/workspace/test2/src/test.py", line 74, in check_collisions
>     for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> So far I can see the problem is that player is a dict and the rest is a
> list.
> Is this the correct conclusion ?

It may be correct but it's a low-level view. A more appropriate description 
would be that you are trying to concatenate a list of robots with a player.

Peter


From rwobben at hotmail.com  Thu Sep 16 20:22:57 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 16 Sep 2010 18:22:57 +0000
Subject: [Tutor] FW:  FW:  robots question
In-Reply-To: <SNT118-W45180E3212B8ED770C6D2EAE7A0@phx.gbl>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>,
	<i6tfe6$r6d$1@dough.gmane.org>,
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>,
	<SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>,
	<i6tmes$dl$1@dough.gmane.org>,
	<SNT118-W45180E3212B8ED770C6D2EAE7A0@phx.gbl>
Message-ID: <SNT118-W47AF7B88CA0CF3477F80D0AE7A0@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: __peter__ at web.de
> Subject: RE: [Tutor] FW: robots question
> Date: Thu, 16 Sep 2010 18:22:03 +0000
>
>
>
>
> ----------------------------------------
>> To: tutor at python.org
>> From: __peter__ at web.de
>> Date: Thu, 16 Sep 2010 20:10:02 +0200
>> Subject: Re: [Tutor] FW: robots question
>>
>> Roelof Wobben wrote:
>>
>>> I change everything to this :
>>
>>> def check_collisions(robots, junk, player):
>>
>>> defeated = check_collisions(robots, player, junk)
>>
>> Do you see the problem?
>
>

yes, Player en junk are swapped.

>
>
>>
>>> print "type robots", type(robots)
>>> print "type junk", type(junk)
>>> print "type player", type(player)
>>
>> Adding print statements for debugging purposes is a good approach.
>>
>>> And now Im getting this message :
>>>
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
>>> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
>>>
>>> type robotsTraceback (most recent call last):
>>>
>>> type junk
>>> type player
>>> File "/root/workspace/test2/src/test.py", line 125, in
>>> play_game()
>>> File "/root/workspace/test2/src/test.py", line 111, in play_game
>>> defeated = check_collisions(robots, player, junk)
>>> File "/root/workspace/test2/src/test.py", line 74, in check_collisions
>>> for thing in robots + junk:
>>> TypeError: can only concatenate list (not "dict") to list
>>>
>>> So far I can see the problem is that player is a dict and the rest is a
>>> list.
>>> Is this the correct conclusion ?
>>
>> It may be correct but it's a low-level view. A more appropriate description
>> would be that you are trying to concatenate a list of robots with a player.
>

Oke,

 I will try to make one list which will contain the robots and a player.
 
 

>>
>> Peter
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor 		 	   		  

From michael at trollope.org  Thu Sep 16 20:27:28 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 14:27:28 -0400
Subject: [Tutor] Comparing two lists
Message-ID: <20100916182728.GD2727@cecilia>

Hello,

I have two lists.

alist = ['label', 'guid']

blist = ['column0label', 'column1label', 'dimension0guid',
'description', 'columnid'] 

I want to iterate over blist and extract the items that match my
substrings in alist; alternatively, throw out the items that aren't in
alist (but, I've had bad experiences removing items from lists "in
place," so I tend toward the "copy" motif.)

In real life, blist column entries could have embedded column numbers
from 0 to 19.

I can do this with excrutiatingly painful 'for' loops.  Looking for
something more efficient and elegant.  

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA

"The secret to strong security: less reliance on secrets."
-- Whitfield Diffie
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/7657d1ae/attachment.pgp>

From vince at vinces.ca  Thu Sep 16 20:49:51 2010
From: vince at vinces.ca (Vince Spicer)
Date: Thu, 16 Sep 2010 12:49:51 -0600
Subject: [Tutor] Comparing two lists
In-Reply-To: <20100916182728.GD2727@cecilia>
References: <20100916182728.GD2727@cecilia>
Message-ID: <AANLkTimUQRWBRr+dhZ5ifTurOkCBS=E7kAdpjSVmZ_fd@mail.gmail.com>

On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe <michael at trollope.org> wrote:

> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>
> I want to iterate over blist and extract the items that match my
> substrings in alist; alternatively, throw out the items that aren't in
> alist (but, I've had bad experiences removing items from lists "in
> place," so I tend toward the "copy" motif.)
>
> In real life, blist column entries could have embedded column numbers
> from 0 to 19.
>
> I can do this with excrutiatingly painful 'for' loops.  Looking for
> something more efficient and elegant.
>
> Thanks.
>
> mp
>
> --
> Michael Powe            michael at trollope.org            Naugatuck CT USA
>
> "The secret to strong security: less reliance on secrets."
> -- Whitfield Diffie
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Michel,

One solution is to use list comprehensions.

newlist = [x for x in blist if [a for a in alist if a in x]]

This works, although there may be more efficient ways to accomplish this

Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/fb10c862/attachment.html>

From vince at vinces.ca  Thu Sep 16 20:59:08 2010
From: vince at vinces.ca (Vince Spicer)
Date: Thu, 16 Sep 2010 12:59:08 -0600
Subject: [Tutor] Comparing two lists
In-Reply-To: <AANLkTimUQRWBRr+dhZ5ifTurOkCBS=E7kAdpjSVmZ_fd@mail.gmail.com>
References: <20100916182728.GD2727@cecilia>
	<AANLkTimUQRWBRr+dhZ5ifTurOkCBS=E7kAdpjSVmZ_fd@mail.gmail.com>
Message-ID: <AANLkTimaFx+YNV5SLkOz-kANbR+ujHmuME8j9BCN+HQR@mail.gmail.com>

On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer <vince at vinces.ca> wrote:

>
>
> On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe <michael at trollope.org>wrote:
>
>> Hello,
>>
>> I have two lists.
>>
>> alist = ['label', 'guid']
>>
>> blist = ['column0label', 'column1label', 'dimension0guid',
>> 'description', 'columnid']
>>
>> I want to iterate over blist and extract the items that match my
>> substrings in alist; alternatively, throw out the items that aren't in
>> alist (but, I've had bad experiences removing items from lists "in
>> place," so I tend toward the "copy" motif.)
>>
>> In real life, blist column entries could have embedded column numbers
>> from 0 to 19.
>>
>> I can do this with excrutiatingly painful 'for' loops.  Looking for
>> something more efficient and elegant.
>>
>> Thanks.
>>
>> mp
>>
>> --
>> Michael Powe            michael at trollope.org            Naugatuck CT USA
>>
>> "The secret to strong security: less reliance on secrets."
>> -- Whitfield Diffie
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
> Michel,
>
> One solution is to use list comprehensions.
>
> newlist = [x for x in blist if [a for a in alist if a in x]]
>
> This works, although there may be more efficient ways to accomplish this
>
> Vince
>
>
On major speed up is to make a simple filter that returns as soon as a match
is found instead of
completing the loop every element in alist

def filter_(x, against):
    for a in against:
        if a in x:
            return True
    return False

newlist = [x for x in blist if filter_(x, alist)]

:)

Vince
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/11a6cd59/attachment.html>

From michael at trollope.org  Thu Sep 16 21:19:33 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 15:19:33 -0400
Subject: [Tutor] Comparing two lists
In-Reply-To: <AANLkTimaFx+YNV5SLkOz-kANbR+ujHmuME8j9BCN+HQR@mail.gmail.com>
References: <20100916182728.GD2727@cecilia>
	<AANLkTimUQRWBRr+dhZ5ifTurOkCBS=E7kAdpjSVmZ_fd@mail.gmail.com>
	<AANLkTimaFx+YNV5SLkOz-kANbR+ujHmuME8j9BCN+HQR@mail.gmail.com>
Message-ID: <20100916191933.GE2727@cecilia>

On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer <vince at vinces.ca> wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe <michael at trollope.org>wrote:

> >> alist = ['label', 'guid']

> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']
> >>
> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> > One solution is to use list comprehensions.

> > newlist = [x for x in blist if [a for a in alist if a in x]]

> > This works, although there may be more efficient ways to accomplish this

> On major speed up is to make a simple filter that returns as soon as a match
> is found instead of
> completing the loop every element in alist
 
> def filter_(x, against):
>     for a in against:
>         if a in x:
>             return True
>     return False
> 
> newlist = [x for x in blist if filter_(x, alist)]

Hello,

Very cool, thanks.

I've used list comprehensions before but I just couldn't get the
structure right this time, for some reason.

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA
"No provision in our Constitution ought to be dearer to man than that
which protects the rights of conscience against the enterprises of the
civil authority." -- Thomas Jefferson to New London Methodists,
1809. ME 16:332
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/bec53454/attachment-0001.pgp>

From emile at fenx.com  Thu Sep 16 21:44:55 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 16 Sep 2010 12:44:55 -0700
Subject: [Tutor] Comparing two lists
In-Reply-To: <20100916182728.GD2727@cecilia>
References: <20100916182728.GD2727@cecilia>
Message-ID: <i6ts3o$q3a$1@dough.gmane.org>

On 9/16/2010 11:27 AM Michael Powe said...
> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>

Something like this?

 >>> [ ii for jj in alist for ii in blist if jj in ii ]
['column0label', 'column1label', 'dimension0guid']

Emile


From michael at trollope.org  Thu Sep 16 22:00:19 2010
From: michael at trollope.org (Michael Powe)
Date: Thu, 16 Sep 2010 16:00:19 -0400
Subject: [Tutor] Comparing two lists
In-Reply-To: <AANLkTimaFx+YNV5SLkOz-kANbR+ujHmuME8j9BCN+HQR@mail.gmail.com>
References: <20100916182728.GD2727@cecilia>
	<AANLkTimUQRWBRr+dhZ5ifTurOkCBS=E7kAdpjSVmZ_fd@mail.gmail.com>
	<AANLkTimaFx+YNV5SLkOz-kANbR+ujHmuME8j9BCN+HQR@mail.gmail.com>
Message-ID: <20100916200019.GF2727@cecilia>

On Thu, Sep 16, 2010 at 12:59:08PM -0600, Vince Spicer wrote:
> On Thu, Sep 16, 2010 at 12:49 PM, Vince Spicer <vince at vinces.ca> wrote:

> > On Thu, Sep 16, 2010 at 12:27 PM, Michael Powe <michael at trollope.org>wrote:

> >> I have two lists.

> >> alist = ['label', 'guid']
> >>
> >> blist = ['column0label', 'column1label', 'dimension0guid',
> >> 'description', 'columnid']

> >> I want to iterate over blist and extract the items that match my
> >> substrings in alist; alternatively, throw out the items that aren't in
> >> alist (but, I've had bad experiences removing items from lists "in
> >> place," so I tend toward the "copy" motif.)

> On major speed up is to make a simple filter that returns as soon as
> a match is found instead of completing the loop every element in
> alist

> def filter_(x, against):
>     for a in against:
>         if a in x:
>             return True
>     return False

Hello,

Totally awesome.  I actually have a dictionary, with the key being an
ini file header and the value being one of these lists of ini
settings.  With your method, I am able to loop through the dictionary,
and expunge the unwanted settings.

I knew there had to be a way to take advantage of the fact that the 'i
in s' object test acts like a substring test for strings.  

Thanks.

mp

-- 
Michael Powe		michael at trollope.org		Naugatuck CT USA

'Unless we approve your idea, it will not be permitted, it will not be
allowed.'  -- Hilary Rosen, President, RIAA
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/02e2c176/attachment.pgp>

From alan.gauld at btinternet.com  Thu Sep 16 23:26:14 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 16 Sep 2010 22:26:14 +0100
Subject: [Tutor] Function behavior
References: <4C920B25.8020405@gmail.com>
Message-ID: <i6u21r$nig$1@dough.gmane.org>


"Ken Green" <beachkidken at gmail.com> wrote

>I am unclear on the behavior of using a function.

You certainly are!
Which tutorial are you working from?
You have several fundamental errors here, its hard to know
where to start.

> def change(amount):
>     if match == 1:
>         amount = 0
>     if match == 2:
>         amount = 0
>     if match == 3:
>         amount = 3

This function is called change and it has an input parameter called 
amount.
The parameter is like a local variable only visible inside the 
function.
Because there are no return statements in it it will always return the
default value of None - probably not what you want.

Inside the function you compare a variable called match - which is not
defined in the function so presumably will be found outside in the 
module
or global scope - to a number.
You then set the parameter amount to another number, one greater
than the test value. But since amount is the parameter and invisible
outside the function that will have no affect on anything outside the
function.

> match = raw_input("How many matches?: ")

Now we define the global variable match but set it to a string.
The change() function is expecting match to be a number.
Maybe we should convert it using int()?

> change(match)


This does nothing and since we don't assign the functions value
to anything the None that it returns is lost.

> print amount

amount is not defined anywhere at the global scope and
the amount parameter in the function is not visible outside
the function.

> How many matches?: 2
> Traceback (most recent call last):
>   File "/home/ken/Python262/TEST Function.py", line 13, in <module>
>     print amount
> NameError: name 'amount' is not defined

> Should it be def change(match) instead of def change(amount)?
> Perhaps, change(amount) instead of change(match)?

You need to go back to basics on how parameters and arguments
work (This is, I admit, a subtle concept when you first come across 
it)

> Perhaps, I need to add return somewhere?

Yes you probably do. You can do what you want without it but
its considered bad practice. Functions should reurn their results.

Try reading the functions and modules topic in my tutorial
to see if that helps.

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




From matt.gregory at oregonstate.edu  Thu Sep 16 23:43:30 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Thu, 16 Sep 2010 14:43:30 -0700
Subject: [Tutor] constructing objects with one set of required options
Message-ID: <1D673F86DDA00841A1216F04D1CE70D64261C9D024@EXCH2.nws.oregonstate.edu>

Sorry for what is probably a poor subject line ...

Generally, I'm trying to understand the best way to set up an object's __init__ if there are some required parameters and other parameters that can be specified in a number of ways.  As an example, I'm working on an envelope class that describes a spatial envelope complete with cell size information.  Assuming that this envelope needs to have its upper left corner specified and a cell size, I can *either* specify a lower right corner or the number of rows and columns to finish the specification.  Can folks provide guidance on a good way to do this?  Specifically, I'm wondering if some or all options should be by position or by keyword.

Here's my first cut of doing it all by keyword.

class EnvelopeException(Exception):
    pass

class Envelope(object):
    def __init__(self, **kwargs):
        try:
            self.x_min = kwargs['x_min']
            self.y_max = kwargs['y_max']
            self.cell_size = kwargs['cell_size']
        except KeyError:
            err_str = 'Not all required parameters were specified'
            raise EnvelopeException(err_str)

        try:
            # First try n_cols and n_rows as keyword args
            self.n_cols = kwargs['n_cols']
            self.n_rows = kwargs['n_rows']
        except KeyError:
            try:
                # Try x_max and y_min instead
                self.x_max = kwargs['x_max']
                self.y_min = kwargs['y_min']
            except KeyError:
                err_str  = 'Either the number of rows and columns or '
                err_str += 'the lower-right coordinate was not specified.'
                raise EnvelopeException(err_str)

        # calculate the remaining parts of the specification
        ...

(I realize that I could also specify the x_max and the n_rows or y_min and n_cols and still derive the envelope, but that seemed nonintuitive to me, although maybe I should consider it.)

thanks for help,
matt

From prologic at shortcircuit.net.au  Thu Sep 16 23:59:16 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 17 Sep 2010 07:59:16 +1000
Subject: [Tutor] constructing objects with one set of required options
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D64261C9D024@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D64261C9D024@EXCH2.nws.oregonstate.edu>
Message-ID: <AANLkTi=pURLZS6-D=UW1D0w8zMO2rBKbXFvxqyOZjss6@mail.gmail.com>

On Fri, Sep 17, 2010 at 7:43 AM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
> Sorry for what is probably a poor subject line ...
>
> Generally, I'm trying to understand the best way to set up an object's __init__ if there are some required parameters and other parameters that can be specified in a number of ways. ?As an example, I'm working on an envelope class that describes a spatial envelope complete with cell size information. ?Assuming that this envelope needs to have its upper left corner specified and a cell size, I can *either* specify a lower right corner or the number of rows and columns to finish the specification. ?Can folks provide guidance on a good way to do this? ?Specifically, I'm wondering if some or all options should be by position or by keyword.
>
> Here's my first cut of doing it all by keyword.
>
> class EnvelopeException(Exception):
> ? ?pass
>
> class Envelope(object):
> ? ?def __init__(self, **kwargs):
> ? ? ? ?try:
> ? ? ? ? ? ?self.x_min = kwargs['x_min']
> ? ? ? ? ? ?self.y_max = kwargs['y_max']
> ? ? ? ? ? ?self.cell_size = kwargs['cell_size']
> ? ? ? ?except KeyError:
> ? ? ? ? ? ?err_str = 'Not all required parameters were specified'
> ? ? ? ? ? ?raise EnvelopeException(err_str)
>
> ? ? ? ?try:
> ? ? ? ? ? ?# First try n_cols and n_rows as keyword args
> ? ? ? ? ? ?self.n_cols = kwargs['n_cols']
> ? ? ? ? ? ?self.n_rows = kwargs['n_rows']
> ? ? ? ?except KeyError:
> ? ? ? ? ? ?try:
> ? ? ? ? ? ? ? ?# Try x_max and y_min instead
> ? ? ? ? ? ? ? ?self.x_max = kwargs['x_max']
> ? ? ? ? ? ? ? ?self.y_min = kwargs['y_min']
> ? ? ? ? ? ?except KeyError:
> ? ? ? ? ? ? ? ?err_str ?= 'Either the number of rows and columns or '
> ? ? ? ? ? ? ? ?err_str += 'the lower-right coordinate was not specified.'
> ? ? ? ? ? ? ? ?raise EnvelopeException(err_str)
>
> ? ? ? ?# calculate the remaining parts of the specification
> ? ? ? ?...
>
> (I realize that I could also specify the x_max and the n_rows or y_min and n_cols and still derive the envelope, but that seemed nonintuitive to me, although maybe I should consider it.)

Rather than present you with what I think (subjective)
might be a "good solution", why don't you look up in the
python documentation how you define methods and
what you can do with them (parameters-wise).

I'll summarize:

def foo(self, a, b, c):
   ...
def foor(self, a, b, *args):
   ...
def foo(self, a, b, c=None):
   ...
def foo(self, a, b, *args, **kwargs):
   ...

There are probably other combinations, but these are
probably the most common.

The point I'm trying to make here is that this is
really "up to you".

Use a combination of variable arguments (*args)
and maybe some arguments with default values
(c=None) or just use **kwargs. Choice is yours :)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From matt.gregory at oregonstate.edu  Fri Sep 17 00:35:37 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Thu, 16 Sep 2010 15:35:37 -0700
Subject: [Tutor] constructing objects with one set of required options
In-Reply-To: <AANLkTi=pURLZS6-D=UW1D0w8zMO2rBKbXFvxqyOZjss6@mail.gmail.com>
References: <1D673F86DDA00841A1216F04D1CE70D64261C9D024@EXCH2.nws.oregonstate.edu>
	<AANLkTi=pURLZS6-D=UW1D0w8zMO2rBKbXFvxqyOZjss6@mail.gmail.com>
Message-ID: <1D673F86DDA00841A1216F04D1CE70D64261C9D02C@EXCH2.nws.oregonstate.edu>

Hi James,

James Mills wrote:
> Rather than present you with what I think (subjective)
> might be a "good solution", why don't you look up in the
> python documentation how you define methods and
> what you can do with them (parameters-wise).
> 
> I'll summarize:
> 
> def foo(self, a, b, c):
>    ...
> def foor(self, a, b, *args):
>    ...
> def foo(self, a, b, c=None):
>    ...
> def foo(self, a, b, *args, **kwargs):
>    ...
> 
> There are probably other combinations, but these are
> probably the most common.
> 
> The point I'm trying to make here is that this is
> really "up to you".
> 
> Use a combination of variable arguments (*args)
> and maybe some arguments with default values
> (c=None) or just use **kwargs. Choice is yours :)

Thanks for your reply.  I do understand all the different ways parameters can be passed and realize that it's up to me to choose that signature.  But, mostly, I wanted advice on how to make this signature as intuitive as possible to a user.  So, from my earlier example, a signature with positional args like this is a bad idea:

    class Envelope:
        def __init__(x_min, y_max, cell_size, *args):
            ...

    # are args 3 and 4 rows and columns or x_max, y_min?
    e = Envelope(10, 20, 1, 30, 10)

so I know at least the last two args should probably be keywords, but a signature like this is somewhat confusing to me as well because it's not immediately clear to me what the first three parameters are by looking at the *call* (obviously by looking at the method you can figure it out).

   def __init__(x_min, y_max, cell_size, **kwargs):
   e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
   e = Envelope(10, 20, 1, x_max=30, y_min=10)

So I know I'm getting around to answering my own question, but the clearest way to me was to provide all keyword args.  I just didn't know if this was too verbose from a user's standpoint.  Really just a stylistic question that might be best left to the individual.

thanks for help,
matt

From prologic at shortcircuit.net.au  Fri Sep 17 00:44:02 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 17 Sep 2010 08:44:02 +1000
Subject: [Tutor] constructing objects with one set of required options
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D64261C9D02C@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D64261C9D024@EXCH2.nws.oregonstate.edu>
	<AANLkTi=pURLZS6-D=UW1D0w8zMO2rBKbXFvxqyOZjss6@mail.gmail.com>
	<1D673F86DDA00841A1216F04D1CE70D64261C9D02C@EXCH2.nws.oregonstate.edu>
Message-ID: <AANLkTin_+yKmqTWmY-8Gp2DcHudDBtromeyy=0B2=4L4@mail.gmail.com>

On Fri, Sep 17, 2010 at 8:35 AM, Gregory, Matthew
<matt.gregory at oregonstate.edu> wrote:
> Thanks for your reply. ?I do understand all the different ways parameters can be passed and realize that it's up to me to choose that signature. ?But, mostly, I wanted advice on how to make this signature as intuitive as possible to a user. ?So, from my earlier example, a signature with positional args like this is a bad idea:
>
> ? ?class Envelope:
> ? ? ? ?def __init__(x_min, y_max, cell_size, *args):
> ? ? ? ? ? ?...
>
> ? ?# are args 3 and 4 rows and columns or x_max, y_min?
> ? ?e = Envelope(10, 20, 1, 30, 10)

Don't forget "self".

This signature seems okay to me.

> so I know at least the last two args should probably be keywords, but a signature like this is somewhat confusing to me as well because it's not immediately clear to me what the first three parameters are by looking at the *call* (obviously by looking at the method you can figure it out).
>
> ? def __init__(x_min, y_max, cell_size, **kwargs):
> ? e = Envelope(10, 20, 1, n_cols=30, n_rows=10)
> ? e = Envelope(10, 20, 1, x_max=30, y_min=10)
>
> So I know I'm getting around to answering my own question, but the clearest way to me was to provide all keyword args. ?I just didn't know if this was too verbose from a user's standpoint. ?Really just a stylistic question that might be best left to the individual.

In my experience, I've always defined explicit arguments and keyword arguments
for constructors and use **kwargs for anything that can be specified as optional
but have defaults. eg:

class Foo(object)
   def __init__(self, a, b, c, x=1, **kwargs):
      super(Foo, self).__init__()

      self.a = a
      self.b = b
      self.c = c

      self.x = x

      self.y = kwargs.get("y", None)

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From martin at linux-ip.net  Fri Sep 17 00:45:29 2010
From: martin at linux-ip.net (Martin A. Brown)
Date: Thu, 16 Sep 2010 18:45:29 -0400
Subject: [Tutor] intercepting and recored I/O function calls
In-Reply-To: <AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
	<i6reb1$h7l$1@dough.gmane.org>
	<AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
Message-ID: <alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>


[apologies in advance for an answer that is partially off topic]

Hi there JoJo,

 : I could begin with tracing I/O calls in my App.. if its 
 : sufficient enough i may not need i/o calls for the OS.

What do you suspect?  Filesystem I/O?

  * open(), close(), opendir() closedir() filesystem latency?
  * read(), write() latency?
  * low read() and write() throughput?

Network I/O?

  * Are name lookups taking a long time?
  * Do you have slow network throughput?  (Consider tcpdump.)

Rather than writing code (at first glance), why not use a system 
call profiler to check this out.  It is very unlikely that python 
itself is the problem.  Could it be the filesystem/network?  Could 
it be DNS?  A system call profiler can help you find this.

Are you asking this because you plan on diagnosing I/O performance 
issues in your application?  Is this a one time thing in a 
production environment that is sensitive to application latency?  
If so, you might try tickling the application and attaching to the 
process with a system call tracer.  Under CentOS you should be able 
to install 'strace'.  If you can run the proggie on the command 
line:

  strace -o /tmp/trace-output-file.txt -f python yourscript.py args

Then, go learn how to read the /tmp/trace-output-file.txt.

Suggested options:

  -f        follow children
  -ttt      sane Unix-y timestamps
  -T        total time spent in each system call
  -s 256    256 byte limit on string output (default is 32)
  -o file   store trace data in a file
  -p pid    attach to running process of pid
  -c        only show a summary of cumulative time per system call

 : > But this is extremely dependant on the Operating System - you will
 : > basically have to intercept the system calls. So, which OS are 
 : > you using?  And how familiar are you with its API?
 : 
 : I am using centos, however i don't even have admin privileges.  
 : Which API are you referring to?

You shouldn't need admin privileges if you can run the program as 
yourself.  If you have setuid/setgid bits, then you will need 
somebody with administrative privileges to help you.

OK, so let's say that you have already done this and understand all 
of the above, you know it's not the system and you really want to 
understand where your application is susceptible to bad performance 
or I/O issues.  Now, we're back to python land.

  * look at the profile module
    http://docs.python.org/library/profile.html

  * instrument your application by using the logging module
    http://docs.python.org/library/logging.html

You might ask how it is a benefit to use the logging module.  Well, 
if your program generates logging data (let's say to STDERR) and you 
do not include timestamps on each log line, you can trivially add 
timestamps to the logging data using your system's logging 
facilities:

  { python thingy.py >/dev/null ; } 2>&1 | logger -ist 'thingy.py' --

Or, if you like DJB tools:

  { python thingy.py >/dev/null ; } 2>&1 | multilog t ./directory/

Either of which solution leaves you (implicitly) with timing 
information.

 : > Also, While you can probably do this in Python but its likely 
 : > to have a serious impact on the OS performance, it will slow 
 : > down the performamce quite noticeably. I'd normally recommend 
 : > using C for something like this.

Alan's admonition bears repeating.  Trapping all application I/O is 
probably just fine for development, instrumenting and diagnosing, 
but you may wish to support that in an easily removable manner, 
especially if performance is paramount.

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From alan.gauld at btinternet.com  Fri Sep 17 01:45:39 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 Sep 2010 00:45:39 +0100
Subject: [Tutor] "Overloading" methods
References: <20100916120218.GC2727@cecilia>
	<AANLkTimPA+TA3i2Yf05hqaksXpDEKSxP4g6uye+jHGbH@mail.gmail.com>
Message-ID: <i6ua78$np3$1@dough.gmane.org>


> On Thu, Sep 16, 2010 at 6:02 AM, Michael Powe <michael at trollope.org> 
> wrote:
>
>> line structures, I had the thought to write methods with 
>> descriptive
>> names that simply returned a generic method that processed the 
>> method
>> arguments. e.g.,
>>
>> def setpattern_iis(self,pattern,parameter) :
>>        type='iis'
>>        return pattern_generator(self,type,pattern,parameter)
>>
>> In this case, creating a regular expression to parse the log lines 
>> for
>> a query parameter.

This doesn't really show that, it shows you calling a function and
returning its result, but we have no way of knowing what that is.

However the concept is sound and quite common in functional
programming where the function which returns another function
is referred to as a higher order function.

>> This is just a bit more "self documenting" than using the generic
>> method with the 'type' argument and requiring the user to enter the
>> type.  At the same time, it allows me to put all the parsing code 
>> in
>> one method.

Going by your example above it only saves one parameter - the
type - and I'm not sure that's so valuable. However without real code
its hard to judge. The concept is sound but like so many things
its possible to abuse it.

You can usually achieve similar ends with classes and/or dispatch
tables.

HTH,


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



From alan.gauld at btinternet.com  Fri Sep 17 02:14:32 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 Sep 2010 01:14:32 +0100
Subject: [Tutor] robots question
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>,
	<i6tfe6$r6d$1@dough.gmane.org>,
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>
	<SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>
Message-ID: <i6ubtc$t5k$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote


#
# robots.py

This is pretty weird code, there are several odd things in it.

def place_player():
    # x = random.randint(0, GRID_WIDTH)
    # y = random.randint(0, GRID_HEIGHT)
    x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
    return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 
'y': y}

So this returns a dictionary which always contains the same data.

def place_robot(x,y, junk):
    x = random.randint(0, GRID_WIDTH)
    y = random.randint(0, GRID_HEIGHT)
    return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}

This returns a similar dict but with random data.
It ignores the values of x and y passed in and does not use junk at 
all.

def place_robots(numbots):
    robots = []
    # for i in range(numbots):
    #    x = random.randint(0, GRID_WIDTH)
    #    y = random.randint(0, GRID_HEIGHT)
    #    robots.append(place_robot(x, y))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, 
junk= False))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, 
junk = False))
    print type(robots)
    return robots

This returns a list of 2 dictionaries. The x,y parameters are ignored 
by the function.


def move_player(player):
    update_when('key_pressed')
    if key_pressed('escape'):
        return True
    elif key_pressed('4'): ...
    else:
        return False
    move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))
    return False

This seems OK, it returns True for escape otherwise False.

def collided(thing1, thing2):
    return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

This returns a boolean


def check_collisions(robots, junk, player):
    # check whether player has collided with anything
    for thing in robots + junk:
        if collided(thing, player):
            return True
    return False

Could be simplified to just

for thing in robots + junk:
     return collided(thing, player)

It requires that robots and junk are capable of being added together
and the result being iterable.

def move_robot(robot, player):
    if robot['x'] < player['x']: robot['x'] += 1
    elif robot['x'] > player['x']: robot['x'] -= 1

    if robot['y'] < player['y']: robot['y'] += 1
    elif robot['y'] > player['y']: robot['y'] -= 1

    move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

I don't see move_to so assume its part of the module you imported?

def move_robots(robots, player):
    for robot in robots:
        move_robot(robot, player)

ok


def play_game():
    begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    player = place_player()
    robot = place_robots(4)
    junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
    robots = []
    defeated = False

So at this point
player is a dict
robot is a list of 2 dicts
junk is a list of one dict
robots is an empty list


    while not defeated:
        quit =  move_player(player)
        if quit:
            break
        move_robots(robots, player)
        print "type robots", type(robots)
        print "type junk", type(junk)
        print "type player", type(player)
        defeated = check_collisions(robots, player, junk)

You now call check_collisions passing an empty list and a dict and a 
list of a dict
The order in the definition is:

def check_collisions(robots, junk, player):

so it looks like you swapped the last two arguments


And now Im getting this message :

** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
<type 'list'>

Not sure where that lot came from...

type robotsTraceback (most recent call last):
 <type 'list'>
type junk <type 'list'>
type player <type 'dict'>
  File "/root/workspace/test2/src/test.py", line 125, in <module>
    play_game()
  File "/root/workspace/test2/src/test.py", line 111, in play_game
    defeated = check_collisions(robots, player, junk)
  File "/root/workspace/test2/src/test.py", line 74, in 
check_collisions
    for thing in robots + junk:
TypeError: can only concatenate list (not "dict") to list

But this is valid because of the swapped arguments.

> So far I can see the problem is that player is a dict and the rest 
> is a list.
> Is this the correct conclusion ?

Yes, but you missed the fact that you changed the order of the 
arguments.
When you get type errors check the types at your interfaces(functions, 
classes etc)
match the definitions.

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



From steve at pearwood.info  Fri Sep 17 02:15:20 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 17 Sep 2010 10:15:20 +1000
Subject: [Tutor] How to get both 2.6 scripts as well as 3.1 scripts to
	run at command line?
In-Reply-To: <AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>
References: <AANLkTinY2qxPRo983799-_Q2gqdKkwyLpSVQ3W-hM_fH@mail.gmail.com>
	<AANLkTimFLr4CKYqqwjZwxLNZB-La2kea_qOQe-cnZhP4@mail.gmail.com>
Message-ID: <201009171015.20593.steve@pearwood.info>

On Thu, 16 Sep 2010 01:35:17 pm David Hutto wrote:
> print("a is", a)
> or
> from future import *

Neither of those lines are correct. Given (say) a=42, in Python 2.6 the 
first line will print the tuple:

("a is", 42)

while in Python 3.1 it will print the string:

a is 42

Note the extra punctuation in the first version. For a quick-and-dirty 
script, you might not care about that, so passing tuples to print in 
2.x is a reasonably simple work-around, but they are not the same.

On the other hand, the second line does behave the same in both Python 
2.6 and 3.1:

>>> from future import *
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named future

It might be the same, but I'm pretty sure it's not useful.

What you are thinking of is the special module __future__ with leading 
and trailing double-underscores. __future__ is special -- the line 

from __future__ import ...

(where ... is one or more feature) tells the Python compiler to change 
behaviour. If you use a "from __future__ import" line, it MUST be the 
first executable line in a module or script. It's okay for it to follow 
blank lines, comments or a doc-string, but it must be before any other 
line of Python code.

In the case of Python 2.6 you can execute:

from __future__ import print_function

to turn print into a function like in 3.1.

However, you can't use the asterisk form:

>>> from __future__ import *
  File "<stdin>", line 1
SyntaxError: future feature * is not defined



-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 17 03:00:38 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 17 Sep 2010 11:00:38 +1000
Subject: [Tutor] "Overloading" methods
In-Reply-To: <20100916120218.GC2727@cecilia>
References: <20100916120218.GC2727@cecilia>
Message-ID: <201009171100.39322.steve@pearwood.info>

On Thu, 16 Sep 2010 10:02:18 pm Michael Powe wrote:
> Hello,
>
> Strictly speaking, this isn't overloading a method in the way we do
> it in Java.  But similar.  Maybe.

Ha ha, you sound like me -- I can recognise design patterns, but I have 
no idea what they're called, or why anyone bothers to distinguish 
between the "builder" pattern and the "factory" pattern... the 
difference is too subtle for me.

It sounds like what you're trying to do is a design pattern, or 
combination of patterns.


> I am writing a module for processing web server log files and one of
> the methods I provide is to extract a given query parameter and its
> value.

So you have a module that provides a single log-processing class with a 
single method that extracts query parameters?

If there will only ever be a single instance of the class, you should 
consider making the methods ordinary functions. Instead of:

inst = module.LogProcessor()
inst.extract(stuff)


you get:

module.extract(stuff)


Modules give you Singleton behaviour for free!


> Because there are several types of log files with different 
> line structures, I had the thought to write methods with descriptive
> names that simply returned a generic method that processed the method
> arguments. e.g.,
>
> def setpattern_iis(self,pattern,parameter) :
> 	type='iis'
> 	return pattern_generator(self,type,pattern,parameter)
>
> In this case, creating a regular expression to parse the log lines
> for a query parameter.

Sounds fine to me. I would question the name -- a method 
called "setpattern_iis" should, well, *set* a pattern somewhere (a 
global? a property?), not return a value. But other than that, the 
basic tactic is sound. Whether it is more or less straightforward 
compared to alternatives is another question. (See below.)


> This is just a bit more "self documenting" than using the generic
> method with the 'type' argument and requiring the user to enter the
> type.

True, but consider how the caller might use this. I'm guessing what your 
API might be:

import module
log_parser = module.Log_Parser()  # make a generic parser
regex = logParser.setpattern_iis(pattern, parameter)  # get a regex
results = logParser.search_log(regex, log)  # and use it

Am I close? 

Perhaps a better API might be:

import module
log_parser = module.IIS_Log_Parser()  # make a IIS parser
results = log_parser.search_log(pattern, parameters, log)


In this case, the basic strategy would be to have an abstract log 
parser:

class AbstractLogParser(object):
    type = None

    def __init__(self):
        if self is AbstractLogParser:
            raise TypeError('abstract class cannot be initialised')

    # define common methods
    def pattern_generator(self, pattern, parameter):
        type = self.type
        return type + "spam"  # whatever...

    def search_log(self, pattern, parameters, log):
        regex = self.pattern_generator(pattern, parameter)
        return regex.search(log)  # whatever


Creating a new subclass is easy:

class IISLogParser(AbstractLogParser):
    type = 'iis'



-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 17 03:28:04 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 17 Sep 2010 11:28:04 +1000
Subject: [Tutor] robots question
In-Reply-To: <7D35B5E3-0EF8-4493-9B46-E3CABF30CE18@gmail.com>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
	<7D35B5E3-0EF8-4493-9B46-E3CABF30CE18@gmail.com>
Message-ID: <201009171128.04514.steve@pearwood.info>

On Fri, 17 Sep 2010 01:57:48 am Evert Rol wrote:
> > As a exercise from this book ( Thinking like a computer scientist )
> > I have to make this programm on this
> > page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
> > Exercise 11
> >
> > #
> > # robots.py
> > #
> > from gasp import *
>
> Argh!
> Is that really in the book?
> Bad book, bad.
>
> You can just "import gasp" and type "gasp.<function>" a few times.

Settle down!

import * does have its uses. It should be considered advanced 
functionality, and people (especially beginners) should beware of 
over-using it, but there's no need to treat it as forbidden.



-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 17 03:40:49 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 17 Sep 2010 11:40:49 +1000
Subject: [Tutor] Comparing two lists
In-Reply-To: <20100916182728.GD2727@cecilia>
References: <20100916182728.GD2727@cecilia>
Message-ID: <201009171140.50283.steve@pearwood.info>

On Fri, 17 Sep 2010 04:27:28 am Michael Powe wrote:
> Hello,
>
> I have two lists.
>
> alist = ['label', 'guid']
>
> blist = ['column0label', 'column1label', 'dimension0guid',
> 'description', 'columnid']
>
> I want to iterate over blist and extract the items that match my
> substrings in alist; 

Presumably you want to get:

clist = ['column0label', 'column1label', 'dimension0guid', 'columnid']


> alternatively, throw out the items that aren't 
> in alist (but, I've had bad experiences removing items from lists "in
> place," so I tend toward the "copy" motif.)

That's almost always the best approach in Python.


> In real life, blist column entries could have embedded column numbers
> from 0 to 19.
>
> I can do this with excrutiatingly painful 'for' loops.  Looking for
> something more efficient and elegant.

Why would they be painful, let alone excruciatingly so?

clist = []
for b in blist:
    for a in alist:
        if a in b:
            clist.append(b)
            break

Okay, it's not elegant but it is concise as far as number of operations 
performed, and six lines of code isn't really that bad. There shouldn't 
be anything painful about it. It's simple to read and understand, and 
short enough that you could use it in place if necessary, although I'd 
wrap it in a function.

You can get rid of the inner for-loop:

clist = []
for b in blist:
    if any(a in b for a in alist):
        clist.append(b)

which then makes the list comp form obvious:

clist = [b for b in blist if any(a in b for a in alist)]



-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 17 03:42:14 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 17 Sep 2010 11:42:14 +1000
Subject: [Tutor] robots question
In-Reply-To: <201009171128.04514.steve@pearwood.info>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
	<7D35B5E3-0EF8-4493-9B46-E3CABF30CE18@gmail.com>
	<201009171128.04514.steve@pearwood.info>
Message-ID: <201009171142.14495.steve@pearwood.info>

On Fri, 17 Sep 2010 11:28:04 am Steven D'Aprano wrote:

> Settle down!

Sorry, that reads a bit more harshly than I intended. Please insert a 
smiley after it.

:)


-- 
Steven D'Aprano

From wallenpb at gmail.com  Fri Sep 17 04:13:33 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Thu, 16 Sep 2010 21:13:33 -0500
Subject: [Tutor] plotting pixels
Message-ID: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>

Is there a simple way to plot pixels in Python, without resorting to turtle
graphics?


--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/e5263064/attachment.html>

From prologic at shortcircuit.net.au  Fri Sep 17 04:21:57 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 17 Sep 2010 12:21:57 +1000
Subject: [Tutor] plotting pixels
In-Reply-To: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
Message-ID: <AANLkTinUhYReRckLUAojsRKMOux+nORik+f5mX3AVDjL@mail.gmail.com>

On Fri, Sep 17, 2010 at 12:13 PM, Bill Allen <wallenpb at gmail.com> wrote:
> Is there a simple way to plot pixels in Python, without resorting to turtle
> graphics?

Give matplotlib a go.

Alternatively you may want to try pygame or pyglet.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From wallenpb at gmail.com  Fri Sep 17 04:39:06 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Thu, 16 Sep 2010 21:39:06 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <AANLkTinUhYReRckLUAojsRKMOux+nORik+f5mX3AVDjL@mail.gmail.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<AANLkTinUhYReRckLUAojsRKMOux+nORik+f5mX3AVDjL@mail.gmail.com>
Message-ID: <AANLkTi=jxm9Jg-Yses8hT_yt6fJqRrbPfENiybSAZvVv@mail.gmail.com>

On Thu, Sep 16, 2010 at 9:21 PM, James Mills
<prologic at shortcircuit.net.au>wrote:

> On Fri, Sep 17, 2010 at 12:13 PM, Bill Allen <wallenpb at gmail.com> wrote:
> > Is there a simple way to plot pixels in Python, without resorting to
> turtle
> > graphics?
>
> Give matplotlib a go.
>
> Alternatively you may want to try pygame or pyglet.
>
> cheers
> James
>
> --
> -- James Mills
> --
>
Thanks!  I'll give those a try.

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100916/bc8a2ffc/attachment-0001.html>

From nblack3 at student.gsu.edu  Fri Sep 17 06:19:25 2010
From: nblack3 at student.gsu.edu (Nick)
Date: Fri, 17 Sep 2010 04:19:25 +0000
Subject: [Tutor] Scribbler Robot
Message-ID: <C5A53F581135B44E815BDEB60735CF047914@BL2PRD0103MB010.prod.exchangelabs.com>

http://www.georgiarobotics.com/roboteducation/robot-kit.html  

you can check the robot out at this link.  is this a good buy you guys think, or is there a better python compatible robot out there?  I just want something to keep me interested in programming and that gives me ideas of programs to write.  The benefit of the scribbler is also that free book online learning with robotics...  It has all kinds of sample code for programs for the scribbler.

From rwobben at hotmail.com  Fri Sep 17 09:46:23 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 17 Sep 2010 07:46:23 +0000
Subject: [Tutor] robots question
In-Reply-To: <i6ubtc$t5k$1@dough.gmane.org>
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>, ,
	<i6tfe6$r6d$1@dough.gmane.org>, ,
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>,
	<SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>,
	<i6ubtc$t5k$1@dough.gmane.org>
Message-ID: <SNT118-W3794B96EB3585F5B88E03CAE7B0@phx.gbl>


Hello, 

I changed a lot because of your suggestions.

But one thing is still a puzzle.

The robots don't move anymore.

What I have is this :

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
    # x = random.randint(0, GRID_WIDTH)
    # y = random.randint(0, GRID_HEIGHT)
    x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
    return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x, y, junk=False):
    return {'shape': Box((10*x, 10*y), 10, 10, filled = junk), 'x': x, 'y': y}


def place_robots(numbots):
    robots=[]
    # for i in range(numbots):
    #    x = random.randint(0, GRID_WIDTH)
    #    y = random.randint(0, GRID_HEIGHT)
    #    robots.append(place_robot(x, y))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk = False))
    robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = False))
    return robots

def move_player(player):
    update_when('key_pressed')
    if key_pressed('escape'):
        return True
    elif key_pressed('4'):
        if player['x'] > 0: player['x'] -= 1
    elif key_pressed('7'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('8'):
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('9'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] < GRID_HEIGHT: player['y'] += 1
    elif key_pressed('6'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
    elif key_pressed('3'):
        if player['x'] < GRID_WIDTH: player['x'] += 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('2'):
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('1'):
        if player['x'] > 0: player['x'] -= 1
        if player['y'] > 0: player['y'] -= 1
    elif key_pressed('0'):
       player['x'] = random.randint(0, GRID_WIDTH)
       player['y'] = random.randint(0, GRID_HEIGHT)
    else:
        return False

    move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

    return False

def collided(thing1, thing2):
    return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
    # check whether player has collided with anything
    for thing in robots + junk:
        if collided(thing, player):
            return True
    return False



def move_robot(robot, player):
    if robot['x'] < player['x']: robot['x'] += 1
    elif robot['x'] > player['x']: robot['x'] -= 1

    if robot['y'] < player['y']: robot['y'] += 1
    elif robot['y'] > player['y']: robot['y'] -= 1

    move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
    for robot in robots:
        move_robot(robot, player)


def play_game():
    begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
    player = place_player()
    robots = []
    place_robots(4)
    junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk=True )]
    defeated = False

    while not defeated:
        quit =  move_player(player)
        if quit:
            break
        move_robots(robots, player)
        defeated = check_collisions(robots, junk, player)

    if defeated:
        remove_from_screen(player['shape'])
        for thing in robots + junk:
            remove_from_screen(thing['shape'])
        Text("They got you!", (240, 240), size=32)
        sleep(3)

    end_graphics()



if __name__ == '__main__':
    play_game()

Roelof


> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Fri, 17 Sep 2010 01:14:32 +0100
> Subject: Re: [Tutor] robots question
> 
> 
> "Roelof Wobben" <rwobben at hotmail.com> wrote
> 
> 
> #
> # robots.py
> 
> This is pretty weird code, there are several odd things in it.
> 
> def place_player():
>     # x = random.randint(0, GRID_WIDTH)
>     # y = random.randint(0, GRID_HEIGHT)
>     x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
>     return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 
> 'y': y}
> 
> So this returns a dictionary which always contains the same data.
> 
> def place_robot(x,y, junk):
>     x = random.randint(0, GRID_WIDTH)
>     y = random.randint(0, GRID_HEIGHT)
>     return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}
> 
> This returns a similar dict but with random data.
> It ignores the values of x and y passed in and does not use junk at 
> all.
> 
> def place_robots(numbots):
>     robots = []
>     # for i in range(numbots):
>     #    x = random.randint(0, GRID_WIDTH)
>     #    y = random.randint(0, GRID_HEIGHT)
>     #    robots.append(place_robot(x, y))
>     robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, 
> junk= False))
>     robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, 
> junk = False))
>     print type(robots)
>     return robots
> 
> This returns a list of 2 dictionaries. The x,y parameters are ignored 
> by the function.
> 
> 
> def move_player(player):
>     update_when('key_pressed')
>     if key_pressed('escape'):
>         return True
>     elif key_pressed('4'): ...
>     else:
>         return False
>     move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))
>     return False
> 
> This seems OK, it returns True for escape otherwise False.
> 
> def collided(thing1, thing2):
>     return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']
> 
> This returns a boolean
> 
> 
> def check_collisions(robots, junk, player):
>     # check whether player has collided with anything
>     for thing in robots + junk:
>         if collided(thing, player):
>             return True
>     return False
> 
> Could be simplified to just
> 
> for thing in robots + junk:
>      return collided(thing, player)
> 
> It requires that robots and junk are capable of being added together
> and the result being iterable.
> 
> def move_robot(robot, player):
>     if robot['x'] < player['x']: robot['x'] += 1
>     elif robot['x'] > player['x']: robot['x'] -= 1
> 
>     if robot['y'] < player['y']: robot['y'] += 1
>     elif robot['y'] > player['y']: robot['y'] -= 1
> 
>     move_to(robot['shape'], (10*robot['x'], 10*robot['y']))
> 
> I don't see move_to so assume its part of the module you imported?
> 
> def move_robots(robots, player):
>     for robot in robots:
>         move_robot(robot, player)
> 
> ok
> 
> 
> def play_game():
>     begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
>     player = place_player()
>     robot = place_robots(4)
>     junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk="true" )]
>     robots = []
>     defeated = False
> 
> So at this point
> player is a dict
> robot is a list of 2 dicts
> junk is a list of one dict
> robots is an empty list
> 
> 
>     while not defeated:
>         quit =  move_player(player)
>         if quit:
>             break
>         move_robots(robots, player)
>         print "type robots", type(robots)
>         print "type junk", type(junk)
>         print "type player", type(player)
>         defeated = check_collisions(robots, player, junk)
> 
> You now call check_collisions passing an empty list and a dict and a 
> list of a dict
> The order in the definition is:
> 
> def check_collisions(robots, junk, player):
> 
> so it looks like you swapped the last two arguments
> 
> 
> And now Im getting this message :
> 
> ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
> ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
> <type 'list'>
> 
> Not sure where that lot came from...
> 
> type robotsTraceback (most recent call last):
>  <type 'list'>
> type junk <type 'list'>
> type player <type 'dict'>
>   File "/root/workspace/test2/src/test.py", line 125, in <module>
>     play_game()
>   File "/root/workspace/test2/src/test.py", line 111, in play_game
>     defeated = check_collisions(robots, player, junk)
>   File "/root/workspace/test2/src/test.py", line 74, in 
> check_collisions
>     for thing in robots + junk:
> TypeError: can only concatenate list (not "dict") to list
> 
> But this is valid because of the swapped arguments.
> 
> > So far I can see the problem is that player is a dict and the rest 
> > is a list.
> > Is this the correct conclusion ?
> 
> Yes, but you missed the fact that you changed the order of the 
> arguments.
> When you get type errors check the types at your interfaces(functions, 
> classes etc)
> match the definitions.
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/a0fc87aa/attachment-0001.html>

From qeg20 at cam.ac.uk  Thu Sep 16 23:24:10 2010
From: qeg20 at cam.ac.uk (Quinton Goddard)
Date: Thu, 16 Sep 2010 22:24:10 +0100
Subject: [Tutor] Bus Error with matplotlib
Message-ID: <43FAF9B6-0C84-4428-8077-D21DB74B41A6@cam.ac.uk>

Hi, I have been trying to install matplotlib for python on my mac which is running snow leopard. The installation appeared to go well until I tried the following

> python
>>> import matplotlib
>>> import matplotlib.pyplot
Bus error
>

It is very annoying, I have posted the error message below but I am not sure why it is crashing at this point! 

Many thanks for your help,

Quinton

OS Version:      Mac OS X 10.6.3 (10D575)
Report Version:  6

Interval Since Last Report:          3106 sec
Crashes Since Last Report:           21
Per-App Crashes Since Last Report:   16
Anonymous UUID:                      3FCCD611-0550-49F2-B5F4-43CD7E093033

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000000
Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
0   ???                           	0000000000 0 + 0
1   org.python.python             	0x0009da39 _PyImport_LoadDynamicModule + 204
2   org.python.python             	0x0009c09f _PyImport_FindModule + 823
3   org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
4   org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
5   org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
6   org.python.python             	0x0008578f _PyBuiltin_Init + 14665
7   org.python.python             	0x0000c6e0 PyObject_Call + 101
8   org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
9   org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
10  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
11  org.python.python             	0x0008d019 PyEval_EvalCode + 87
12  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
13  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
14  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
15  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
16  org.python.python             	0x0009d295 PyImport_ImportModuleLevel + 1167
17  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
18  org.python.python             	0x0000c6e0 PyObject_Call + 101
19  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
20  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
21  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
22  org.python.python             	0x0008d019 PyEval_EvalCode + 87
23  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
24  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
25  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
26  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
27  org.python.python             	0x0009d295 PyImport_ImportModuleLevel + 1167
28  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
29  org.python.python             	0x0000c6e0 PyObject_Call + 101
30  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
31  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
32  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
33  org.python.python             	0x0008d019 PyEval_EvalCode + 87
34  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
35  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
36  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
37  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
38  org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
39  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
40  org.python.python             	0x0000c6e0 PyObject_Call + 101
41  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
42  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
43  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
44  org.python.python             	0x0008d019 PyEval_EvalCode + 87
45  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
46  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
47  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
48  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
49  org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
50  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
51  org.python.python             	0x0000c6e0 PyObject_Call + 101
52  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
53  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
54  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
55  org.python.python             	0x0008d019 PyEval_EvalCode + 87
56  org.python.python             	0x000a40af Py_CompileString + 111
57  org.python.python             	0x000a6134 PyRun_InteractiveOneFlags + 483
58  org.python.python             	0x000a6282 PyRun_InteractiveLoopFlags + 216
59  org.python.python             	0x000a630b PyRun_AnyFileExFlags + 85
60  org.python.python             	0x000b315c Py_Main + 3074
61  org.python.python.app         	0x00001eb5 start + 53

Thread 0 crashed with X86 Thread State (32-bit):
  eax: 0x0067e420  ebx: 0x0112b7d6  ecx: 0x00607480  edx: 0x0067e420
  edi: 0x00169cf8  esi: 0x005fd430  ebp: 0xbfff9cf8  esp: 0xbfff9ccc
   ss: 0x0000001f  efl: 0x00010246  eip: 0x00000000   cs: 0x00000017
   ds: 0x0000001f   es: 0x0000001f   fs: 0x00000000   gs: 0x00000037
  cr2: 0x00000000

Binary Images:
    0x1000 -     0x1ff7  org.python.python.app 2.6 (2.6) <3988BDB2-24F5-3751-9F9D-4E212DA5711D> /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
    0x5000 -    0xecfef  org.python.python 2.6.1 (2.6.1) <3AB40053-E1C2-4B9E-D587-7D66895DA529> /System/Library/Frameworks/Python.framework/Versions/2.6/Python
  0x1df000 -   0x1e0ff7  readline.so ??? (???) <BA680530-51E6-E2E5-462D-36309F511D6A> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/readline.so
  0x1e5000 -   0x1e6ff7  time.so ??? (???) <4E4350A6-4C5E-8670-C32E-F220447B8F1D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/time.so
  0x1ed000 -   0x1efff7  select.so ??? (???) <3DC11479-CB30-8D7D-9AE9-FF487D78719D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/select.so
  0x1f4000 -   0x1f5ff7  fcntl.so ??? (???) <5F44F901-1697-0CEF-E769-028A4217F9FB> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/fcntl.so
  0x1f9000 -   0x1fbfe7  binascii.so ??? (???) <DFE1DF4A-F41F-A8D4-FADB-3EFFE800EC37> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/binascii.so
  0x400000 -   0x417fe7  libedit.2.dylib 2.11.0 (compatibility 2.0.0) <45688CB7-9BE4-5D1B-C209-A414EE98C5D2> /usr/lib/libedit.2.dylib
  0x464000 -   0x467ff7  _struct.so ??? (???) <176DAD3C-8E60-620D-81F5-EB5D27D57F69> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_struct.so
  0x46d000 -   0x46eff7  cStringIO.so ??? (???) <64A8EC11-C5D1-6E73-B59F-9A491237A23D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/cStringIO.so
  0x472000 -   0x474ff7  strop.so ??? (???) <8F7684CD-789D-E6F8-64D7-99A33B8D9318> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/strop.so
  0x4b9000 -   0x4bbff7  math.so ??? (???) <3891D857-214A-8798-B736-819432EB84A3> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/math.so
  0x4c0000 -   0x4c1ff7  _random.so ??? (???) <7F4EA908-81B3-776A-F958-6D130B24379F> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_random.so
  0x529000 -   0x529ff7  _weakref.so ??? (???) <8E7902C2-4ADB-D16B-A0F7-C94D0F512ED4> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_weakref.so
  0x52d000 -   0x52fff7  _collections.so ??? (???) <FA9F805B-7D3B-F044-E952-2DA639189D6B> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_collections.so
  0x534000 -   0x537ff7  operator.so ??? (???) <00481461-D3D4-6EF8-A241-18482D968A08> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/operator.so
  0x57c000 -   0x582ff7  _socket.so ??? (???) <7C6162A9-6CAF-BAC8-8B53-7B85212AB590> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_socket.so
  0x589000 -   0x58cff7  _ssl.so ??? (???) <088DED4E-B311-94AE-673D-FC173026655C> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_ssl.so
  0x632000 -   0x67dfe7  multiarray.so ??? (???) <50C2A00A-3580-6447-7996-D2D14F193B24> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/multiarray.so
  0x68b000 -   0x6b4ff7  umath.so ??? (???) <CA03C867-A230-6A4B-0780-5782457925E1> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/umath.so
  0x6be000 -   0x6caff7  _sort.so ??? (???) <668A5C9F-8010-6116-D61D-C6681D82095B> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/_sort.so
  0x6ce000 -   0x6d1ff7  _dotblas.so ??? (???) <22EE39DF-8ADE-E3D4-513B-56DEF5C67445> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/_dotblas.so
  0x6d5000 -   0x6e0ff7  cPickle.so ??? (???) <A3480F0F-FE1B-4418-15B8-1F45F3233DA0> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/cPickle.so
  0x726000 -   0x73cff7  scalarmath.so ??? (???) <3E96A1D4-767B-288E-F2BC-7EE061980362> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/scalarmath.so
  0x780000 -   0x782ff7  _compiled_base.so ??? (???) <9B71A0D7-8CE1-34CA-CF23-39AFE76DA804> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/lib/_compiled_base.so
  0x786000 -   0x78aff7  itertools.so ??? (???) <9D9D4B35-BE7F-8A56-F452-57DFA4AE18F8> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so
  0x791000 -   0x794ff7  lapack_lite.so ??? (???) <6B0A9764-9AE7-7663-EB28-A0526E4AE2AF> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/linalg/lapack_lite.so
  0x798000 -   0x7a1ff7  fftpack_lite.so ??? (???) <04E48656-49F3-BD1C-BCE7-A6F30B07F063> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/fft/fftpack_lite.so
  0x7a5000 -   0x7cafe7  mtrand.so ??? (???) <D3C90661-48DE-01D9-45DC-77F0998FB37F> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/random/mtrand.so
  0x7e0000 -   0x7efff7  _ctypes.so ??? (???) <B6BF055E-60EA-4640-98CB-D783D9572938> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_ctypes.so
  0x7f8000 -   0x7f8ff7  _functools.so ??? (???) <9B2AECA3-38C5-E4E3-647C-C67CFE35F320> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_functools.so
  0x7fc000 -   0x7fcff7  _bisect.so ??? (???) <6D2C7E9B-FDA6-87DF-6C0B-16CD7F552347> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_bisect.so
 0x1080000 -  0x1081ff7  _locale.so ??? (???) <A4E4DED9-4011-B581-98C0-E43715CBB36E> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_locale.so
 0x1085000 -  0x108efe7  datetime.so ??? (???) <E2DA53DF-7A59-FD08-5F1A-070B2C41A059> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/datetime.so
 0x1096000 -  0x1097ff7  _hashlib.so ??? (???) <D88753D0-E78F-0F62-DCF5-364D4F54E5BD> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_hashlib.so
 0x111b000 -  0x1141ff3 +_path.so ??? (???) <96E0FC98-87B0-889D-6BD8-1E0A61137D36> /Library/Python/2.6/site-packages/matplotlib/_path.so
0x8fe00000 - 0x8fe4162b  dyld 132.1 (???) <5C229EB2-F7CA-A638-41B6-5755DE940108> /usr/lib/dyld
0x90051000 - 0x90084ff7  libncurses.5.4.dylib 5.4.0 (compatibility 5.4.0) <4014E921-F04E-09BB-4CDA-1527B1C850AB> /usr/lib/libncurses.5.4.dylib
0x91603000 - 0x91604ff7  com.apple.TrustEvaluationAgent 1.1 (1) <FEB55E8C-38A4-CFE9-A737-945F39761B4C> /System/Library/PrivateFrameworks/TrustEvaluationAgent.framework/Versions/A/TrustEvaluationAgent
0x9209f000 - 0x92191ff7  libcrypto.0.9.8.dylib 0.9.8 (compatibility 0.9.8) <7482933B-4AF6-ED55-AD72-4FBD1E134958> /usr/lib/libcrypto.0.9.8.dylib
0x92523000 - 0x92531fe7  libz.1.dylib 1.2.3 (compatibility 1.0.0) <82B2C254-6F8D-7BEA-4C18-038E90CAE19B> /usr/lib/libz.1.dylib
0x925a1000 - 0x925a1ff7  com.apple.vecLib 3.6 (vecLib 3.6) <7362077A-890F-3AEF-A8AB-22247B10E106> /System/Library/Frameworks/vecLib.framework/Versions/A/vecLib
0x9307a000 - 0x93127fe7  libobjc.A.dylib 227.0.0 (compatibility 1.0.0) <DF8E4CFA-3719-3415-0BF1-E8C5E561C3B1> /usr/lib/libobjc.A.dylib
0x93772000 - 0x938ebffb  com.apple.CoreFoundation 6.6.1 (550.19) <1E97FB1E-9E42-B8EB-E463-5C75315FDA31> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
0x93dfb000 - 0x93fa0feb  libSystem.B.dylib 125.0.1 (compatibility 1.0.0) <06A5336A-A6F6-4E62-F55F-4909A64631C2> /usr/lib/libSystem.B.dylib
0x93fc0000 - 0x93fc0ff7  com.apple.Accelerate 1.6 (Accelerate 1.6) <BC501C9F-7C20-961A-B135-0A457667D03C> /System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate
0x943b3000 - 0x943f9ff7  libauto.dylib ??? (???) <85670A64-3B67-8162-D441-D8E0BE15CA94> /usr/lib/libauto.dylib
0x94409000 - 0x94473fe7  libstdc++.6.dylib 7.9.0 (compatibility 7.0.0) <411D87F4-B7E1-44EB-F201-F8B4F9227213> /usr/lib/libstdc++.6.dylib
0x94794000 - 0x94794ff7  com.apple.Accelerate.vecLib 3.6 (vecLib 3.6) <1DEC639C-173D-F808-DE0D-4070CC6F5BC7> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/vecLib
0x953cc000 - 0x9540eff7  libvDSP.dylib 268.0.1 (compatibility 1.0.0) <3F0ED200-741B-4E27-B89F-634B131F5E9E> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvDSP.dylib
0x955a3000 - 0x955a3ffb  libffi.dylib ??? (???) <58985323-6EC6-9AD2-B9F0-8787C0B2791C> /usr/lib/libffi.dylib
0x955a4000 - 0x95613ff7  libvMisc.dylib 268.0.1 (compatibility 1.0.0) <2FC2178F-FEF9-6E3F-3289-A6307B1A154C> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvMisc.dylib
0x95614000 - 0x95a2aff7  libBLAS.dylib 219.0.0 (compatibility 1.0.0) <C4FB303A-DB4D-F9E8-181C-129585E59603> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
0x95bde000 - 0x96013ff7  libLAPACK.dylib 219.0.0 (compatibility 1.0.0) <5E2D2283-57DE-9A49-1DB0-CD027FEFA6C2> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib
0x9727e000 - 0x97400fe7  libicucore.A.dylib 40.0.0 (compatibility 1.0.0) <96A45E03-2B29-83EB-0FC6-2C932E398722> /usr/lib/libicucore.A.dylib
0x97710000 - 0x977edff7  com.apple.vImage 4.0 (4.0) <64597E4B-F144-DBB3-F428-0EC3D9A1219E> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/vImage
0x978f9000 - 0x978fcfe7  libmathCommon.A.dylib 315.0.0 (compatibility 1.0.0) <1622A54F-1A98-2CBE-B6A4-2122981A500E> /usr/lib/system/libmathCommon.A.dylib
0x994cc000 - 0x99500ff7  libssl.0.9.8.dylib 0.9.8 (compatibility 0.9.8) <5FEC74CA-1D3C-B6E3-E046-3970095C44BC> /usr/lib/libssl.0.9.8.dylib
0xffff0000 - 0xffff1fff  libSystem.B.dylib ??? (???) <06A5336A-A6F6-4E62-F55F-4909A64631C2> /usr/lib/libSystem.B.dylib

Model: MacBook1,1, BootROM MB11.0061.B03, 2 processors, Intel Core Duo, 2 GHz, 1 GB, SMC 1.4f12
Graphics: Intel GMA 950, GMA 950, Built-In, spdisplays_integrated_vram
Memory Module: global_name
AirPort: spairport_wireless_card_type_airport_extreme (0x168C, 0x86), Atheros 5424: 2.0.19.10
Bluetooth: Version 2.3.1f4, 2 service, 19 devices, 1 incoming serial ports
Network Service: AirPort, AirPort, en1
Serial ATA Device: TOSHIBA MK8032GSX, 74.53 GB
Parallel ATA Device: MATSHITADVD-R   UJ-857, 7.54 GB
USB Device: Built-in iSight, 0x05ac  (Apple Inc.), 0x8501, 0xfd400000
USB Device: Apple Internal Keyboard / Trackpad, 0x05ac  (Apple Inc.), 0x0218, 0x1d200000
USB Device: Composite Device, 0x0430, 0x0100, 0x3d100000
USB Device: IR Receiver, 0x05ac  (Apple Inc.), 0x8240, 0x5d200000
USB Device: Bluetooth USB Host Controller, 0x05ac  (Apple Inc.), 0x8205, 0x7d100000






From evert.rol at gmail.com  Fri Sep 17 10:17:23 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Fri, 17 Sep 2010 10:17:23 +0200
Subject: [Tutor] Bus Error with matplotlib
In-Reply-To: <43FAF9B6-0C84-4428-8077-D21DB74B41A6@cam.ac.uk>
References: <43FAF9B6-0C84-4428-8077-D21DB74B41A6@cam.ac.uk>
Message-ID: <6229E67B-774E-4620-99BB-29D9B0EFBE31@gmail.com>

> Hi, I have been trying to install matplotlib for python on my mac which is running snow leopard. The installation appeared to go well until I tried the following
> 
>> python
>>>> import matplotlib
>>>> import matplotlib.pyplot
> Bus error
>> 
> 
> It is very annoying, I have posted the error message below but I am not sure why it is crashing at this point! 

This is really not a tutor question; you'd be better off checking on the matplotlib user group.

However:
- what version of matplotlib are you installing? 1.0 I assume?
- how are you installing matplotlib? Mac OS X binary (which one; there seem to be multiple options) or differently?
- have you tried installing from source? If you're not used to that, it can be a harsh exercise, but can at times result in working results

Btw, you're OS X version seems to run a bit behind: 10.6.4 is current. I don't expect it to let matplotlib work, but one never knows.

  Evert

> 
> Many thanks for your help,
> 
> Quinton
> 
> OS Version:      Mac OS X 10.6.3 (10D575)
> Report Version:  6
> 
> Interval Since Last Report:          3106 sec
> Crashes Since Last Report:           21
> Per-App Crashes Since Last Report:   16
> Anonymous UUID:                      3FCCD611-0550-49F2-B5F4-43CD7E093033
> 
> Exception Type:  EXC_BAD_ACCESS (SIGBUS)
> Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000000
> Crashed Thread:  0  Dispatch queue: com.apple.main-thread
> 
> Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
> 0   ???                           	0000000000 0 + 0
> 1   org.python.python             	0x0009da39 _PyImport_LoadDynamicModule + 204
> 2   org.python.python             	0x0009c09f _PyImport_FindModule + 823
> 3   org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
> 4   org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
> 5   org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
> 6   org.python.python             	0x0008578f _PyBuiltin_Init + 14665
> 7   org.python.python             	0x0000c6e0 PyObject_Call + 101
> 8   org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
> 9   org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
> 10  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
> 11  org.python.python             	0x0008d019 PyEval_EvalCode + 87
> 12  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
> 13  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
> 14  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
> 15  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
> 16  org.python.python             	0x0009d295 PyImport_ImportModuleLevel + 1167
> 17  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
> 18  org.python.python             	0x0000c6e0 PyObject_Call + 101
> 19  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
> 20  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
> 21  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
> 22  org.python.python             	0x0008d019 PyEval_EvalCode + 87
> 23  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
> 24  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
> 25  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
> 26  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
> 27  org.python.python             	0x0009d295 PyImport_ImportModuleLevel + 1167
> 28  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
> 29  org.python.python             	0x0000c6e0 PyObject_Call + 101
> 30  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
> 31  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
> 32  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
> 33  org.python.python             	0x0008d019 PyEval_EvalCode + 87
> 34  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
> 35  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
> 36  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
> 37  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
> 38  org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
> 39  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
> 40  org.python.python             	0x0000c6e0 PyObject_Call + 101
> 41  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
> 42  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
> 43  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
> 44  org.python.python             	0x0008d019 PyEval_EvalCode + 87
> 45  org.python.python             	0x0009a542 PyImport_ExecCodeModuleEx + 240
> 46  org.python.python             	0x0009af3a PyImport_AppendInittab + 1164
> 47  org.python.python             	0x0009c88f PyImport_ReloadModule + 1392
> 48  org.python.python             	0x0009cce7 PyImport_ReloadModule + 2504
> 49  org.python.python             	0x0009d2cb PyImport_ImportModuleLevel + 1221
> 50  org.python.python             	0x0008578f _PyBuiltin_Init + 14665
> 51  org.python.python             	0x0000c6e0 PyObject_Call + 101
> 52  org.python.python             	0x0008678a PyEval_CallObjectWithKeywords + 171
> 53  org.python.python             	0x0008a758 PyEval_EvalFrameEx + 13261
> 54  org.python.python             	0x0008cf74 PyEval_EvalCodeEx + 1720
> 55  org.python.python             	0x0008d019 PyEval_EvalCode + 87
> 56  org.python.python             	0x000a40af Py_CompileString + 111
> 57  org.python.python             	0x000a6134 PyRun_InteractiveOneFlags + 483
> 58  org.python.python             	0x000a6282 PyRun_InteractiveLoopFlags + 216
> 59  org.python.python             	0x000a630b PyRun_AnyFileExFlags + 85
> 60  org.python.python             	0x000b315c Py_Main + 3074
> 61  org.python.python.app         	0x00001eb5 start + 53
> 
> Thread 0 crashed with X86 Thread State (32-bit):
>  eax: 0x0067e420  ebx: 0x0112b7d6  ecx: 0x00607480  edx: 0x0067e420
>  edi: 0x00169cf8  esi: 0x005fd430  ebp: 0xbfff9cf8  esp: 0xbfff9ccc
>   ss: 0x0000001f  efl: 0x00010246  eip: 0x00000000   cs: 0x00000017
>   ds: 0x0000001f   es: 0x0000001f   fs: 0x00000000   gs: 0x00000037
>  cr2: 0x00000000
> 
> Binary Images:
>    0x1000 -     0x1ff7  org.python.python.app 2.6 (2.6) <3988BDB2-24F5-3751-9F9D-4E212DA5711D> /System/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python
>    0x5000 -    0xecfef  org.python.python 2.6.1 (2.6.1) <3AB40053-E1C2-4B9E-D587-7D66895DA529> /System/Library/Frameworks/Python.framework/Versions/2.6/Python
>  0x1df000 -   0x1e0ff7  readline.so ??? (???) <BA680530-51E6-E2E5-462D-36309F511D6A> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/readline.so
>  0x1e5000 -   0x1e6ff7  time.so ??? (???) <4E4350A6-4C5E-8670-C32E-F220447B8F1D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/time.so
>  0x1ed000 -   0x1efff7  select.so ??? (???) <3DC11479-CB30-8D7D-9AE9-FF487D78719D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/select.so
>  0x1f4000 -   0x1f5ff7  fcntl.so ??? (???) <5F44F901-1697-0CEF-E769-028A4217F9FB> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/fcntl.so
>  0x1f9000 -   0x1fbfe7  binascii.so ??? (???) <DFE1DF4A-F41F-A8D4-FADB-3EFFE800EC37> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/binascii.so
>  0x400000 -   0x417fe7  libedit.2.dylib 2.11.0 (compatibility 2.0.0) <45688CB7-9BE4-5D1B-C209-A414EE98C5D2> /usr/lib/libedit.2.dylib
>  0x464000 -   0x467ff7  _struct.so ??? (???) <176DAD3C-8E60-620D-81F5-EB5D27D57F69> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_struct.so
>  0x46d000 -   0x46eff7  cStringIO.so ??? (???) <64A8EC11-C5D1-6E73-B59F-9A491237A23D> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/cStringIO.so
>  0x472000 -   0x474ff7  strop.so ??? (???) <8F7684CD-789D-E6F8-64D7-99A33B8D9318> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/strop.so
>  0x4b9000 -   0x4bbff7  math.so ??? (???) <3891D857-214A-8798-B736-819432EB84A3> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/math.so
>  0x4c0000 -   0x4c1ff7  _random.so ??? (???) <7F4EA908-81B3-776A-F958-6D130B24379F> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_random.so
>  0x529000 -   0x529ff7  _weakref.so ??? (???) <8E7902C2-4ADB-D16B-A0F7-C94D0F512ED4> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_weakref.so
>  0x52d000 -   0x52fff7  _collections.so ??? (???) <FA9F805B-7D3B-F044-E952-2DA639189D6B> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_collections.so
>  0x534000 -   0x537ff7  operator.so ??? (???) <00481461-D3D4-6EF8-A241-18482D968A08> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/operator.so
>  0x57c000 -   0x582ff7  _socket.so ??? (???) <7C6162A9-6CAF-BAC8-8B53-7B85212AB590> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_socket.so
>  0x589000 -   0x58cff7  _ssl.so ??? (???) <088DED4E-B311-94AE-673D-FC173026655C> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_ssl.so
>  0x632000 -   0x67dfe7  multiarray.so ??? (???) <50C2A00A-3580-6447-7996-D2D14F193B24> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/multiarray.so
>  0x68b000 -   0x6b4ff7  umath.so ??? (???) <CA03C867-A230-6A4B-0780-5782457925E1> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/umath.so
>  0x6be000 -   0x6caff7  _sort.so ??? (???) <668A5C9F-8010-6116-D61D-C6681D82095B> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/_sort.so
>  0x6ce000 -   0x6d1ff7  _dotblas.so ??? (???) <22EE39DF-8ADE-E3D4-513B-56DEF5C67445> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/_dotblas.so
>  0x6d5000 -   0x6e0ff7  cPickle.so ??? (???) <A3480F0F-FE1B-4418-15B8-1F45F3233DA0> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/cPickle.so
>  0x726000 -   0x73cff7  scalarmath.so ??? (???) <3E96A1D4-767B-288E-F2BC-7EE061980362> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/core/scalarmath.so
>  0x780000 -   0x782ff7  _compiled_base.so ??? (???) <9B71A0D7-8CE1-34CA-CF23-39AFE76DA804> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/lib/_compiled_base.so
>  0x786000 -   0x78aff7  itertools.so ??? (???) <9D9D4B35-BE7F-8A56-F452-57DFA4AE18F8> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/itertools.so
>  0x791000 -   0x794ff7  lapack_lite.so ??? (???) <6B0A9764-9AE7-7663-EB28-A0526E4AE2AF> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/linalg/lapack_lite.so
>  0x798000 -   0x7a1ff7  fftpack_lite.so ??? (???) <04E48656-49F3-BD1C-BCE7-A6F30B07F063> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/fft/fftpack_lite.so
>  0x7a5000 -   0x7cafe7  mtrand.so ??? (???) <D3C90661-48DE-01D9-45DC-77F0998FB37F> /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/numpy/random/mtrand.so
>  0x7e0000 -   0x7efff7  _ctypes.so ??? (???) <B6BF055E-60EA-4640-98CB-D783D9572938> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_ctypes.so
>  0x7f8000 -   0x7f8ff7  _functools.so ??? (???) <9B2AECA3-38C5-E4E3-647C-C67CFE35F320> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_functools.so
>  0x7fc000 -   0x7fcff7  _bisect.so ??? (???) <6D2C7E9B-FDA6-87DF-6C0B-16CD7F552347> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_bisect.so
> 0x1080000 -  0x1081ff7  _locale.so ??? (???) <A4E4DED9-4011-B581-98C0-E43715CBB36E> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_locale.so
> 0x1085000 -  0x108efe7  datetime.so ??? (???) <E2DA53DF-7A59-FD08-5F1A-070B2C41A059> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/datetime.so
> 0x1096000 -  0x1097ff7  _hashlib.so ??? (???) <D88753D0-E78F-0F62-DCF5-364D4F54E5BD> /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/_hashlib.so
> 0x111b000 -  0x1141ff3 +_path.so ??? (???) <96E0FC98-87B0-889D-6BD8-1E0A61137D36> /Library/Python/2.6/site-packages/matplotlib/_path.so
> 0x8fe00000 - 0x8fe4162b  dyld 132.1 (???) <5C229EB2-F7CA-A638-41B6-5755DE940108> /usr/lib/dyld
> 0x90051000 - 0x90084ff7  libncurses.5.4.dylib 5.4.0 (compatibility 5.4.0) <4014E921-F04E-09BB-4CDA-1527B1C850AB> /usr/lib/libncurses.5.4.dylib
> 0x91603000 - 0x91604ff7  com.apple.TrustEvaluationAgent 1.1 (1) <FEB55E8C-38A4-CFE9-A737-945F39761B4C> /System/Library/PrivateFrameworks/TrustEvaluationAgent.framework/Versions/A/TrustEvaluationAgent
> 0x9209f000 - 0x92191ff7  libcrypto.0.9.8.dylib 0.9.8 (compatibility 0.9.8) <7482933B-4AF6-ED55-AD72-4FBD1E134958> /usr/lib/libcrypto.0.9.8.dylib
> 0x92523000 - 0x92531fe7  libz.1.dylib 1.2.3 (compatibility 1.0.0) <82B2C254-6F8D-7BEA-4C18-038E90CAE19B> /usr/lib/libz.1.dylib
> 0x925a1000 - 0x925a1ff7  com.apple.vecLib 3.6 (vecLib 3.6) <7362077A-890F-3AEF-A8AB-22247B10E106> /System/Library/Frameworks/vecLib.framework/Versions/A/vecLib
> 0x9307a000 - 0x93127fe7  libobjc.A.dylib 227.0.0 (compatibility 1.0.0) <DF8E4CFA-3719-3415-0BF1-E8C5E561C3B1> /usr/lib/libobjc.A.dylib
> 0x93772000 - 0x938ebffb  com.apple.CoreFoundation 6.6.1 (550.19) <1E97FB1E-9E42-B8EB-E463-5C75315FDA31> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
> 0x93dfb000 - 0x93fa0feb  libSystem.B.dylib 125.0.1 (compatibility 1.0.0) <06A5336A-A6F6-4E62-F55F-4909A64631C2> /usr/lib/libSystem.B.dylib
> 0x93fc0000 - 0x93fc0ff7  com.apple.Accelerate 1.6 (Accelerate 1.6) <BC501C9F-7C20-961A-B135-0A457667D03C> /System/Library/Frameworks/Accelerate.framework/Versions/A/Accelerate
> 0x943b3000 - 0x943f9ff7  libauto.dylib ??? (???) <85670A64-3B67-8162-D441-D8E0BE15CA94> /usr/lib/libauto.dylib
> 0x94409000 - 0x94473fe7  libstdc++.6.dylib 7.9.0 (compatibility 7.0.0) <411D87F4-B7E1-44EB-F201-F8B4F9227213> /usr/lib/libstdc++.6.dylib
> 0x94794000 - 0x94794ff7  com.apple.Accelerate.vecLib 3.6 (vecLib 3.6) <1DEC639C-173D-F808-DE0D-4070CC6F5BC7> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/vecLib
> 0x953cc000 - 0x9540eff7  libvDSP.dylib 268.0.1 (compatibility 1.0.0) <3F0ED200-741B-4E27-B89F-634B131F5E9E> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvDSP.dylib
> 0x955a3000 - 0x955a3ffb  libffi.dylib ??? (???) <58985323-6EC6-9AD2-B9F0-8787C0B2791C> /usr/lib/libffi.dylib
> 0x955a4000 - 0x95613ff7  libvMisc.dylib 268.0.1 (compatibility 1.0.0) <2FC2178F-FEF9-6E3F-3289-A6307B1A154C> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libvMisc.dylib
> 0x95614000 - 0x95a2aff7  libBLAS.dylib 219.0.0 (compatibility 1.0.0) <C4FB303A-DB4D-F9E8-181C-129585E59603> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
> 0x95bde000 - 0x96013ff7  libLAPACK.dylib 219.0.0 (compatibility 1.0.0) <5E2D2283-57DE-9A49-1DB0-CD027FEFA6C2> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libLAPACK.dylib
> 0x9727e000 - 0x97400fe7  libicucore.A.dylib 40.0.0 (compatibility 1.0.0) <96A45E03-2B29-83EB-0FC6-2C932E398722> /usr/lib/libicucore.A.dylib
> 0x97710000 - 0x977edff7  com.apple.vImage 4.0 (4.0) <64597E4B-F144-DBB3-F428-0EC3D9A1219E> /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vImage.framework/Versions/A/vImage
> 0x978f9000 - 0x978fcfe7  libmathCommon.A.dylib 315.0.0 (compatibility 1.0.0) <1622A54F-1A98-2CBE-B6A4-2122981A500E> /usr/lib/system/libmathCommon.A.dylib
> 0x994cc000 - 0x99500ff7  libssl.0.9.8.dylib 0.9.8 (compatibility 0.9.8) <5FEC74CA-1D3C-B6E3-E046-3970095C44BC> /usr/lib/libssl.0.9.8.dylib
> 0xffff0000 - 0xffff1fff  libSystem.B.dylib ??? (???) <06A5336A-A6F6-4E62-F55F-4909A64631C2> /usr/lib/libSystem.B.dylib
> 
> Model: MacBook1,1, BootROM MB11.0061.B03, 2 processors, Intel Core Duo, 2 GHz, 1 GB, SMC 1.4f12
> Graphics: Intel GMA 950, GMA 950, Built-In, spdisplays_integrated_vram
> Memory Module: global_name
> AirPort: spairport_wireless_card_type_airport_extreme (0x168C, 0x86), Atheros 5424: 2.0.19.10
> Bluetooth: Version 2.3.1f4, 2 service, 19 devices, 1 incoming serial ports
> Network Service: AirPort, AirPort, en1
> Serial ATA Device: TOSHIBA MK8032GSX, 74.53 GB
> Parallel ATA Device: MATSHITADVD-R   UJ-857, 7.54 GB
> USB Device: Built-in iSight, 0x05ac  (Apple Inc.), 0x8501, 0xfd400000
> USB Device: Apple Internal Keyboard / Trackpad, 0x05ac  (Apple Inc.), 0x0218, 0x1d200000
> USB Device: Composite Device, 0x0430, 0x0100, 0x3d100000
> USB Device: IR Receiver, 0x05ac  (Apple Inc.), 0x8240, 0x5d200000
> USB Device: Bluetooth USB Host Controller, 0x05ac  (Apple Inc.), 0x8205, 0x7d100000
> 
> 
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Fri Sep 17 10:38:07 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 Sep 2010 09:38:07 +0100
Subject: [Tutor] plotting pixels
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
Message-ID: <i6v9dk$rhf$1@dough.gmane.org>


"Bill Allen" <wallenpb at gmail.com> wrote

> Is there a simple way to plot pixels in Python, without resorting to 
> turtle
> graphics?

James already mentioned matplotlib but you can just draw on a canvas.
It depends on what you are trying to do.

For plotting pixels I would not use turtle graphics.
That would be a fairly complicated option I'd have thought.
A simple canvas would be easier.

Alan G. 



From jojo.mwebaze at gmail.com  Fri Sep 17 10:55:28 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Fri, 17 Sep 2010 10:55:28 +0200
Subject: [Tutor] intercepting and recored I/O function calls
In-Reply-To: <alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
	<i6reb1$h7l$1@dough.gmane.org>
	<AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
	<alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>
Message-ID: <AANLkTimikH+vo9sFA=jOpBU1suHMPbGp-GvTP9joHgcA@mail.gmail.com>

Thanks Martin, for the detailed break down, it actually helped me solve one
of my other problems..

My applogies to begin with,  it seems i didnt state my problem clearly for
this particular case - perharps I/O was not the best way to describe my
problem.

We have a system fully developed in python- with thousands of lines of code-
i know i can use the logging facilty for this task, but this means i have to
go into the code and edit it to log specifics of what i need, this is gone
take a while and this also implies all other users adding modules must
include logging statements..

Specifically, i would like to track all inputs/output to modules/functions -
if a module  retrieved and used files and run some analysis on them and
produced other files in return, i would like to take not of this. i.e what i
want is to recored input and outputs to a module. and also to record all
paramaters, attribute vaules used by the same module.

I thought i would build a wrapper around the orignial python program or
probably pick this information at OS level.

Sorry for the confusion..

Jojo


On Fri, Sep 17, 2010 at 12:45 AM, Martin A. Brown <martin at linux-ip.net>wrote:

>
> [apologies in advance for an answer that is partially off topic]
>
> Hi there JoJo,
>
>  : I could begin with tracing I/O calls in my App.. if its
>  : sufficient enough i may not need i/o calls for the OS.
>
> What do you suspect?  Filesystem I/O?
>
>  * open(), close(), opendir() closedir() filesystem latency?
>  * read(), write() latency?
>  * low read() and write() throughput?
>
> Network I/O?
>
>  * Are name lookups taking a long time?
>  * Do you have slow network throughput?  (Consider tcpdump.)
>
> Rather than writing code (at first glance), why not use a system
> call profiler to check this out.  It is very unlikely that python
> itself is the problem.  Could it be the filesystem/network?  Could
> it be DNS?  A system call profiler can help you find this.
>
> Are you asking this because you plan on diagnosing I/O performance
> issues in your application?  Is this a one time thing in a
> production environment that is sensitive to application latency?
> If so, you might try tickling the application and attaching to the
> process with a system call tracer.  Under CentOS you should be able
> to install 'strace'.  If you can run the proggie on the command
> line:
>
>  strace -o /tmp/trace-output-file.txt -f python yourscript.py args
>
> Then, go learn how to read the /tmp/trace-output-file.txt.
>
> Suggested options:
>
>  -f        follow children
>  -ttt      sane Unix-y timestamps
>  -T        total time spent in each system call
>  -s 256    256 byte limit on string output (default is 32)
>  -o file   store trace data in a file
>  -p pid    attach to running process of pid
>  -c        only show a summary of cumulative time per system call
>
>  : > But this is extremely dependant on the Operating System - you will
>  : > basically have to intercept the system calls. So, which OS are
>  : > you using?  And how familiar are you with its API?
>  :
>  : I am using centos, however i don't even have admin privileges.
>  : Which API are you referring to?
>
> You shouldn't need admin privileges if you can run the program as
> yourself.  If you have setuid/setgid bits, then you will need
> somebody with administrative privileges to help you.
>
> OK, so let's say that you have already done this and understand all
> of the above, you know it's not the system and you really want to
> understand where your application is susceptible to bad performance
> or I/O issues.  Now, we're back to python land.
>
>  * look at the profile module
>    http://docs.python.org/library/profile.html
>
>  * instrument your application by using the logging module
>    http://docs.python.org/library/logging.html
>
> You might ask how it is a benefit to use the logging module.  Well,
> if your program generates logging data (let's say to STDERR) and you
> do not include timestamps on each log line, you can trivially add
> timestamps to the logging data using your system's logging
> facilities:
>
>  { python thingy.py >/dev/null ; } 2>&1 | logger -ist 'thingy.py' --
>
> Or, if you like DJB tools:
>
>  { python thingy.py >/dev/null ; } 2>&1 | multilog t ./directory/
>
> Either of which solution leaves you (implicitly) with timing
> information.
>
>  : > Also, While you can probably do this in Python but its likely
>  : > to have a serious impact on the OS performance, it will slow
>  : > down the performamce quite noticeably. I'd normally recommend
>  : > using C for something like this.
>
> Alan's admonition bears repeating.  Trapping all application I/O is
> probably just fine for development, instrumenting and diagnosing,
> but you may wish to support that in an easily removable manner,
> especially if performance is paramount.
>
> Good luck,
>
> -Martin
>
> --
> Martin A. Brown
> http://linux-ip.net/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/abef7828/attachment.html>

From __peter__ at web.de  Fri Sep 17 11:49:46 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 17 Sep 2010 11:49:46 +0200
Subject: [Tutor] robots question
References: <SNT118-W25212DA1B84305A6282D2BAE7A0@phx.gbl>
	<i6tfe6$r6d$1@dough.gmane.org>
	<SNT118-W7983F9B500C7B8B6AC69DAE7A0@phx.gbl>
	<SNT118-W324FACE4D7AFE2D9458706AE7A0@phx.gbl>
	<i6ubtc$t5k$1@dough.gmane.org>
	<SNT118-W3794B96EB3585F5B88E03CAE7B0@phx.gbl>
Message-ID: <i6vdgr$cv8$1@dough.gmane.org>

Roelof Wobben wrote:

> I changed a lot because of your suggestions.
> But one thing is still a puzzle.
> The robots don't move anymore.
> 
> What I have is this :

>     robots = []
>     place_robots(4)

>         move_robots(robots, player)

You are only moving the robots in the 'robots' list. But that list is empty.

Peter


From vceder at canterburyschool.org  Fri Sep 17 12:32:43 2010
From: vceder at canterburyschool.org (Vern Ceder)
Date: Fri, 17 Sep 2010 06:32:43 -0400
Subject: [Tutor] Scribbler Robot
In-Reply-To: <C5A53F581135B44E815BDEB60735CF047914@BL2PRD0103MB010.prod.exchangelabs.com>
References: <C5A53F581135B44E815BDEB60735CF047914@BL2PRD0103MB010.prod.exchangelabs.com>
Message-ID: <AANLkTikvyVVPHLngf=uToLtNa=0LBC_K1ihQEJ+_R6vQ@mail.gmail.com>

We're using the scribblers in our intro to Python programming class, and I'm
pretty happy with them so far. They're a little clunky in some ways, but
 they do have a ton of sensors, and it's relatively easy to get going with
them. For what they do, they're the cheapest option I've found.

Cheers,
Vern

On Fri, Sep 17, 2010 at 12:19 AM, Nick <nblack3 at student.gsu.edu> wrote:

> http://www.georgiarobotics.com/roboteducation/robot-kit.html
>
> you can check the robot out at this link.  is this a good buy you guys
> think, or is there a better python compatible robot out there?  I just want
> something to keep me interested in programming and that gives me ideas of
> programs to write.  The benefit of the scribbler is also that free book
> online learning with robotics...  It has all kinds of sample code for
> programs for the scribbler.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
This time for sure!
   -Bullwinkle J. Moose
-----------------------------
Vern Ceder, Director of Technology
Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804
vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137

The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/c0a59b95/attachment.html>

From martin at linux-ip.net  Fri Sep 17 13:27:41 2010
From: martin at linux-ip.net (Martin A. Brown)
Date: Fri, 17 Sep 2010 07:27:41 -0400
Subject: [Tutor] intercepting and recored I/O function calls
In-Reply-To: <AANLkTimikH+vo9sFA=jOpBU1suHMPbGp-GvTP9joHgcA@mail.gmail.com>
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
	<i6reb1$h7l$1@dough.gmane.org>
	<AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
	<alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>
	<AANLkTimikH+vo9sFA=jOpBU1suHMPbGp-GvTP9joHgcA@mail.gmail.com>
Message-ID: <alpine.LNX.2.00.1009170710590.18450@paprika.renesys.com>


Good morning Jojo,

 : Thanks Martin, for the detailed break down, it actually helped me 
 : solve one of my other problems..

Quite glad to help.

 : My applogies to begin with, it seems i didnt state my problem 
 : clearly for this particular case - perharps I/O was not the best 
 : way to describe my problem.
 : 
 : We have a system fully developed in python- with thousands of 
 : lines of code- i know i can use the logging facilty for this 
 : task, but this means i have to go into the code and edit it to 
 : log specifics of what i need, this is gone take a while and this 
 : also implies all other users adding modules must include logging 
 : statements..

Right.  OK.  So, you have an existing code base that you are trying 
to understand (and possibly instrument), got it.

 : Specifically, i would like to track all inputs/output to 
 : modules/functions - if a module retrieved and used files and run 
 : some analysis on them and produced other files in return, i would 
 : like to take not of this. i.e what i want is to recored input and 
 : outputs to a module. and also to record all paramaters, attribute 
 : vaules used by the same module.
 : 
 : I thought i would build a wrapper around the orignial python 
 : program or probably pick this information at OS level.

If I understand your description correctly....

  * you have many modules

  * you are not (so) worried about how one module calls another 
    (whether it instantiates classes from one module, in which case 
    you might find metaclasses helpful)

  * you are more worried about which module is opening what files;
    you can always learn what files are getting opened with 'strace 
    -e open', however you want to know which files are opened by 
    what module; that's application-specific

  * you are also worried about application state--you mention 
    attribute values; that's application-specific

I guess I would suggest two things:

  1. Start adding the logging code.  If the application behaviour is 
     opaque now, it's not going to get any more transparent without 
     logging.

  2. Consider learning pdb or whatever another python trace tool, 
     which may be able to provide some of the above for you.  (I 
     will be continuing to follow this thread to learn something 
     new here, as well.)

I'm really not sure what else to recommend here, JoJo.  Maybe some 
of the others on this list can help.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From beachkidken at gmail.com  Fri Sep 17 13:51:36 2010
From: beachkidken at gmail.com (Ken Green)
Date: Fri, 17 Sep 2010 07:51:36 -0400
Subject: [Tutor] Function behavior
In-Reply-To: <i6u21r$nig$1@dough.gmane.org>
References: <4C920B25.8020405@gmail.com> <i6u21r$nig$1@dough.gmane.org>
Message-ID: <4C935648.9040803@gmail.com>

Thanks Alan.  With suggestion and help from several other people on the 
list, I was able to solve the problem.  I learned from an example 
previously given.  I am using several different tutorials and I have 
yours bookmarked.

Ken

On 09/16/2010 05:26 PM, Alan Gauld wrote:
>
> "Ken Green" <beachkidken at gmail.com> wrote
>
>> I am unclear on the behavior of using a function.
>
> You certainly are!
> Which tutorial are you working from?
> You have several fundamental errors here, its hard to know
> where to start.
>
>> def change(amount):
>>     if match == 1:
>>         amount = 0
>>     if match == 2:
>>         amount = 0
>>     if match == 3:
>>         amount = 3
>
> This function is called change and it has an input parameter called 
> amount.
> The parameter is like a local variable only visible inside the function.
> Because there are no return statements in it it will always return the
> default value of None - probably not what you want.
>
> Inside the function you compare a variable called match - which is not
> defined in the function so presumably will be found outside in the module
> or global scope - to a number.
> You then set the parameter amount to another number, one greater
> than the test value. But since amount is the parameter and invisible
> outside the function that will have no affect on anything outside the
> function.
>
>> match = raw_input("How many matches?: ")
>
> Now we define the global variable match but set it to a string.
> The change() function is expecting match to be a number.
> Maybe we should convert it using int()?
>
>> change(match)
>
>
> This does nothing and since we don't assign the functions value
> to anything the None that it returns is lost.
>
>> print amount
>
> amount is not defined anywhere at the global scope and
> the amount parameter in the function is not visible outside
> the function.
>
>> How many matches?: 2
>> Traceback (most recent call last):
>>   File "/home/ken/Python262/TEST Function.py", line 13, in <module>
>>     print amount
>> NameError: name 'amount' is not defined
>
>> Should it be def change(match) instead of def change(amount)?
>> Perhaps, change(amount) instead of change(match)?
>
> You need to go back to basics on how parameters and arguments
> work (This is, I admit, a subtle concept when you first come across it)
>
>> Perhaps, I need to add return somewhere?
>
> Yes you probably do. You can do what you want without it but
> its considered bad practice. Functions should reurn their results.
>
> Try reading the functions and modules topic in my tutorial
> to see if that helps.
>

From alan.gauld at btinternet.com  Fri Sep 17 18:47:18 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 17 Sep 2010 17:47:18 +0100
Subject: [Tutor] intercepting and recored I/O function calls
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com><i6reb1$h7l$1@dough.gmane.org><AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com><alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>
	<AANLkTimikH+vo9sFA=jOpBU1suHMPbGp-GvTP9joHgcA@mail.gmail.com>
Message-ID: <i7062s$388$1@dough.gmane.org>

"Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote

> My applogies to begin with,  it seems i didnt state my problem 
> clearly for
> this particular case - perharps I/O was not the best way to describe 
> my
> problem.

Hmmm, perhaps not! :-)

> Specifically, i would like to track all inputs/output to 
> modules/functions -
> if a module  retrieved and used files and run some analysis on them 
> and
> produced other files in return, i would like to take not of this. 
> i.e what i
> want is to recored input and outputs to a module. and also to record 
> all
> paramaters, attribute vaules used by the same module.

You could do some of that with static code analysis I think.
And while I'm sure you could do this by delving into the innards of
Python it will be a lot of work and I'm not sure what the impact
would be on the performance of your code.

> I thought i would build a wrapper around the orignial python program 
> or
> probably pick this information at OS level.

I don't think the OS will have much of what you want you will need to
look inside Python itself I think. It might be best to tweak the 
interpreter
to trap those details but that would need to be done in C. And it 
would
slow the interpreter down for everything.

The OS knows how your app is interacting with the network and file
system but it doesn't know about the interactons between modules
inside Python. Maybe there are some of the more obscure modules
in the standard library that allow monitoring. The debug and profiling
modules might yield clues too.

An interesting challenge and I'm not sure how I'd go about it myself.
Might be a good one to try on the main comp.lang.python list, its
certainly not typical newbie stuff!

Alan G. 



From lie.1296 at gmail.com  Fri Sep 17 18:56:20 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sat, 18 Sep 2010 02:56:20 +1000
Subject: [Tutor] "Overloading" methods
In-Reply-To: <AANLkTimPA+TA3i2Yf05hqaksXpDEKSxP4g6uye+jHGbH@mail.gmail.com>
References: <20100916120218.GC2727@cecilia>
	<AANLkTimPA+TA3i2Yf05hqaksXpDEKSxP4g6uye+jHGbH@mail.gmail.com>
Message-ID: <i706hr$58b$1@dough.gmane.org>

On 09/17/10 00:22, Vince Spicer wrote:
> 
> 
> Well I can't comment on right or wrong I would think creating a simple
> class with a __call__ method is a little more pythonic.

I think even more pythonic is to use closure:

def create_setpattern(type_):
    def f(self, pattern, parameter):
        return pattern_generator(self, type_, pattern, parameter)
    return f
setpattern_iis = create_setpattern('iis')

for short function body, you can use lambda:

def create_setpattern(t):
    return lambda s, pat, par: pattern_generator(s, t, pat, par)



probably the best solution is to use functools.partial:

from functools import partial
setpattern_iis = partial(pattern_generator, type='iis')

however, this does NOT work due to (TypeError: pattern_generator() got
multiple values for keyword argument 'type'); do you think it will be
reasonable for partial to support this use case?


From 427 at free.fr  Fri Sep 17 15:08:06 2010
From: 427 at free.fr (M. 427)
Date: Fri, 17 Sep 2010 15:08:06 +0200
Subject: [Tutor] Remove a dictionary entry
Message-ID: <1284728886.6961.1.camel@mechazawa>

Hello,

(I am very new to python)
I built a dictionary d={} of lists similar to this :

d = { 
'a': ['apricot', 'apple'],
'b': ['beach', 'bear', 'bottle'],
'c': ['cold', 'cook', 'coleslaw'],
'd': ['deep'],
'e': ['expression', 'elephant']
}

Now i want to go through this dictionary and remove all rows containing
only one entry. How should I do that?


Question 2 : where should I have found this answer myself? (apart from
here)


Thank you for your help.

Mr. 427 


From joel.goldstick at gmail.com  Fri Sep 17 19:34:09 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 17 Sep 2010 13:34:09 -0400
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <1284728886.6961.1.camel@mechazawa>
References: <1284728886.6961.1.camel@mechazawa>
Message-ID: <AANLkTinYG1z-LFqO-H_gTCt6Js+_M1L-XkStRS_=drap@mail.gmail.com>

On Fri, Sep 17, 2010 at 9:08 AM, M. 427 <427 at free.fr> wrote:

> Hello,
>
> (I am very new to python)
> I built a dictionary d={} of lists similar to this :
>
> d = {
> 'a': ['apricot', 'apple'],
> 'b': ['beach', 'bear', 'bottle'],
> 'c': ['cold', 'cook', 'coleslaw'],
> 'd': ['deep'],
> 'e': ['expression', 'elephant']
> }
>
> Now i want to go through this dictionary and remove all rows containing
> only one entry. How should I do that?
>
> You can loop through all the entries in d, and remove the entries that have
length one.  Hope that isn't too much of a hint

>
> Question 2 : where should I have found this answer myself? (apart from
> here)
>
>
> Thank you for your help.
>
> Mr. 427
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/7a263040/attachment.html>

From bgailer at gmail.com  Fri Sep 17 23:01:40 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 17 Sep 2010 17:01:40 -0400
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <1284728886.6961.1.camel@mechazawa>
References: <1284728886.6961.1.camel@mechazawa>
Message-ID: <4C93D734.5010404@gmail.com>

  On 9/17/2010 9:08 AM, M. 427 wrote:
> Hello,
>
> (I am very new to python)
> I built a dictionary d={} of lists similar to this :
>
> d = {
> 'a': ['apricot', 'apple'],
> 'b': ['beach', 'bear', 'bottle'],
> 'c': ['cold', 'cook', 'coleslaw'],
> 'd': ['deep'],
> 'e': ['expression', 'elephant']
> }
>
> Now i want to go through this dictionary and remove all rows containing
> only one entry. How should I do that?

We like to help when you tell us what part(s) of the answer you know. 
There are 4 things involved here:
1 - How to get a list of all the key-value pairs in a dictionary.
2 - How to loop thru that list.
3 - How to get the length of a value's list.
4 - How to test that for equal to 1.
5- How to delete a dictionary entry knowing the key.

Which of those do you know? Which do you need help with?
>
> Question 2 : where should I have found this answer myself? (apart from
> here)
It is hard to give a specific answer since we don't know what you don't 
know.

I suspect most tutorials will give you the answers.

In the Python Reference /6.8 Mapping Type - dict /it tells you the 
answers to 1 and 5.

In the Python Reference /6.6.4. Mutable Sequence Types/ it tells you the 
answer to 3.

In the Python Reference /5.9 Comparisons/ it tells you the answer to 4.

Regarding 3 there are several ways to loop through a sequence. Tutorials 
explain these.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/3d98da51/attachment.html>

From bgailer at gmail.com  Sat Sep 18 00:10:19 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 17 Sep 2010 18:10:19 -0400
Subject: [Tutor] Function behavior
In-Reply-To: <4C920B25.8020405@gmail.com>
References: <4C920B25.8020405@gmail.com>
Message-ID: <4C93E74B.2040102@gmail.com>

  On 9/16/2010 8:18 AM, Ken Green wrote:
> I am unclear on the behavior of using a function.  Below is a short 
> code I wrote to print an amount out after inputting the number of match.
>
> # TEST Function.py
>
> def change(amount):
>     if match == 1:
>         amount = 0
>     if match == 2:
>         amount = 0
>     if match == 3:
>         amount = 3
>
[snip]

How about:

def change(amount, amts={1:0, 2:0, 3:3}):
     return amts[match]

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From bgailer at gmail.com  Sat Sep 18 02:50:12 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 17 Sep 2010 20:50:12 -0400
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <1284762025.13289.74.camel@mechazawa>
References: <1284728886.6961.1.camel@mechazawa> <4C93D74C.8040702@gmail.com>
	<1284762025.13289.74.camel@mechazawa>
Message-ID: <4C940CC4.6020805@gmail.com>

  Please always reply-all so a copy goes to the tutor list.

On 9/17/2010 6:20 PM, M. 427 wrote:
> Thank you very much for your answer.
> I wanted to know the pythonic way of doing this, so I did not post my
> buggy trial which was :
>
> version 1 :
> for row in d :
>    if len(row) == 1 :
>      del row # WRONG
>
> Version 2 :
> for i,row in d :
>    if len(row) == 1 :
>      del d(i) # BUG : Syntax error

Thank you for posting code. In the future do so initially. It helps us 
know where to help.

It looks like you learned from version 1.

When you get a syntax error check the manual. When you look at del in:
Python v2.6.4 documentation - The Python Standard Library - 6.8 Mapping 
Type - dict
you will see d[key] - compare that to what you wrote in version 2.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100917/a31b8fd6/attachment.html>

From beachkidken at gmail.com  Sat Sep 18 02:50:35 2010
From: beachkidken at gmail.com (Ken Green)
Date: Fri, 17 Sep 2010 20:50:35 -0400
Subject: [Tutor] Function behavior (SOLVED)
In-Reply-To: <4C93E74B.2040102@gmail.com>
References: <4C920B25.8020405@gmail.com> <4C93E74B.2040102@gmail.com>
Message-ID: <4C940CDB.2080900@gmail.com>

Thank you.  This will be printed out and studied.  Amazing of what 
Python can do.

Ken

On 09/17/2010 06:10 PM, bob gailer wrote:
>  On 9/16/2010 8:18 AM, Ken Green wrote:
>> I am unclear on the behavior of using a function.  Below is a short 
>> code I wrote to print an amount out after inputting the number of match.
>>
>> # TEST Function.py
>>
>> def change(amount):
>>     if match == 1:
>>         amount = 0
>>     if match == 2:
>>         amount = 0
>>     if match == 3:
>>         amount = 3
>>
> [snip]
>
> How about:
>
> def change(amount, amts={1:0, 2:0, 3:3}):
>     return amts[match]
>

From bgailer at gmail.com  Sat Sep 18 03:36:17 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 17 Sep 2010 21:36:17 -0400
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <1284772867.13289.93.camel@mechazawa>
References: <1284728886.6961.1.camel@mechazawa> <4C93D74C.8040702@gmail.com>	
	<1284762025.13289.74.camel@mechazawa> <4C940CC4.6020805@gmail.com>
	<1284772867.13289.93.camel@mechazawa>
Message-ID: <4C941791.70200@gmail.com>

  On 9/17/2010 9:21 PM, M. 427 wrote:
> Thank you,
> After reading the following documentations
> http://docs.python.org/tutorial/datastructures.html#looping-techniques
> http://docs.python.org/tutorial/controlflow.html#for-statements
> I ended up with this :
>
> Version 3 :
> for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
>      if len(row)<  2 :
>          del d[i]
>
> Still buggy... Any lead for this error message? Is a slice unhashable?
> Am I looking in the right direction for this task?
Where did you see [:] after a dict? [:] is slicing, and applies to a 
sequence not a mapping.

Also note the warning "Using iteritems()  while adding or deleting 
entries in the dictionary may raise a RuntimeError  or fail to iterate 
over all entries."

You should get a list rather than an iterator of all key-value pairs 
then iterate over that list.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From 427 at free.fr  Sat Sep 18 03:21:07 2010
From: 427 at free.fr (M. 427)
Date: Sat, 18 Sep 2010 03:21:07 +0200
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <4C940CC4.6020805@gmail.com>
References: <1284728886.6961.1.camel@mechazawa> <4C93D74C.8040702@gmail.com>
	<1284762025.13289.74.camel@mechazawa>  <4C940CC4.6020805@gmail.com>
Message-ID: <1284772867.13289.93.camel@mechazawa>

Thank you,
After reading the following documentations
http://docs.python.org/tutorial/datastructures.html#looping-techniques
http://docs.python.org/tutorial/controlflow.html#for-statements
I ended up with this :

Version 3 :
for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
    if len(row) < 2 :
        del d[i]

Still buggy... Any lead for this error message? Is a slice unhashable?
Am I looking in the right direction for this task?

Mr. 427

Le vendredi 17 septembre 2010 ? 20:50 -0400, bob gailer a ?crit :
> Please always reply-all so a copy goes to the tutor list.
> 
> On 9/17/2010 6:20 PM, M. 427 wrote: 
> > Thank you very much for your answer.
> > I wanted to know the pythonic way of doing this, so I did not post my
> > buggy trial which was :
> > 
> > version 1 :
> > for row in d : 
> >   if len(row) == 1 :
> >     del row # WRONG
> > 
> > Version 2 :
> > for i,row in d : 
> >   if len(row) == 1 :
> >     del d(i) # BUG : Syntax error
> 
> Thank you for posting code. In the future do so initially. It helps us
> know where to help.
> 
> It looks like you learned from version 1. 
> 
> When you get a syntax error check the manual. When you look at del in:
> Python v2.6.4 documentation - The Python Standard Library - 6.8
> Mapping Type - dict
> you will see d[key] - compare that to what you wrote in version 2.
> 
> -- 
> Bob Gailer
> 919-636-4239
> Chapel Hill NC



From alan.gauld at btinternet.com  Sat Sep 18 10:35:49 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 18 Sep 2010 09:35:49 +0100
Subject: [Tutor] Remove a dictionary entry
References: <1284728886.6961.1.camel@mechazawa>
	<4C93D74C.8040702@gmail.com><1284762025.13289.74.camel@mechazawa>
	<4C940CC4.6020805@gmail.com> <1284772867.13289.93.camel@mechazawa>
Message-ID: <i71tlb$st9$1@dough.gmane.org>


"M. 427" <427 at free.fr> wrote

> I ended up with this :
>
> Version 3 :
> for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
>    if len(row) < 2 :
>        del d[i]

You are getting too complicated.
You don't need the slice and you don't need iteritems.
You have a dictionary. When you iterate over a dictionary
what do you get? Don't know? Try it::

>>> for x in {1:'foo',2:'bar'}: print x
...
1
2

So we get the keys. Now how do we use the keys to get the list?
Standard dictionary access:

>>> print d[1]
foo

You know how to test the lenth of the list and delete the list so put
that together as you did before:

for row in d :     # row is actually the key
   if len(row) == 1 :        # so use the key to get the real row
     del row # WRONG      #' and delete the row, again using the key

HTH,


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



From __peter__ at web.de  Sat Sep 18 11:13:13 2010
From: __peter__ at web.de (Peter Otten)
Date: Sat, 18 Sep 2010 11:13:13 +0200
Subject: [Tutor] Remove a dictionary entry
References: <1284728886.6961.1.camel@mechazawa>
Message-ID: <i71vo5$47b$1@dough.gmane.org>

M. 427 wrote:

> (I am very new to python)
> I built a dictionary d={} of lists similar to this :
> 
> d = {
> 'a': ['apricot', 'apple'],
> 'b': ['beach', 'bear', 'bottle'],
> 'c': ['cold', 'cook', 'coleslaw'],
> 'd': ['deep'],
> 'e': ['expression', 'elephant']
> }
> 
> Now i want to go through this dictionary and remove all rows containing
> only one entry. How should I do that?

You should never iterate over a list or dictionary and add or remove items 
to it at the same time. That is a recipe for disaster even if it doesn't 
fail explicitly.

Instead create a new dictionary that contains only the items you are 
interested in:

>>> d = {
... 'a': ['apricot', 'apple'],
... 'b': ['beach', 'bear', 'bottle'],
... 'c': ['cold', 'cook', 'coleslaw'],
... 'd': ['deep'],
... 'e': ['expression', 'elephant']
... }
>>> result = {}
>>> for k, v in d.iteritems():
...     if len(v) > 1:
...             result[k] = v
...
>>> import pprint
>>> pprint.pprint(result)
{'a': ['apricot', 'apple'],
 'b': ['beach', 'bear', 'bottle'],
 'c': ['cold', 'cook', 'coleslaw'],
 'e': ['expression', 'elephant']}

Peter

PS: Instead of using the pretty print module "pprint" I could have typed

>>> result
{'a': ['apricot', 'apple'], 'c': ['cold', 'cook', 'coleslaw'], 'b': 
['beach', 'bear', 'bottle'], 'e': ['expression', 'elephant']}

The only difference is that it looks messier.



From rwobben at hotmail.com  Sat Sep 18 11:14:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 18 Sep 2010 09:14:03 +0000
Subject: [Tutor] class problem
Message-ID: <SNT118-W7693A95C4CBA993F88D83AE7C0@phx.gbl>


Hello, 

I have this exercise :

Create and print a Point object, and then use id to print the
object?s unique identifier. Translate the hexadecimal form into decimal and
confirm that they match.

So I thought that this would solve it:

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y


P=(Point)
a=0 
b=0
a=id(P)
print a 
print b
print P

But now id is a decimal so I don't can't translate it.
Did I something wrong ?

Roelof

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/adef21df/attachment.html>

From fanger2099 at gmail.com  Sat Sep 18 16:16:47 2010
From: fanger2099 at gmail.com (Fernando Karpinski)
Date: Sat, 18 Sep 2010 11:16:47 -0300
Subject: [Tutor] Help - importing modules
Message-ID: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>

   Hi, everyone. I need help when importing a file I created, with the .py
extension. I am trying to access its directory in DOS, and after I do it, I
type "import filename", but it is not working. I tried to do it by writing
"import filename.py", but it didn't work either. I'm aware that after the
first import, I should either call the reload function or restart the
session, but I can't even import the file successfully once. I am using
Python 2.7. Thanks in advance for your help.

   F
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/ab26b32a/attachment.html>

From joel.goldstick at gmail.com  Sat Sep 18 17:01:42 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 18 Sep 2010 11:01:42 -0400
Subject: [Tutor] Help - importing modules
In-Reply-To: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>
References: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>
Message-ID: <AANLkTikS7xAvdS5Hsm5JabMkmscc71Ku-wDGaswKPpo1@mail.gmail.com>

On Sat, Sep 18, 2010 at 10:16 AM, Fernando Karpinski
<fanger2099 at gmail.com>wrote:

>
>    Hi, everyone. I need help when importing a file I created, with the .py
> extension. I am trying to access its directory in DOS, and after I do it, I
> type "import filename", but it is not working. I tried to do it by writing
> "import filename.py", but it didn't work either. I'm aware that after the
> first import, I should either call the reload function or restart the
> session, but I can't even import the file successfully once. I am using
> Python 2.7. Thanks in advance for your help.
>
>    F
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
your file needs to be in the same directory as your program or in the
sys.path list

you don't use the extension.

import filename

is all you need, not import filename.py

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/903a39d7/attachment.html>

From alan.gauld at btinternet.com  Sat Sep 18 17:03:43 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 18 Sep 2010 16:03:43 +0100
Subject: [Tutor] Remove a dictionary entry
References: <1284728886.6961.1.camel@mechazawa><4C93D74C.8040702@gmail.com><1284762025.13289.74.camel@mechazawa><4C940CC4.6020805@gmail.com>
	<1284772867.13289.93.camel@mechazawa>
	<i71tlb$st9$1@dough.gmane.org>
Message-ID: <i72kcl$e5j$1@dough.gmane.org>


"Alan Gauld" <alan.gauld at btinternet.com> wrote

>> I ended up with this :
>>
>> Version 3 :
>> for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
>>    if len(row) < 2 :
>>        del d[i]
>
> You are getting too complicated.
> You don't need the slice and you don't need iteritems.
> You have a dictionary. When you iterate over a dictionary
> what do you get? Don't know? Try it::
>
>>>> for x in {1:'foo',2:'bar'}: print x
> ...
> 1
> 2
>
> So we get the keys. Now how do we use the keys to get the list?
> Standard dictionary access:
>
>>>> print d[1]
> foo
>
> You know how to test the lenth of the list and delete the list so 
> put
> that together as you did before:
>
> for row in d :     # row is actually the key
>   if len(row) == 1 :        # so use the key to get the real row
>     del row # WRONG      #' and delete the row, again using the key
>

Oops, as Peter pointed out that won't work because its changing
the iterable while we iterate. (I actually thought it would be OK
because the for would use a copy of the keys() list, but I was 
wrong...)
But you can fix that with a list() call:

for row in list(d) :     # generates a new list of the dict keys
   if len(d[row]) == 1 :        # so use the key to get the real row
     del d[row]


HTH,


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




> HTH,
>
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From alan.gauld at btinternet.com  Sat Sep 18 17:11:36 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 18 Sep 2010 16:11:36 +0100
Subject: [Tutor] class problem
References: <SNT118-W7693A95C4CBA993F88D83AE7C0@phx.gbl>
Message-ID: <i72krf$ft7$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote

> Create and print a Point object, and then use id to print the
> object?s unique identifier. Translate the hexadecimal form into 
> decimal and
> confirm that they match.

I initially had no idea what hexadecimal form the text is talking 
about.
id returns a decimal form... This is a badly worded assignment.

> class Point:
>     def __init__(self, x=0, y=0):
>         self.x = x
>         self.y = y
>
> P=(Point)
> a=0
> b=0

The two a,b assigments are seemingly pointless?

> a=id(P)
> print a
> print b
> print P

Why do you want to print b which will  be zero?

However your print P gave me a clue to what the assignment is about.
When you print the object it gives you a hex value     I think they 
want
you to extract that value and convert it to decimal to see if its the 
same
as the value id() gives you.
At least that's the only sane thing I can think it means!

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



From wallenpb at gmail.com  Sat Sep 18 17:44:21 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 18 Sep 2010 10:44:21 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <i6v9dk$rhf$1@dough.gmane.org>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
Message-ID: <AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>

On Fri, Sep 17, 2010 at 3:38 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> For plotting pixels I would not use turtle graphics.
> That would be a fairly complicated option I'd have thought.
> A simple canvas would be easier.
>
> Alan G.
>
>
Oh, I see!  I did not realize that Tk had a canvas widget.  That is nice.  I
will have to play with that and see if I can get everything done in the code
I am working with.  What I am doing is just trying to do a simple Mandelbrot
set plot.  It is another bit of coding that I do when learning a new
language to get a handle on some of the graphics capabilities, and I am to
that point.

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/ff030f43/attachment.html>

From wallenpb at gmail.com  Sat Sep 18 17:45:07 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 18 Sep 2010 10:45:07 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
Message-ID: <AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>

On Sat, Sep 18, 2010 at 10:44 AM, Bill Allen <wallenpb at gmail.com> wrote:

>
>
> On Fri, Sep 17, 2010 at 3:38 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:
>
>>
>> For plotting pixels I would not use turtle graphics.
>> That would be a fairly complicated option I'd have thought.
>> A simple canvas would be easier.
>>
>> Alan G.
>>
>>
> Oh, I see!  I did not realize that Tk had a canvas widget.  That is nice.
> I will have to play with that and see if I can get everything done in the
> code I am working with.  What I am doing is just trying to do a simple
> Mandelbrot set plot.  It is another bit of coding that I do when learning a
> new language to get a handle on some of the graphics capabilities, and I am
> to that point.
>
> -Bill
>
 It appears that the Tk canvas widget does not support simply plotting a
pixel.  However, I can plot a line only one pixel long.   I wonder why they
do not simply provide the pixel plot primitive?  I have seen very many
graphics packages that do this and I have always wondered why.  The
primitive obviously exists in the underlying code, because that is what
everything else is built upon.  Does Tk actually have a something like a
create_pixel method in the canvas widget that I have missed?

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/0f48cebb/attachment-0001.html>

From steve at pearwood.info  Sat Sep 18 17:46:37 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 Sep 2010 01:46:37 +1000
Subject: [Tutor] Help - importing modules
In-Reply-To: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>
References: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>
Message-ID: <201009190146.38918.steve@pearwood.info>

On Sun, 19 Sep 2010 12:16:47 am Fernando Karpinski wrote:
>    Hi, everyone. I need help when importing a file I created, with
> the .py extension. I am trying to access its directory in DOS, and
> after I do it, I type "import filename", but it is not working.

Define "not working".

My crystal ball tells me that you're trying to run import filename at 
the DOS prompt, rather than in the Python interpreter. Is my crystal 
ball accurate?



-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 18 17:54:11 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 Sep 2010 01:54:11 +1000
Subject: [Tutor] class problem
In-Reply-To: <SNT118-W7693A95C4CBA993F88D83AE7C0@phx.gbl>
References: <SNT118-W7693A95C4CBA993F88D83AE7C0@phx.gbl>
Message-ID: <201009190154.11803.steve@pearwood.info>

On Sat, 18 Sep 2010 07:14:03 pm Roelof Wobben wrote:

> P=(Point)

This line does not do what you think it does. Brackets in Python are 
used for two things, grouping and calling functions.

To call a function, or a class, you need to have the brackets *after* 
the function:

P = Point()  # what about arguments to the function?

If you surround it with brackets, as you do above, it does nothing. It's 
like this:

x = (1+1)  # exactly the same as x = 1+1 without brackets


> a=0
> b=0
> a=id(P)

It is a waste of time to initialise variables immediately before 
initialising them again.



> print a
> print b
> print P
>
> But now id is a decimal so I don't can't translate it.

id(x) returns an integer. By default, integers always print in decimal, 
if you want to print them in hex you can do this:

hex(id(P))



-- 
Steven D'Aprano

From steve at pearwood.info  Sat Sep 18 18:06:22 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 Sep 2010 02:06:22 +1000
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <i71vo5$47b$1@dough.gmane.org>
References: <1284728886.6961.1.camel@mechazawa> <i71vo5$47b$1@dough.gmane.org>
Message-ID: <201009190206.22436.steve@pearwood.info>

On Sat, 18 Sep 2010 07:13:13 pm Peter Otten wrote:

> You should never iterate over a list or dictionary and add or remove
> items to it at the same time. That is a recipe for disaster even if
> it doesn't fail explicitly.

That's a bit strong. It's quite possible to modify lists safely and 
correctly while iterating over them with a little bit of care.

You know, for decades people were able to program in languages like C 
and Pascal and assembly, often on machines with tiny amounts of memory. 
When your machine has 64K of memory, and the OS and application uses 
half of it, you don't have the luxury of making a copy of a 20K list 
before modifying it. Back when I was a lad, we learned how to modify 
lists in place. It isn't hard. *wink*

Even in Python, it is sometimes necessary to modify lists and even dicts 
in place while iterating over them. 98% of the time, making a copy is 
faster, simpler and more efficient, but learning how to safely modify 
data structures in place is a valuable skill to have.

But I'm just talking about general principles here. In most cases, stick 
to Peter's advice to make a copy.


-- 
Steven D'Aprano

From smokefloat at gmail.com  Sat Sep 18 18:14:08 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 18 Sep 2010 12:14:08 -0400
Subject: [Tutor] Help - importing modules
In-Reply-To: <201009190146.38918.steve@pearwood.info>
References: <AANLkTin0hXJkknoOmX7++Sr8g8imcC9RffN6faLwgxhy@mail.gmail.com>
	<201009190146.38918.steve@pearwood.info>
Message-ID: <AANLkTikuQA1zzs90u2s84nxMTQy3H-NNZXsDwGTynDLG@mail.gmail.com>

On Sat, Sep 18, 2010 at 11:46 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 19 Sep 2010 12:16:47 am Fernando Karpinski wrote:
>> ? ?Hi, everyone. I need help when importing a file I created, with
>> the .py extension. I am trying to access its directory in DOS, and
>> after I do it, I type "import filename", but it is not working.
>
> Define "not working".
>
> My crystal ball tells me that you're trying to run import filename at
> the DOS prompt, rather than in the Python interpreter. Is my crystal
> ball accurate?

My crystal ball says, 'Hey buddy, pal', but after that it says, you
have to first assign python in windows, as an environmental variable
in windows, with C:\pythonversion. so you can type python in the cmd
prompt on windows, and have python interpreter come up.

>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From rwobben at hotmail.com  Sat Sep 18 18:27:01 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 18 Sep 2010 16:27:01 +0000
Subject: [Tutor] FW:  class problem
In-Reply-To: <SNT118-W5118FB5F7C3C372930CC0EAE7C0@phx.gbl>
References: <SNT118-W7693A95C4CBA993F88D83AE7C0@phx.gbl>,
	<201009190154.11803.steve@pearwood.info>,
	<SNT118-W5118FB5F7C3C372930CC0EAE7C0@phx.gbl>
Message-ID: <SNT118-W43E2C4D48A194FC514675FAE7C0@phx.gbl>




Hello ,

Thanks everyone.

I solved it by this :


class Point:
   def __init__(self, x=0, y=0):
      self.x = x
      self.y = y


P=Point()
print P
print id(P)

and a calculator which can convert hex to decimal.

Roelof


> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Sun, 19 Sep 2010 01:54:11 +1000
>> Subject: Re: [Tutor] class problem
>>
>> On Sat, 18 Sep 2010 07:14:03 pm Roelof Wobben wrote:
>>
>>> P=(Point)
>>
>> This line does not do what you think it does. Brackets in Python are
>> used for two things, grouping and calling functions.
>>
>> To call a function, or a class, you need to have the brackets *after*
>> the function:
>>
>> P = Point() # what about arguments to the function?
>>
>> If you surround it with brackets, as you do above, it does nothing. It's
>> like this:
>>
>> x = (1+1) # exactly the same as x = 1+1 without brackets
>>
>>
>>> a=0
>>> b=0
>>> a=id(P)
>>
>> It is a waste of time to initialise variables immediately before
>> initialising them again.
>>
>>
>>
>>> print a
>>> print b
>>> print P
>>>
>>> But now id is a decimal so I don't can't translate it.
>>
>> id(x) returns an integer. By default, integers always print in decimal,
>> if you want to print them in hex you can do this:
>>
>> hex(id(P))
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor 		 	   		  

From knacktus at googlemail.com  Sat Sep 18 18:50:42 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sat, 18 Sep 2010 18:50:42 +0200
Subject: [Tutor] What are "singletons" good for?
Message-ID: <4C94EDE2.4040302@googlemail.com>

Hey all,

the usual explanation for the usage of a Singleton goes like this:

"Use a singleton if you want to make sure, that only one instance of a 
class exists."

But now I ask myself: Why should I call the constructor of a class more 
than once if I only want one instance?
After all, I decide in my code when to create an instance or when to 
pass an existing instance around.

Example in pseudocode:

class Session(object):
     """Hold a dictionary of ident_to_data_objects"""

     def __init__(self, ident_to_data):
         self.ident_to_data = ident_to_data

Now, that would be a typical "singleton" use case. I want one instance 
of this class application-wide. For example in a View class:

class View(object):
     """Create fancy views"""

     def __init__(self, session):
         self.session = session

In my code I use these classes like this:

class MainApp(object):
     """Do some stuff with the data_objects"""

     def __init__(self):
         self.session = Session()
         self.view = View(self.session)

Would a singleton usage in the View class look like that?

class View(object):
     """Create fancy views"""

     def __init__(self):
         self.session = Session()

What's the point? Is it the spared typing when instanciating a lot of 
View classes (I wouldn't need to pass the session to the constructor). 
Or are there some more advantages (instead of passing the same instance 
aorund)? Also, what would you guys consider as disadvantages?


Another question related to this topic is, if I would use a module as a 
singleton (as suggested by Steve and other), how would I import it the 
instances of a class? Maybe like this?

class View(object):
     """Create fancy views"""

     import session

     def do_something(self, ident):
         self.certain_data_object = session.ident_to_data[ident]

A lot of questions, so thanks in advance for any comments!

Cheers,

Jan

From bgailer at gmail.com  Sat Sep 18 19:18:12 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 18 Sep 2010 13:18:12 -0400
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <i72kcl$e5j$1@dough.gmane.org>
References: <1284728886.6961.1.camel@mechazawa><4C93D74C.8040702@gmail.com><1284762025.13289.74.camel@mechazawa><4C940CC4.6020805@gmail.com>	<1284772867.13289.93.camel@mechazawa>	<i71tlb$st9$1@dough.gmane.org>
	<i72kcl$e5j$1@dough.gmane.org>
Message-ID: <4C94F454.8050704@gmail.com>

  Yet another way is to iterate thru the dict collecting a list of keys 
of items to be deleted.

Then iterate thru that list deleting from the dict.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Sat Sep 18 19:20:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 18 Sep 2010 17:20:03 +0000
Subject: [Tutor] next class problem
Message-ID: <SNT118-W28BAD6A1D322408E71E4EBAE7C0@phx.gbl>



Hello, 
 
I have this exercise :
 
Rewrite the distance function from chapter 5 so that it takes two Points as parameters instead of four numbers.
 
I have this solution :
 
class Point:
     def __init__(self, x=0, y=0): 
         self.x = x
         self.y = y
     
def distance(p1,p2):
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    dsquared = dx**2 + dy**2
    result = dsquared**0.5
    return result
P1 = Point()
P1.x = 3
P1.y = 3
P2 = Point()
P2.x = 6
P2.y = 7 
result = distance (P1,P2)
print result
 
 
Is this the correct solution ?
 
Roelof
  		 	   		  

From bgailer at gmail.com  Sat Sep 18 19:40:55 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 18 Sep 2010 13:40:55 -0400
Subject: [Tutor] next class problem
In-Reply-To: <SNT118-W28BAD6A1D322408E71E4EBAE7C0@phx.gbl>
References: <SNT118-W28BAD6A1D322408E71E4EBAE7C0@phx.gbl>
Message-ID: <4C94F9A7.7040601@gmail.com>

  On 9/18/2010 1:20 PM, Roelof Wobben wrote:
>
> Hello,
>
> I have this exercise :
>
> Rewrite the distance function from chapter 5 so that it takes two Points as parameters instead of four numbers.
>
> I have this solution :
>
> class Point:
>       def __init__(self, x=0, y=0):
>           self.x = x
>           self.y = y
>
> def distance(p1,p2):
>      dx = p2.x - p1.x
>      dy = p2.y - p1.y
>      dsquared = dx**2 + dy**2
>      result = dsquared**0.5
>      return result
> P1 = Point()
> P1.x = 3
> P1.y = 3
> P2 = Point()
> P2.x = 6
> P2.y = 7
> result = distance (P1,P2)
> print result
>
>
> Is this the correct solution ?

What is your criteria for "correct"?

There is no one correct solution!

You seem to be passing 2 points, as requested.

Do you get the correct answer?

Then it mus be correct.

FWIW Python convention recommends names starting with lower case except 
for classes and constants.

Therefore p1 and p2 are preferred to P1 and P2.

Also why not initialize x and y thus:
p1 = Point(3,3)
That is what the __init__ is for.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Sat Sep 18 19:50:45 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 18 Sep 2010 17:50:45 +0000
Subject: [Tutor] next class problem
In-Reply-To: <4C94F9A7.7040601@gmail.com>
References: <SNT118-W28BAD6A1D322408E71E4EBAE7C0@phx.gbl>,
	<4C94F9A7.7040601@gmail.com>
Message-ID: <SNT118-W29A7754B28AE8BAAD89B3FAE7C0@phx.gbl>




----------------------------------------
> Date: Sat, 18 Sep 2010 13:40:55 -0400
> From: bgailer at gmail.com
> To: rwobben at hotmail.com
> CC: tutor at python.org
> Subject: Re: [Tutor] next class problem
>
> On 9/18/2010 1:20 PM, Roelof Wobben wrote:
>>
>> Hello,
>>
>> I have this exercise :
>>
>> Rewrite the distance function from chapter 5 so that it takes two Points as parameters instead of four numbers.
>>
>> I have this solution :
>>
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> def distance(p1,p2):
>> dx = p2.x - p1.x
>> dy = p2.y - p1.y
>> dsquared = dx**2 + dy**2
>> result = dsquared**0.5
>> return result
>> P1 = Point()
>> P1.x = 3
>> P1.y = 3
>> P2 = Point()
>> P2.x = 6
>> P2.y = 7
>> result = distance (P1,P2)
>> print result
>>
>>
>> Is this the correct solution ?
>
> What is your criteria for "correct"?
>
> There is no one correct solution!
>
> You seem to be passing 2 points, as requested.
>
> Do you get the correct answer?
>
> Then it mus be correct.
>
> FWIW Python convention recommends names starting with lower case except
> for classes and constants.
>
> Therefore p1 and p2 are preferred to P1 and P2.
>
> Also why not initialize x and y thus:
> p1 = Point(3,3)
> That is what the __init__ is for.
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
 
Hello, 
 
Thank you.
Learned another thing.
 
Roelof

  		 	   		  

From ksterling at mindspring.com  Sat Sep 18 20:18:06 2010
From: ksterling at mindspring.com (Ken Oliver)
Date: Sat, 18 Sep 2010 14:18:06 -0400 (GMT-04:00)
Subject: [Tutor] plotting pixels
Message-ID: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/e0491a41/attachment.html>

From lie.1296 at gmail.com  Sat Sep 18 21:37:11 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 19 Sep 2010 05:37:11 +1000
Subject: [Tutor] plotting pixels
In-Reply-To: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
References: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
Message-ID: <i734be$cgv$1@dough.gmane.org>

>      It appears that the Tk canvas widget does not support simply
>     plotting a pixel.  However, I can plot a line only one pixel long.  
>     I wonder why they do not simply provide the pixel plot primitive?  I
>     have seen very many graphics packages that do this and I have always
>     wondered why.  The primitive obviously exists in the underlying
>     code, because that is what everything else is built upon.  Does Tk
>     actually have a something like a create_pixel method in the canvas
>     widget that I have missed?

You don't want that.

Tkinter's Canvas is a Smart Canvas, each lines and shapes corresponds to
a Tcl/Tk object. If you want to plot a 800*600 image pixel-per-pixel in
Tkinter's Canvas, then Tkinter would have to create 480000 Tcl Objects.

If you want to draw pixels and lines directly, Tkinter Canvas isn't
suitable for that. Try using a different Canvas, one that uses a
Stateless Canvas.


From lie.1296 at gmail.com  Sat Sep 18 22:03:33 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 19 Sep 2010 06:03:33 +1000
Subject: [Tutor] What are "singletons" good for?
In-Reply-To: <4C94EDE2.4040302@googlemail.com>
References: <4C94EDE2.4040302@googlemail.com>
Message-ID: <i735t1$i5m$1@dough.gmane.org>

On 09/19/10 02:50, Knacktus wrote:
> Hey all,
> 
> the usual explanation for the usage of a Singleton goes like this:
> 
> "Use a singleton if you want to make sure, that only one instance of a
> class exists."
> 
> But now I ask myself: Why should I call the constructor of a class more
> than once if I only want one instance?
> After all, I decide in my code when to create an instance or when to
> pass an existing instance around.

The guarantee.

If you're writing a module that may be used by two or more modules, that
may be used by a script. A logger module is a good example; if your
script imports two modules, and both modules import the same logger
module and instantiate their own version of loggers, then it is
difficult to coordinate the logging of those two modules. If instead the
logger class is a Singleton, then the user of logger modules doesn't
need to care about any other modules using the same logger module, since
they will create an instance when needed or get the existing logger when
someone else already made one.

A configuration module is another good example. It is a common idiom in
python to import a .py script for configuration purpose. The benefit of
this is that the config file basically becomes a truly global variable
(python does not have a true global variable).

> What's the point? Is it the spared typing when instanciating a lot of
> View classes (I wouldn't need to pass the session to the constructor).
> Or are there some more advantages (instead of passing the same instance
> aorund)? Also, what would you guys consider as disadvantages?

Disadvantage? compared to what?


From wallenpb at gmail.com  Sat Sep 18 23:46:23 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 18 Sep 2010 16:46:23 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
References: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
Message-ID: <AANLkTikOJAB+1sud1kqNp85vep8B=BiYyE2814dDrAUY@mail.gmail.com>

On Sat, Sep 18, 2010 at 1:18 PM, Ken Oliver <ksterling at mindspring.com>wrote:

>
>
>> On Fri, Sep 17, 2010 at 3:38 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:
>>
>>>
>>> For plotting pixels I would not use turtle graphics.
>>> That would be a fairly complicated option I'd have thought.
>>> A simple canvas would be easier.
>>>
>>> Alan G.
>>>
>>>
>> Oh, I see!  I did not realize that Tk had a canvas widget.  That is nice.
>> I will have to play with that and see if I can get everything done in the
>> code I am working with.  What I am doing is just trying to do a simple
>> Mandelbrot set plot.  It is another bit of coding that I do when learning a
>> new language to get a handle on some of the graphics capabilities, and I am
>> to that point.
>>
>> -Bill
>>
>  It appears that the Tk canvas widget does not support simply plotting a
> pixel.  However, I can plot a line only one pixel long.   I wonder why they
> do not simply provide the pixel plot primitive?  I have seen very many
> graphics packages that do this and I have always wondered why.  The
> primitive obviously exists in the underlying code, because that is what
> everything else is built upon.  Does Tk actually have a something like a
> create_pixel method in the canvas widget that I have missed?
>
> -Bill
>
> Is it naive of me to ask, "Couldn't one write his own plotpixel( ) function
> using the line() function?"
>
>  .
>
> No, not naive at all.  Indeed I could, but that is not the issue in my
mind.  My point is that it seems strange to me that any graphics package
would not make the most basic of the routines, ploting a single pixel,
available.   I think I actually see a way of doing it with the bitmap class,
but that is not the point.  While I could do exactly as you have said, I
would rather either write my own low-level code to accomplish that or use a
package that does provide it than to wrap up a higher end function, such as
drawing a line or rectangle, into even more code in order to do less.   For
the particular use that I am going to put this to, a package such as pygame
which does provide the ability to plot pixels directly will be more
suitable.

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/bf181383/attachment-0001.html>

From alan.gauld at btinternet.com  Sun Sep 19 01:39:34 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sat, 18 Sep 2010 23:39:34 +0000 (GMT)
Subject: [Tutor] plotting pixels
In-Reply-To: <AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
Message-ID: <813627.27084.qm@web86704.mail.ird.yahoo.com>

> It appears that the Tk canvas widget does not support simply plotting a  
>pixel.  
>

Correct, and I agree it seems odd, but in practice drawing either lines or 
ovals of one-pixel do the equivalent job - albeit a little more slowly.

> The  primitive obviously exists in the underlying code, 

It probably exists in the native graphics toolkit (Xlib or Win32 or Aqua) 
but it doesn't exist at the Tk level which is why Tkinter can't expose it.

FWIW wxPython does provide a DrawPoint() method as part of its 
DeviceContext class.

Digging a little deeper it seems the idiomatic way to do this in Python 
is to use PIL the Python Imaging Library to create a GIF or bitmap 
image and then insert that into Tkinters cancvas as an image object.

The Pil ImageDraw class has a point() ethod

I've never tried this but it is described in Grayson's (now out of print?) 
book on Tkinter where he uses it to draw a Mandelbrot....
The book may be available online these days...

Nowdownloadall.com seems to have it although I've no idea 
of the legality of it!

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/b525ab30/attachment.html>

From wallenpb at gmail.com  Sun Sep 19 04:26:35 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 18 Sep 2010 21:26:35 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <813627.27084.qm@web86704.mail.ird.yahoo.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
	<813627.27084.qm@web86704.mail.ird.yahoo.com>
Message-ID: <AANLkTim7mk2fA2Kazkha0rnmvDyHMN5P0rwLAYTL=YbK@mail.gmail.com>

>
> Digging a little deeper it seems the idiomatic way to do this in Python
> is to use PIL the Python Imaging Library to create a GIF or bitmap
> image and then insert that into Tkinters cancvas as an image object.
>
> The Pil ImageDraw class has a point() ethod
>
> I've never tried this but it is described in Grayson's (now out of print?)
> book on Tkinter where he uses it to draw a Mandelbrot....
> The book may be available online these days...
>
> Nowdownloadall.com seems to have it although I've no idea
> of the legality of it!
>
> HTH,
>
> Alan G.
>
Yes, to create a gif or a bmp from the iteration results and then to display
that at the end of the run is by far the most efficient way of producing
Mandelbrot and related sets.  I have actually done it that way before.   I
just have always had a strange preference to see the set as it is being
produced, which is far from efficient.  Kind of a very elaborate progress
bar!  Anyway, I have no real complaints about the Tk canvas methods.  It has
always just been a pet peeve of mine when something as basic and simple as
plotting a pixel is missing.  My complaint on this goes way back to the
ancient days when I had to figure out how to write a plot_pixel primitive in
x86 assembler and then build a graphics library of my own so I could have
pixel based graphics on my old monochrome IBM XT clone that had a Hercules
graphics card in it.  Those were the days!  Mandelbrot sets in 4 shades of
amber-monochrome!    ;-)   I will check out that book you referenced.   I
appreciate everybody's feedback on this.

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/aa661574/attachment.html>

From wallenpb at gmail.com  Sun Sep 19 05:50:14 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 18 Sep 2010 22:50:14 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <AANLkTim7mk2fA2Kazkha0rnmvDyHMN5P0rwLAYTL=YbK@mail.gmail.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
	<813627.27084.qm@web86704.mail.ird.yahoo.com>
	<AANLkTim7mk2fA2Kazkha0rnmvDyHMN5P0rwLAYTL=YbK@mail.gmail.com>
Message-ID: <AANLkTikg18as9MdAcG8HBysP_gMK_jk8+YkBAvj=FLwd@mail.gmail.com>

On Sat, Sep 18, 2010 at 9:26 PM, Bill Allen <wallenpb at gmail.com> wrote:

>
>
>> Digging a little deeper it seems the idiomatic way to do this in Python
>> is to use PIL the Python Imaging Library to create a GIF or bitmap
>> image and then insert that into Tkinters cancvas as an image object.
>>
>> The Pil ImageDraw class has a point() ethod
>>
>> I've never tried this but it is described in Grayson's (now out of print?)
>>
>> book on Tkinter where he uses it to draw a Mandelbrot....
>> The book may be available online these days...
>>
>> Nowdownloadall.com seems to have it although I've no idea
>> of the legality of it!
>>
>> HTH,
>>
>> Alan G.
>>
> Yes, to create a gif or a bmp from the iteration results and then to
> display that at the end of the run is by far the most efficient way of
> producing Mandelbrot and related sets.  I have actually done it that way
> before.   I just have always had a strange preference to see the set as it
> is being produced, which is far from efficient.  Kind of a very elaborate
> progress bar!  Anyway, I have no real complaints about the Tk canvas
> methods.  It has always just been a pet peeve of mine when something as
> basic and simple as plotting a pixel is missing.  My complaint on this goes
> way back to the ancient days when I had to figure out how to write a
> plot_pixel primitive in x86 assembler and then build a graphics library of
> my own so I could have pixel based graphics on my old monochrome IBM XT
> clone that had a Hercules graphics card in it.  Those were the days!
> Mandelbrot sets in 4 shades of amber-monochrome!    ;-)   I will check out
> that book you referenced.   I appreciate everybody's feedback on this.
>
> -Bill
>
>
> I found this code on the web.  It creates a 100x100 tk.photoimage  and
fills it with a radom colored pixels then displays it.  It seems to me that
I should be able to adapt this to what I am trying to acomplish.  The only
difference in the way I am filling the tk.photoimage object.  I ran this
under Python 3.1.2 with success.  I believe the '#%02x%02x%02x' is the
format for an image.   It is a color photoimage, but I am presuming that if
written directly out to a file this would not actually produce a valid, bmp,
gif, pgn, etc.  Correct?   This does seem to be a reasonable solution that
is a pure Tk solution.  Also it works in Python 3x, whereas the PIL library
has not yet been released for 3x.   I have not mentioned it before, but
using Python 3x only is also one of my requirement, though self-imposed.
Can anyone help me better understand this part of the code below?
self.i.put('#%02x%02x%02x' % tuple(color),(row,col))

import tkinter, random
class App:
    def __init__(self, t):
        self.i = tkinter.PhotoImage(width=100,height=100)
        colors = [[random.randint(0,255) for i in range(0,3)] for j in
range(0,10000)]
        row = 0; col = 0
        for color in colors:
            self.i.put('#%02x%02x%02x' % tuple(color),(row,col))
            col += 1
            if col == 100:
                row +=1; col = 0
        c = tkinter.Canvas(t, width=100, height=100); c.pack()
        c.create_image(0, 0, image = self.i, anchor=tkinter.NW)

t = tkinter.Tk()
a = App(t)
t.mainloop()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100918/7196f486/attachment.html>

From 427 at free.fr  Sun Sep 19 02:39:18 2010
From: 427 at free.fr (M. 427)
Date: Sun, 19 Sep 2010 02:39:18 +0200
Subject: [Tutor] Remove a dictionary entry
In-Reply-To: <4C941791.70200@gmail.com>
References: <1284728886.6961.1.camel@mechazawa> <4C93D74C.8040702@gmail.com>
	<1284762025.13289.74.camel@mechazawa>  <4C940CC4.6020805@gmail.com>
	<1284772867.13289.93.camel@mechazawa>  <4C941791.70200@gmail.com>
Message-ID: <1284856758.5947.4.camel@mechazawa>

Version 4 : (2 steps)

	# step 1 : list keys of unwanted rows
	sck=[] # list of single children keys in dictionary
	for k in d.keys() :
		if len(d[k]) < 2 :
			sck.append(k)
	# step 2 : delete all d rows whose key is listed in sck
	while len(sck) > 0 :
		del d[sck.pop()]

This works.
Is this the optimal pythonic way of doing it?

Mr. 427


Le vendredi 17 septembre 2010 ? 21:36 -0400, bob gailer a ?crit :
> On 9/17/2010 9:21 PM, M. 427 wrote:
> > Thank you,
> > After reading the following documentations
> > http://docs.python.org/tutorial/datastructures.html#looping-techniques
> > http://docs.python.org/tutorial/controlflow.html#for-statements
> > I ended up with this :
> >
> > Version 3 :
> > for i,row in d[:].iteritems() : # BUG : TypeError: unhashable type
> >      if len(row)<  2 :
> >          del d[i]
> >
> > Still buggy... Any lead for this error message? Is a slice unhashable?
> > Am I looking in the right direction for this task?
> Where did you see [:] after a dict? [:] is slicing, and applies to a 
> sequence not a mapping.
> 
> Also note the warning "Using iteritems()  while adding or deleting 
> entries in the dictionary may raise a RuntimeError  or fail to iterate 
> over all entries."
> 
> You should get a list rather than an iterator of all key-value pairs 
> then iterate over that list.
> 



From lie.1296 at gmail.com  Sun Sep 19 09:40:34 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Sun, 19 Sep 2010 17:40:34 +1000
Subject: [Tutor] plotting pixels
In-Reply-To: <813627.27084.qm@web86704.mail.ird.yahoo.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>	<i6v9dk$rhf$1@dough.gmane.org>	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
	<813627.27084.qm@web86704.mail.ird.yahoo.com>
Message-ID: <i74enp$a5h$1@dough.gmane.org>

On 09/19/10 09:39, ALAN GAULD wrote:
>> It appears that the Tk canvas widget does not support simply plotting
> a pixel. 
> 
> Correct, and I agree it seems odd, but in practice drawing either lines or
> ovals of one-pixel do the equivalent job - albeit a little more slowly.

More slowly and takes huge amount of memory. A single Tk canvas object
takes at least 14 words (= 114 bytes in 64-bit OS = 56 bytes in 32-bit
OS) + the amount of data is needed to store the `kind of object`. That's
much larger than the ideal 3 bytes per pixel (or 4 bytes with alpha).

Tkinter's Canvas intentionally doesn't provide create_pixel() because
unlike most other Canvas implementations, Tkinter's Canvas holds a
stateful canvas objects instead of a simple drawing surface. Providing a
create_pixel() will be too tempting for abuse, which would make the
canvas unbearably slow and memory consuming. In short, Canvas is not
designed for pixel drawing.

> Digging a little deeper it seems the idiomatic way to do this in Python
> is to use PIL the Python Imaging Library to create a GIF or bitmap
> image and then insert that into Tkinters cancvas as an image object.
> 
> The Pil ImageDraw class has a point() ethod

If you need to plot pixels, do use pygame, PIL, or at least the
PhotoImage trick.


From rwobben at hotmail.com  Sun Sep 19 10:49:12 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 08:49:12 +0000
Subject: [Tutor] Can this be done easly
Message-ID: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>



Hello, 
 
I have this programm :
 
class Point:
     def __init__(self, x=0, y=0): 
         self.x = x
         self.y = y
     
class Rectangle(Point):
    def _init_(self, width=0, length=0):
        self.width = width
        self.length = length
        
punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
This one gives as error message  : 
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in <module>
    rechthoek = Rectangle (punt,20,30)
TypeError: __init__() takes at most 3 arguments (4 given)
 
Roelof
  		 	   		  

From __peter__ at web.de  Sun Sep 19 10:45:34 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Sep 2010 10:45:34 +0200
Subject: [Tutor] Remove a dictionary entry
References: <1284728886.6961.1.camel@mechazawa> <4C93D74C.8040702@gmail.com>
	<1284762025.13289.74.camel@mechazawa> <4C940CC4.6020805@gmail.com>
	<1284772867.13289.93.camel@mechazawa>
	<4C941791.70200@gmail.com> <1284856758.5947.4.camel@mechazawa>
Message-ID: <i74ijc$ls8$1@dough.gmane.org>

M. 427 wrote:

> Version 4 : (2 steps)
> 
>         # step 1 : list keys of unwanted rows
>         sck=[] # list of single children keys in dictionary
>         for k in d.keys() :
>                 if len(d[k]) < 2 :
>                         sck.append(k)
>         # step 2 : delete all d rows whose key is listed in sck
>         while len(sck) > 0 :
>                 del d[sck.pop()]
> 
> This works.
> Is this the optimal pythonic way of doing it?

Ceterum censeo: the pythonic way is to make a copy:

d = dict((k, v) for k, v in d.iteritems() if len(v) > 1)

As an optimization, if the dictionary is huge and there are relatively few 
items to be deleted you may fall back to the 2-step approach. I would write 
it

delenda = [k for k, v in d.iteritems() if len(v) < 2]
for k in delenda:
    del d[k]

Peter


From __peter__ at web.de  Sun Sep 19 10:41:00 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Sep 2010 10:41 +0200
Subject: [Tutor] Remove a dictionary entry
References: <1284728886.6961.1.camel@mechazawa> <i71vo5$47b$1@dough.gmane.org>
	<201009190206.22436.steve@pearwood.info>
Message-ID: <i74iaq$l0a$1@dough.gmane.org>

Steven D'Aprano wrote:

> On Sat, 18 Sep 2010 07:13:13 pm Peter Otten wrote:
> 
>> You should never iterate over a list or dictionary and add or remove
>> items to it at the same time. That is a recipe for disaster even if
>> it doesn't fail explicitly.
> 
> That's a bit strong. It's quite possible to modify lists safely and
> correctly while iterating over them with a little bit of care.

You're of course not the intended audience of my advice.
 
> You know, for decades people were able to program in languages like C
> and Pascal and assembly, often on machines with tiny amounts of memory.
> When your machine has 64K of memory, and the OS and application uses
> half of it, you don't have the luxury of making a copy of a 20K list
> before modifying it. Back when I was a lad, we learned how to modify
> lists in place. It isn't hard. *wink*

When you do that you are usually operating on an abstraction level below 
Python.
 
> Even in Python, it is sometimes necessary to modify lists and even dicts
> in place while iterating over them. 98% of the time, making a copy is
> faster, simpler and more efficient, but learning how to safely modify
> data structures in place is a valuable skill to have.

If you have a huge list that you can only modify in place you may have 
chosen the wrong data structure.

> But I'm just talking about general principles here. In most cases, stick
> to Peter's advice to make a copy.

Hey, I can agree with that ;)

Peter


From knacktus at googlemail.com  Sun Sep 19 14:19:46 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sun, 19 Sep 2010 14:19:46 +0200
Subject: [Tutor] Can this be done easly
In-Reply-To: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
Message-ID: <4C95FFE2.2010304@googlemail.com>

Am 19.09.2010 10:49, schrieb Roelof Wobben:
>
>
> Hello,
>
> I have this programm :
>
> class Point:
>       def __init__(self, x=0, y=0):
>           self.x = x
>           self.y = y
>
> class Rectangle(Point):
>      def _init_(self, width=0, length=0):
>          self.width = width
>          self.length = length
You're inheriting the Point Class, but you don't initialise it.
For some detailled description of inheritance in Python I rather suggest 
to check out some tutorials instead of trying to explain it. Also, 
others on this list can do this probably better. Here's one reference:
http://diveintopython.org/object_oriented_framework/index.html

But now some remarks regarding your problem:

First, I would not consider a Rectangle as a special Point. It's not a 
relation like a Sportscar is a Car (is-a-relationship). It's more a 
relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a 
width and length. So, it's probably better to express your Rectangle 
class like this:

class Rectangle(object):
     def __init__(self, base_point, width=0, length=0):
         self.base_point = base_point
         self.width = width
         self.length = length

then you go (with German names ;-)):

punkt = Point(3,4)
rechteck = Rectangle(punkt,20,30)

In your Rectangle class, the __init__ method takes only two arguments 
(not counting the instance: self), but you're passing three arguments.

At the beginning, the error messages are a bit confusing, because they 
count the instance as one of the arguments. So it tells you, that you 
have given 4 arguments, but you might wonder "Hey, I gave you 3".

HTH,

Jan

>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
>
> Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
> This one gives as error message  :
>
> Traceback (most recent call last):
>    File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in<module>
>      rechthoek = Rectangle (punt,20,30)
> TypeError: __init__() takes at most 3 arguments (4 given)
>
> Roelof
>    		 	   		
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From steve at pearwood.info  Sun Sep 19 15:41:54 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 19 Sep 2010 23:41:54 +1000
Subject: [Tutor] What are "singletons" good for?
In-Reply-To: <4C94EDE2.4040302@googlemail.com>
References: <4C94EDE2.4040302@googlemail.com>
Message-ID: <201009192341.56495.steve@pearwood.info>

On Sun, 19 Sep 2010 02:50:42 am Knacktus wrote:
> Hey all,
>
> the usual explanation for the usage of a Singleton goes like this:
>
> "Use a singleton if you want to make sure, that only one instance of
> a class exists."
>
> But now I ask myself: Why should I call the constructor of a class
> more than once if I only want one instance?

Why does int("spam") raise an exception that you can catch, instead of 
dumping core and crashing the machine? After all, if you don't want to 
crash the machine, just make sure you never call int() with something 
that isn't an integer.

Right?

No. We all know that no matter how much you intend to only call int() on 
strings which actually do represent integers, bugs do happen, so we 
have the language protect us from our mistakes. Likewise, you might 
intend to only call the constructor of a class once, and in a 200 line 
script you might even be confident of that fact, but in a 200,000 line 
program how confident will you be?

You might say "do a search of the source code, and if you see the 
constructor called twice, you know it's wrong" but of course there 
might be a legitimate reason to call the constructor from different 
places in the code, so long as only one of them is actually executed.


> After all, I decide in my code when to create an instance or when to
> pass an existing instance around.

Why should you have to decide? Why bother to track that yourself, when 
the class could track it for you?

Depending on your needs or philosophy, one tactic is to have the class 
explicitly tell you when you're trying to initialise a second instance, 
by raising an exception. Python does that with some singletons:

>>> type(None)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'NoneType' instances

And the same for NotImplemented. Personally, I don't understand that 
tactic. I prefer the tactic used by the pair of singletons True and 
False:

>>> bool() is False
True

No matter how many times you call bool(), it will always return one of 
the two singleton instances True or False. Imported modules are the 
same -- every time you import a module, Python gives you the same 
module instance. So if you need singleton behaviour, a module gives you 
that for free.


> Example in pseudocode:
>
> class Session(object):
>      """Hold a dictionary of ident_to_data_objects"""
>
>      def __init__(self, ident_to_data):
>          self.ident_to_data = ident_to_data
>
> Now, that would be a typical "singleton" use case. I want one 
> instance of this class application-wide. For example in a View class:
>
> class View(object):
>      """Create fancy views"""
>
>      def __init__(self, session):
>          self.session = session

If there's only ever one session, can't possibly be a second, then why 
make it an attribute of the view instance? You might have 30 views, so 
why pretend that they could have 30 different sessions?

Better to inject the session into the View class itself, as a class 
attribute:

class View(object):
    """Create fancy views"""
    session = None
    def __init__(self, session=None):
        if self.session is None:
            self.__class__.session = session
        elif session is not None:
            raise ValueError('cannot use two sessions')

But why pretend that you might have multiple View-like classes, with 
different sessions? Since you have the invariant that there can only 
ever be one session, you can't allow this:

class MyView(View):
    session = another_session()

Since that's prohibited, don't pretend it's allowed. You might as well 
make session a global variable, and stop pretending to be more virtuous 
than you actually are.

And that's the problem -- singletons are often (not always, but often) 
just a sop to the idea that global variables are bad. They are, but 
disguising them as a singleton object doesn't make them less bad. It's 
better to think really hard about *why* you want only one instance of a 
class, whether it's really necessary, and if so, whether an alternative 
such as the Borg pattern would be better.

http://code.activestate.com/recipes/66531/


> In my code I use these classes like this:
>
> class MainApp(object):
>      """Do some stuff with the data_objects"""
>
>      def __init__(self):
>          self.session = Session()
>          self.view = View(self.session)

Since every MainApp instance creates it's own independent session 
object, no, there's no singleton. It's not a singleton if you merely 
*happen* to only create one instance. It's only a singleton if you 
*can* only create one instance (or at least, one instance with each 
specific value).

E.g. you can create multiple lists with the same value but different 
identity:

>>> a = [1, 2]
>>> b = [1, 2]
>>> a is b
False

so lists are not singletons. But you can't create multiple module 
objects with the same value and different identity:

>>> import math
>>> import math as another_math
>>> math is another_math
True

So even though there is are many different modules, we call them 
singletons.


> Would a singleton usage in the View class look like that?
>
> class View(object):
>      """Create fancy views"""
>
>      def __init__(self):
>          self.session = Session()

Again, there's nothing "singleton" about this. Apart from modules, you 
don't get singletons for free in Python, you have to work at it. One 
way is this:

# Untested
class Singleton(object):
    _instance = None
    def __new__(cls):
        if cls._instance is not None:
            # raise TypeError('cannot make a second instance')
            # but this might be better:
            return cls._instance
        else:
            inst = object.__new__(cls)
            cls._instance = inst
            return inst



> What's the point? 

Good question. It seems to me that the Singleton design pattern has the 
wrong focus, and so it actually isn't useful or necessary in most of 
the cases that people use it. In my opinion, it's mostly a gimmick.

Some exceptions -- the None singleton is useful, because we *do* care 
about identity. None has no state, it has no attributes or useful 
methods, the *only* thing we care about is identity -- something either 
is None or it isn't. Same with NotImplemented, True, False and a 
handful of other objects. So Singleton is valid for them.

Modules, on the other hand, could just have easily be implemented as the 
Borg pattern -- you might have two, three, a thousand instances of the 
math module, so long as they all share the same state rather than being 
copies, it doesn't matter. Ensuring that there's only one instance of 
the math module is a tiny memory optimization, but other than that, it 
would make no real difference.



> Is it the spared typing when instanciating a lot of 
> View classes (I wouldn't need to pass the session to the
> constructor). Or are there some more advantages (instead of passing
> the same instance aorund)? Also, what would you guys consider as
> disadvantages?

The biggest disadvantage of singletons is that they're often just 
disguised global variables. Instead of writing:

# Globals
default_page_size = "A4"
default_left_margin = 2  # cm
default_right_margin = 2
# etc.

people have a tendency to do this:


MyApp(defaults=SingletonPageSettings("A4", 2, 2))


and think this makes their code "better". (I blame the Go4 for making a 
religion out of design patterns which exist only to work around Java's 
limitations.) But it's just a disguised global record, with exactly the 
same problems as ordinary globals.

The second biggest problem is that, invariably, if you think something 
needs to be a singleton today, tomorrow you'll wish you had two of 
them. You have a singleton Desktop object in your window manager, and 
then you realise that there's no reason not to have multiple desktops. 
Your word processor has a singleton Printer config, but then you buy a 
second printer. Even if you really do want a single instance, say of 
your MainApp object, sometimes it's useful to have a second one for 
debugging. So in Java land, programmers often try to bypass the 
singleton code so they can defeat the original designer who made it a 
singleton.


> Another question related to this topic is, if I would use a module as
> a singleton (as suggested by Steve and other), how would I import it
> the instances of a class? Maybe like this?
>
> class View(object):
>      """Create fancy views"""
>
>      import session
>
>      def do_something(self, ident):
>          self.certain_data_object = session.ident_to_data[ident]

Almost -- you would have to refer to self.session, not just session. 
Other than that, you could do it, of course, but it's simpler to stick 
with this:


import session

class View(object):
    """Create fancy views"""
    def do_something(self, ident):
        self.certain_data_object = session.ident_to_data[ident]




-- 
Steven D'Aprano

From rwobben at hotmail.com  Sun Sep 19 17:48:02 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 15:48:02 +0000
Subject: [Tutor] Can this be done easly
In-Reply-To: <4C95FFE2.2010304@googlemail.com>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>,
	<4C95FFE2.2010304@googlemail.com>
Message-ID: <SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>




----------------------------------------
> Date: Sun, 19 Sep 2010 14:19:46 +0200
> From: knacktus at googlemail.com
> To: tutor at python.org
> Subject: Re: [Tutor] Can this be done easly
>
> Am 19.09.2010 10:49, schrieb Roelof Wobben:
>>
>>
>> Hello,
>>
>> I have this programm :
>>
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(Point):
>> def _init_(self, width=0, length=0):
>> self.width = width
>> self.length = length
> You're inheriting the Point Class, but you don't initialise it.
> For some detailled description of inheritance in Python I rather suggest
> to check out some tutorials instead of trying to explain it. Also,
> others on this list can do this probably better. Here's one reference:
> http://diveintopython.org/object_oriented_framework/index.html
>
> But now some remarks regarding your problem:
>
> First, I would not consider a Rectangle as a special Point. It's not a
> relation like a Sportscar is a Car (is-a-relationship). It's more a
> relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a
> width and length. So, it's probably better to express your Rectangle
> class like this:
>
> class Rectangle(object):
> def __init__(self, base_point, width=0, length=0):
> self.base_point = base_point
> self.width = width
> self.length = length
>
> then you go (with German names ;-)):
>
> punkt = Point(3,4)
> rechteck = Rectangle(punkt,20,30)
>
> In your Rectangle class, the __init__ method takes only two arguments
> (not counting the instance: self), but you're passing three arguments.
>
> At the beginning, the error messages are a bit confusing, because they
> count the instance as one of the arguments. So it tells you, that you
> have given 4 arguments, but you might wonder "Hey, I gave you 3".
>
> HTH,
>
> Jan
>
>>
>> punt = Point(3,4)
>> rechthoek = Rectangle (punt,20,30)
>>
>> Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
>> This one gives as error message :
>>
>> Traceback (most recent call last):
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 12, in
>> rechthoek = Rectangle (punt,20,30)
>> TypeError: __init__() takes at most 3 arguments (4 given)
>>
>> Roelof
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello, 
 
When I change everything to this :
 
class Point:
     def __init__(self, x=0, y=0): 
         self.x = x
         self.y = y
     
class Rectangle(object):
    def _init_(self, base_point, width=0, length=0):
        self.base_point = base_point
        self.width = width
        self.length = length
        
punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
I get this message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in <module>
    rechthoek = Rectangle (punt,20,30)
TypeError: object.__new__() takes no parameters
 
Roelof
  		 	   		  

From __peter__ at web.de  Sun Sep 19 18:04:25 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Sep 2010 18:04:25 +0200
Subject: [Tutor] Can this be done easly
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
Message-ID: <i75ca5$ged$1@dough.gmane.org>

Roelof Wobben wrote:

> When I change everything to this :

> I get this message :
>  
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in
>   <module>
>     rechthoek = Rectangle (punt,20,30)
> TypeError: object.__new__() takes no parameters

Hint: why does this work:
  
>      def __init__(self, x=0, y=0):

...while this doesnt:

>     def _init_(self, base_point, width=0, length=0):

Peter


From rwobben at hotmail.com  Sun Sep 19 18:07:26 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 16:07:26 +0000
Subject: [Tutor] Can this be done easly
In-Reply-To: <i75ca5$ged$1@dough.gmane.org>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>,
	<4C95FFE2.2010304@googlemail.com>,
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>,
	<i75ca5$ged$1@dough.gmane.org>
Message-ID: <SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>




----------------------------------------
> To: tutor at python.org
> From: __peter__ at web.de
> Date: Sun, 19 Sep 2010 18:04:25 +0200
> Subject: Re: [Tutor] Can this be done easly
>
> Roelof Wobben wrote:
>
>> When I change everything to this :
>
>> I get this message :
>>
>> Traceback (most recent call last):
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in
>> 
>> rechthoek = Rectangle (punt,20,30)
>> TypeError: object.__new__() takes no parameters
>
> Hint: why does this work:
>
>> def __init__(self, x=0, y=0):
>
> ...while this doesnt:
>
>> def _init_(self, base_point, width=0, length=0):
>
> Peter
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hoi, 
 
Maybe because base_point has no value ?

Roelof
  		 	   		  

From alan.gauld at btinternet.com  Sun Sep 19 18:09:37 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 19 Sep 2010 17:09:37 +0100
Subject: [Tutor] What are "singletons" good for?
References: <4C94EDE2.4040302@googlemail.com>
	<201009192341.56495.steve@pearwood.info>
Message-ID: <i75ck9$ie5$1@dough.gmane.org>



"Steven D'Aprano" <steve at pearwood.info> wrote


> < much sense about singleton v global>

> and think this makes their code "better". (I blame the Go4 for 
> making a
> religion out of design patterns which exist only to work around 
> Java's
> limitations.)

In fact the original design patterns were based around Smalltalk's
limitations since most of the Go4 were/are Smalltalk hackers. And
thus the Singleton - because Smalltalk has no concept of global
variables.

The book was registered in 1994 and released in 1995, a full year
before the first Java JDK was made publicly available.

Alan G. 



From alan.gauld at btinternet.com  Sun Sep 19 18:12:57 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 19 Sep 2010 17:12:57 +0100
Subject: [Tutor] Can this be done easly
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>,
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
Message-ID: <i75cqh$j7e$1@dough.gmane.org>


"Roelof Wobben" <rwobben at hotmail.com> wrote

> When I change everything to this :
>
> class Rectangle(object):
>    def _init_(self, base_point, width=0, length=0):
>        self.base_point = base_point
>        self.width = width
>        self.length = length
>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
>
> I get this message :
>
> Traceback (most recent call last):
>  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, 
> in <module>
>    rechthoek = Rectangle (punt,20,30)
> TypeError: object.__new__() takes no parameters

Very odd, but are you using IDLE or a similar IDE?
Have you remembered to reload the module? Just a thought...

Alan G.



From __peter__ at web.de  Sun Sep 19 18:27:54 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Sep 2010 18:27:54 +0200
Subject: [Tutor] Can this be done easly
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
	<i75ca5$ged$1@dough.gmane.org>
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>
Message-ID: <i75dm5$llf$1@dough.gmane.org>

Roelof Wobben wrote:

>> Hint: why does this work:
>>
>>> def __init__(self, x=0, y=0):
>>
>> ...while this doesnt:
>>
>>> def _init_(self, base_point, width=0, length=0):
>>
>> Peter

> Maybe because base_point has no value ?

No. One __init__ has two underscores (correct) on each side, the other 
_init_ only one (wrong).


From rwobben at hotmail.com  Sun Sep 19 19:02:32 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 17:02:32 +0000
Subject: [Tutor] FW:  Can this be done easly
In-Reply-To: <SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>,
	<4C95FFE2.2010304@googlemail.com>,
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>,
	<i75ca5$ged$1@dough.gmane.org>,
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>,
	<i75dm5$llf$1@dough.gmane.org>,
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
Message-ID: <SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>




----------------------------------------
> From: rwobben at hotmail.com
> To: __peter__ at web.de
> Subject: RE: [Tutor] Can this be done easly
> Date: Sun, 19 Sep 2010 17:01:22 +0000
>
>
>
>
> ----------------------------------------
>> To: tutor at python.org
>> From: __peter__ at web.de
>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>> Subject: Re: [Tutor] Can this be done easly
>>
>> Roelof Wobben wrote:
>>
>>>> Hint: why does this work:
>>>>
>>>>> def __init__(self, x=0, y=0):
>>>>
>>>> ...while this doesnt:
>>>>
>>>>> def _init_(self, base_point, width=0, length=0):
>>>>
>>>> Peter
>>
>>> Maybe because base_point has no value ?
>>
>> No. One __init__ has two underscores (correct) on each side, the other
>> _init_ only one (wrong).
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>

Hello,

Everybody thanks.

For this exercise :

3.Write a function named move_rect that takes a Rectangle and two parameters named dx and dy. It should change the location of the rectangle by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner.

Is this one of the possible solutions :


class Point:
    def __init__(self, x=0, y=0): 
        self.x = x
        self.y = y
     
class Rectangle(object):
    def __init__(self, base_point, width=0, length=0):
        self.base_point = base_point
        self.width = width
        self.length = length
        
def moverect(rectangle, dx, dy):
    rechthoek.base_point.y += dy
    rechthoek.base_point.x +=dx
    return rechthoek

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
test = moverect (Rectangle, 4,3) 
print rechthoek.base_point.x

Roelof 		 	   		  

From __peter__ at web.de  Sun Sep 19 20:07:05 2010
From: __peter__ at web.de (Peter Otten)
Date: Sun, 19 Sep 2010 20:07:05 +0200
Subject: [Tutor] FW:  Can this be done easly
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
	<i75ca5$ged$1@dough.gmane.org>
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>
	<i75dm5$llf$1@dough.gmane.org>
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
	<SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>
Message-ID: <i75jg5$d9h$1@dough.gmane.org>

Roelof Wobben wrote:

> For this exercise :
> 
> 3.Write a function named move_rect that takes a Rectangle and two
> parameters named dx and dy. It should change the location of the rectangle
> by adding dx to the x coordinate of corner and adding dy to the y
> coordinate of corner.
> 
> Is this one of the possible solutions :
> 
> class Point:
>     def __init__(self, x=0, y=0):
>         self.x = x
>         self.y = y
>      
> class Rectangle(object):
>     def __init__(self, base_point, width=0, length=0):
>         self.base_point = base_point
>         self.width = width
>         self.length = length
>         
> def moverect(rectangle, dx, dy):
>     rechthoek.base_point.y += dy
>     rechthoek.base_point.x +=dx
>     return rechthoek
> 
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x

At first glance I'd say so. At second glance I see that you pass the class 
and not an instance to the moverect() routine. Your program only seems to 
work because you are not using the parameter rectangle but the global 
rechthoek variable and as soon as you are trying to move rectangles with a 
different variable name everything will break.
If I were to run your program I might even find more errors or problematic 
behaviours.

In the long run it's not a sustainable model to verify the correctness of 
your programs by asking someone on the internet who is just as likely to be 
wrong as you or might even fool you.

Instead add some tests. For example, you could precalculate the expected 
position and then check if the new position meets your expectation:

r = Rectangle(Point(3, 4), 20, 30)

moverect(r, 10, 11)

if r.base_point.x == 13 and r.base_point.y == 15:
    print "looks good"
else:
    print "needs work"

Because tests are needed very often there are libraries accompanying the 
interpreter (unittest, doctest) to formalize them and for simple runtime 
checks there is the assert statement. Instead of the if...else you could 
write

assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y

Peter


From andreengels at gmail.com  Sun Sep 19 20:16:15 2010
From: andreengels at gmail.com (Andre Engels)
Date: Sun, 19 Sep 2010 20:16:15 +0200
Subject: [Tutor] FW: Can this be done easly
In-Reply-To: <SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
	<i75ca5$ged$1@dough.gmane.org>
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>
	<i75dm5$llf$1@dough.gmane.org>
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
	<SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>
Message-ID: <AANLkTikN54ES4ku5TDRSRyFVdGiKb5woHhO_bPhv6wxd@mail.gmail.com>

On Sun, Sep 19, 2010 at 7:02 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>
>
> ----------------------------------------
>> From: rwobben at hotmail.com
>> To: __peter__ at web.de
>> Subject: RE: [Tutor] Can this be done easly
>> Date: Sun, 19 Sep 2010 17:01:22 +0000
>>
>>
>>
>>
>> ----------------------------------------
>>> To: tutor at python.org
>>> From: __peter__ at web.de
>>> Date: Sun, 19 Sep 2010 18:27:54 +0200
>>> Subject: Re: [Tutor] Can this be done easly
>>>
>>> Roelof Wobben wrote:
>>>
>>>>> Hint: why does this work:
>>>>>
>>>>>> def __init__(self, x=0, y=0):
>>>>>
>>>>> ...while this doesnt:
>>>>>
>>>>>> def _init_(self, base_point, width=0, length=0):
>>>>>
>>>>> Peter
>>>
>>>> Maybe because base_point has no value ?
>>>
>>> No. One __init__ has two underscores (correct) on each side, the other
>>> _init_ only one (wrong).
>>>
>>> _______________________________________________
>>> Tutor maillist - Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> Hello,
>
> Everybody thanks.
>
> For this exercise :
>
> 3.Write a function named move_rect that takes a Rectangle and two parameters named dx and dy. It should change the location of the rectangle by adding dx to the x coordinate of corner and adding dy to the y coordinate of corner.
>
> Is this one of the possible solutions :
>
>
> class Point:
> ? ?def __init__(self, x=0, y=0):
> ? ? ? ?self.x = x
> ? ? ? ?self.y = y
>
> class Rectangle(object):
> ? ?def __init__(self, base_point, width=0, length=0):
> ? ? ? ?self.base_point = base_point
> ? ? ? ?self.width = width
> ? ? ? ?self.length = length
>
> def moverect(rectangle, dx, dy):
> ? ?rechthoek.base_point.y += dy
> ? ?rechthoek.base_point.x +=dx
> ? ?return rechthoek
>
> punt = Point(3,4)
> rechthoek = Rectangle (punt,20,30)
> test = moverect (Rectangle, 4,3)
> print rechthoek.base_point.x


This test happens to work, but your program is incorrect.

In moverect, you should work with the local variable (rectangle), not
with the global one (rechthoek), because it should be possible to call
it for any Rectangle, not just with the Rectangle that happens to be
called rechthoek. Then, when you call it, you should specify the
Rectangle that you call it for, so

test = moverect (Rectangle, 4, 3)

should be

test = moverect(rechthoek, 4, 3)

Furthermore, you do not use test (which will be null anyway), so you
can shorten this to

moverect(rechthoek, 4, 3)

-- 
Andr? Engels, andreengels at gmail.com

From rwobben at hotmail.com  Sun Sep 19 20:33:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 18:33:46 +0000
Subject: [Tutor] FW:  Can this be done easly
In-Reply-To: <i75jg5$d9h$1@dough.gmane.org>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>,
	<4C95FFE2.2010304@googlemail.com>,
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>,
	<i75ca5$ged$1@dough.gmane.org>,
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>,
	<i75dm5$llf$1@dough.gmane.org>,
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>,
	<SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>,
	<i75jg5$d9h$1@dough.gmane.org>
Message-ID: <SNT118-W377A03846B31D8A438B538AE7D0@phx.gbl>




----------------------------------------
> To: tutor at python.org
> From: __peter__ at web.de
> Date: Sun, 19 Sep 2010 20:07:05 +0200
> Subject: Re: [Tutor] FW: Can this be done easly
>
> Roelof Wobben wrote:
>
>> For this exercise :
>>
>> 3.Write a function named move_rect that takes a Rectangle and two
>> parameters named dx and dy. It should change the location of the rectangle
>> by adding dx to the x coordinate of corner and adding dy to the y
>> coordinate of corner.
>>
>> Is this one of the possible solutions :
>>
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(object):
>> def __init__(self, base_point, width=0, length=0):
>> self.base_point = base_point
>> self.width = width
>> self.length = length
>>
>> def moverect(rectangle, dx, dy):
>> rechthoek.base_point.y += dy
>> rechthoek.base_point.x +=dx
>> return rechthoek
>>
>> punt = Point(3,4)
>> rechthoek = Rectangle (punt,20,30)
>> test = moverect (Rectangle, 4,3)
>> print rechthoek.base_point.x
>
> At first glance I'd say so. At second glance I see that you pass the class
> and not an instance to the moverect() routine. Your program only seems to
> work because you are not using the parameter rectangle but the global
> rechthoek variable and as soon as you are trying to move rectangles with a
> different variable name everything will break.
> If I were to run your program I might even find more errors or problematic
> behaviours.
>
> In the long run it's not a sustainable model to verify the correctness of
> your programs by asking someone on the internet who is just as likely to be
> wrong as you or might even fool you.
>
> Instead add some tests. For example, you could precalculate the expected
> position and then check if the new position meets your expectation:
>
> r = Rectangle(Point(3, 4), 20, 30)
>
> moverect(r, 10, 11)
>
> if r.base_point.x == 13 and r.base_point.y == 15:
> print "looks good"
> else:
> print "needs work"
>
> Because tests are needed very often there are libraries accompanying the
> interpreter (unittest, doctest) to formalize them and for simple runtime
> checks there is the assert statement. Instead of the if...else you could
> write
>
> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>
> Peter
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I changed the programm to this :
 
import unittest
class Point:
    def __init__(self, x=0, y=0): 
        self.x = x
        self.y = y
     
class Rectangle(object):
    def __init__(self, base_point, width=0, length=0):
        self.base_point = base_point
        self.width = width
        self.length = length
        
def moverect(roelof, dx, dy):
    roelof.base_point.y += dy
    roelof.base_point.x +=dx
    return roelof

r = Rectangle(Point(3, 4), 20, 30) 
moverect(r, 10, 11)
assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
 
But no output at all
 
Roelof

  		 	   		  

From andreengels at gmail.com  Sun Sep 19 20:54:01 2010
From: andreengels at gmail.com (Andre Engels)
Date: Sun, 19 Sep 2010 20:54:01 +0200
Subject: [Tutor] FW: Can this be done easly
In-Reply-To: <SNT118-W377A03846B31D8A438B538AE7D0@phx.gbl>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
	<i75ca5$ged$1@dough.gmane.org>
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>
	<i75dm5$llf$1@dough.gmane.org>
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
	<SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>
	<i75jg5$d9h$1@dough.gmane.org>
	<SNT118-W377A03846B31D8A438B538AE7D0@phx.gbl>
Message-ID: <AANLkTikh8oqJN0W+-qu5A9n_SR7TpXvqqBDEBCd-RKCP@mail.gmail.com>

On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

> Hello,
>
> I changed the programm to this :
>
> import unittest
> class Point:
> ? ?def __init__(self, x=0, y=0):
> ? ? ? ?self.x = x
> ? ? ? ?self.y = y
>
> class Rectangle(object):
> ? ?def __init__(self, base_point, width=0, length=0):
> ? ? ? ?self.base_point = base_point
> ? ? ? ?self.width = width
> ? ? ? ?self.length = length
>
> def moverect(roelof, dx, dy):
> ? ?roelof.base_point.y += dy
> ? ?roelof.base_point.x +=dx
> ? ?return roelof
>
> r = Rectangle(Point(3, 4), 20, 30)
> moverect(r, 10, 11)
> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>
> But no output at all

Which output had you expected, and why?


-- 
Andr? Engels, andreengels at gmail.com

From rwobben at hotmail.com  Sun Sep 19 21:05:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 19 Sep 2010 19:05:03 +0000
Subject: [Tutor] FW: Can this be done easly
In-Reply-To: <AANLkTikh8oqJN0W+-qu5A9n_SR7TpXvqqBDEBCd-RKCP@mail.gmail.com>
References: <SNT118-W60537020E4AA099CEA8282AE7D0@phx.gbl>
	<4C95FFE2.2010304@googlemail.com>,
	<SNT118-W3946FC06E200C4ECB3709AAE7D0@phx.gbl>
	<i75ca5$ged$1@dough.gmane.org>,
	<SNT118-W34E88C2A76023D43CE480FAE7D0@phx.gbl>
	<i75dm5$llf$1@dough.gmane.org>,
	<SNT118-W447AAC420127B3280CCD67AE7D0@phx.gbl>
	<SNT118-W330B7203DF5CCE42E970FDAE7D0@phx.gbl>,
	<i75jg5$d9h$1@dough.gmane.org>
	<SNT118-W377A03846B31D8A438B538AE7D0@phx.gbl>,
	<AANLkTikh8oqJN0W+-qu5A9n_SR7TpXvqqBDEBCd-RKCP@mail.gmail.com>
Message-ID: <SNT118-W391021CC9EB01750E3DC4DAE7D0@phx.gbl>




----------------------------------------
> From: andreengels at gmail.com
> Date: Sun, 19 Sep 2010 20:54:01 +0200
> Subject: Re: [Tutor] FW: Can this be done easly
> To: rwobben at hotmail.com
> CC: tutor at python.org
>
> On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben wrote:
>
>> Hello,
>>
>> I changed the programm to this :
>>
>> import unittest
>> class Point:
>> def __init__(self, x=0, y=0):
>> self.x = x
>> self.y = y
>>
>> class Rectangle(object):
>> def __init__(self, base_point, width=0, length=0):
>> self.base_point = base_point
>> self.width = width
>> self.length = length
>>
>> def moverect(roelof, dx, dy):
>> roelof.base_point.y += dy
>> roelof.base_point.x +=dx
>> return roelof
>>
>> r = Rectangle(Point(3, 4), 20, 30)
>> moverect(r, 10, 11)
>> assert r.base_point.x == 13, "wrong x position %d" % r.base_point.x
>> assert r.base_point.y == 15, "wrong y position %d" % r.base_point.y
>>
>> But no output at all
>
> Which output had you expected, and why?
>
>
> --
> Andr? Engels, andreengels at gmail.com
 
Hello, 
 
Oke, I see it now. There is only output when it's not right.
 
Roelof

  		 	   		  

From steve at pearwood.info  Mon Sep 20 01:50:04 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 20 Sep 2010 09:50:04 +1000
Subject: [Tutor] What are "singletons" good for?
In-Reply-To: <i75ck9$ie5$1@dough.gmane.org>
References: <4C94EDE2.4040302@googlemail.com>
	<201009192341.56495.steve@pearwood.info>
	<i75ck9$ie5$1@dough.gmane.org>
Message-ID: <201009200950.05373.steve@pearwood.info>

On Mon, 20 Sep 2010 02:09:37 am Alan Gauld wrote:
> "Steven D'Aprano" <steve at pearwood.info> wrote
>
> > < much sense about singleton v global>
> >
> > and think this makes their code "better". (I blame the Go4 for
> > making a
> > religion out of design patterns which exist only to work around
> > Java's
> > limitations.)
>
> In fact the original design patterns were based around Smalltalk's
> limitations since most of the Go4 were/are Smalltalk hackers. And
> thus the Singleton - because Smalltalk has no concept of global
> variables.
>
> The book was registered in 1994 and released in 1995, a full year
> before the first Java JDK was made publicly available.

Fair enough, I stand corrected. Thank you.

Nevertheless, the design pattern book has been picked up by the Java 
crowd and elevated almost to the status of a religion, rather than a 
set of useful tools. Especially the Singleton pattern, probably because 
it's the only one which most programmers can understand *wink*



-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 20 02:22:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 20 Sep 2010 10:22:07 +1000
Subject: [Tutor] plotting pixels
In-Reply-To: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
References: <11691343.1284833886583.JavaMail.root@elwamui-royal.atl.sa.earthlink.net>
Message-ID: <201009201022.08180.steve@pearwood.info>

Hello Ken,

On Sun, 19 Sep 2010 04:18:06 am Ken Oliver wrote:
> <HEAD>
> <STYLE>body{font-size:10pt;font-family:arial,sans-serif;background-co
>lor:#ffffff;color:black;}p{margin:0px;}</STYLE>
> <META name=GENERATOR content="MSHTML 8.00.6001.18939"></HEAD>
> <BODY><BR><BR><BR>
> <BLOCKQUOTE style="BORDER-LEFT: #0000ff 2px solid; PADDING-LEFT: 5px;
[lots more HTML junk]


Ken, this is what I see when I read your emails. Could you please find 
the setting in your email client to send plain text as well as HTML (or 
what is wrongly called "rich text" by some email clients) and turn it 
on? Unfortunately I've never used EarthLink Zoo Mail 1.0, so I can't 
tell you how.

Not only is HTML-only posting considered rude by millions of people, but 
it's also counter-productive. Pure HTML is one of the stronger 
indications of Spam email, almost as strong as mentioning that word 
that starts with V and sounds like Niagara Falls, and so chances are 
good that some of your emails are being flagged as spam by anti-spam 
checks.


-- 
Steven D'Aprano

From wallenpb at gmail.com  Mon Sep 20 04:27:01 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 19 Sep 2010 21:27:01 -0500
Subject: [Tutor] plotting pixels
In-Reply-To: <i74enp$a5h$1@dough.gmane.org>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
	<813627.27084.qm@web86704.mail.ird.yahoo.com>
	<i74enp$a5h$1@dough.gmane.org>
Message-ID: <AANLkTim8_X7WJSpoK1ave-cZeZYwd=4EO1=qvqQ8ciN8@mail.gmail.com>

On Sun, Sep 19, 2010 at 2:40 AM, Lie Ryan <lie.1296 at gmail.com> wrote:

>
> More slowly and takes huge amount of memory. A single Tk canvas object
> takes at least 14 words (= 114 bytes in 64-bit OS = 56 bytes in 32-bit
> OS) + the amount of data is needed to store the `kind of object`. That's
> much larger than the ideal 3 bytes per pixel (or 4 bytes with alpha).
>
> Tkinter's Canvas intentionally doesn't provide create_pixel() because
> unlike most other Canvas implementations, Tkinter's Canvas holds a
> stateful canvas objects instead of a simple drawing surface. Providing a
> create_pixel() will be too tempting for abuse, which would make the
> canvas unbearably slow and memory consuming. In short, Canvas is not
> designed for pixel drawing.
>
> > Digging a little deeper it seems the idiomatic way to do this in Python
> > is to use PIL the Python Imaging Library to create a GIF or bitmap
> > image and then insert that into Tkinters cancvas as an image object.
> >
> > The Pil ImageDraw class has a point() ethod
>
> If you need to plot pixels, do use pygame, PIL, or at least the
> PhotoImage trick.
>
> Thanks for the feedback!   That does make a lot a sense as to why a
pixel_plot() type function would not be directly implemented in Canvas.  As
this is still largely a learning exercise for me, I may try more than one
approach.  I think first I will try the PhotoImage approach, which might be
the most efficient method.  However, I will definitely give Pygame a try.  I
have seen several programs that were written in Pygame and I am really
impressed!  It is obviously designed to task.

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100919/c8c3d170/attachment-0001.html>

From mnshtb at gmail.com  Mon Sep 20 16:16:09 2010
From: mnshtb at gmail.com (Michael Scharf)
Date: Mon, 20 Sep 2010 10:16:09 -0400
Subject: [Tutor] Why are arguments sometimes on the left side?
Message-ID: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>

Hi,


Why is it



   list0.extend(list1)



and not


   extend(list 0, list1)



or


   stri0 = stri0.strip()


and not


   stri0 = strip(stri0)



Why have arguments on the left side at all, when usually the dot notation
left to right implies a hierarchical relation: file.class or class.method
etc.



I googled this, but didn?t find it.



Thank you,

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100920/942925eb/attachment.html>

From joel.goldstick at gmail.com  Mon Sep 20 16:28:29 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 20 Sep 2010 10:28:29 -0400
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
Message-ID: <AANLkTimjeXfEcQsoHMf0wLt4T0pNdH=efxZWFAJi8=NV@mail.gmail.com>

On Mon, Sep 20, 2010 at 10:16 AM, Michael Scharf <mnshtb at gmail.com> wrote:

>
> Hi,
>
>
> Why is it
>
>
>
>    list0.extend(list1)
>

because extend is a list method

>
>
> and not
>
>
>    extend(list 0, list1)
>
>
>
> or
>
>
>    stri0 = stri0.strip()
>
>
> strip is a string method


> and not
>
>
>    stri0 = strip(stri0)
>
>
>
> Why have arguments on the left side at all, when usually the dot notation
> left to right implies a hierarchical relation: file.class or class.method
> etc.
>
>
>
> I googled this, but didn?t find it.
>
>
>
> Thank you,
>
> Mike
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100920/af402451/attachment.html>

From mehgcap at gmail.com  Mon Sep 20 17:00:46 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 20 Sep 2010 11:00:46 -0400
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
Message-ID: <AANLkTimgmxVLszxFYwqATCkpMrWrZNV8wnqzJavNr3qv@mail.gmail.com>

On 9/20/10, Michael Scharf <mnshtb at gmail.com> wrote:
> Hi,
>
>
> Why is it
>
>
>
>    list0.extend(list1)
>
>
>
> and not
>
>
>    extend(list 0, list1)
>
>
>
> or
>
>
>    stri0 = stri0.strip()
>
>
> and not
>
>
>    stri0 = strip(stri0)

This is because you are calling methods on objects, in this case
strings and lists. You create a list, then want to extend it with
another list. Think of it as operating on list0, so, to operate on it,
you call one of its functions (extend). Some functions do not work
this way, such as print, since print is not a function under an object
or class. If I create a dog class, then create Fluffy as an object:
class dog(object):
 def __init__(self, name):
  self.name=name
 def bark(self):
  print("bark")

f=dog("Fluffy")

Okay, we now have a dog named Fluffy, which is just one instance of
our dog class. With the way you would want to do things, I would have
to say
bark(f)
But what is bark? Where is it defined? You can see it is in the dog
class, but Python cannot; you passed a dog instance to bark(), but
that will not tell Python to search in the dog class to find the bark
method. Saying
f.bark()
will work since it tells Python:
take this instance of dog, called f, and call its bark method. The
bark method is in the dog class since bark is being called on a dog
object (remember that an object is just an instance of a class).
I hope this made some sense.
>
>
>
> Why have arguments on the left side at all, when usually the dot notation
> left to right implies a hierarchical relation: file.class or class.method
> etc.
Exactly: list.function (such as list0.extend) is just the same as
class.function, since a list is a class and list0 is an instance of
the list class, so you are just calling list's extend function on a
particular list, list0 in this case.
>
>
>
> I googled this, but didn?t find it.
>
>
>
> Thank you,
>
> Mike
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From mnshtb at gmail.com  Mon Sep 20 17:04:49 2010
From: mnshtb at gmail.com (Michael Scharf)
Date: Mon, 20 Sep 2010 11:04:49 -0400
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <AANLkTimgmxVLszxFYwqATCkpMrWrZNV8wnqzJavNr3qv@mail.gmail.com>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
	<AANLkTimgmxVLszxFYwqATCkpMrWrZNV8wnqzJavNr3qv@mail.gmail.com>
Message-ID: <AANLkTinXLVDQ2Mv=iB-YQii8A3nwRQHteVAwVJGB7sw1@mail.gmail.com>

Okay, we now have a dog named Fluffy, which is just one instance of
> our dog class. With the way you would want to do things, I would have
> to say
> bark(f)
> But what is bark? Where is it defined? You can see it is in the dog
> class, but Python cannot; you passed a dog instance to bark(), but
> that will not tell Python to search in the dog class to find the bark
> method. Saying
> f.bark()
> will work since it tells Python:
> take this instance of dog, called f, and call its bark method. The
> bark method is in the dog class since bark is being called on a dog
> object (remember that an object is just an instance of a class).
> I hope this made some sense. <http://www.facebook.com/mehgcap>



This is terrific --- very clarifying.  Thank you so much.

Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100920/b0fa3c24/attachment.html>

From aeneas24 at priest.com  Mon Sep 20 17:19:29 2010
From: aeneas24 at priest.com (aeneas24 at priest.com)
Date: Mon, 20 Sep 2010 11:19:29 -0400
Subject: [Tutor] Can't process all my files (need to close?)
Message-ID: <8CD26EE5AC570D8-7E8-1B8B@web-mmc-d02.sysops.aol.com>


My Python script needs to process 45,000 files, but it seems to blow up after about 10,000. Note that I'm outputting bazillions of rows to a csv, so that may be part of the issue.

Here's the error I get (I'm running it through IDLE on Windows 7):

Microsoft Visual C++ Runtime Library
Runtime Error!
Program: C:\Python26\pythonw.exe
This application has requested the Runtime to terminate it in an usual way. 

I think this might be because I don't specifically close the files I'm reading. Except that I'm not quite sure where to put the close. I have 3 places where I would think it might work but I'm not sure which one works or how exactly to do the closing (what it is I append ".close()" to). 

1) During the self.string here:

class ReviewFile:
# In our movie corpus, each movie is one text file. That means that each text file has some "info" about the movie (genre, director, name, etc), followed by a bunch of reviews. This class extracts the relevant information about the movie, which is then attached to review-specific information. 
    def __init__(self, filename):
        self.filename = filename
        self.string = codecs.open(filename, "r", "utf8").read()
        self.info = self.get_fields(self.get_field(self.string, "info")[0])
        review_strings = self.get_field(self.string, "review")
        review_dicts = map(self.get_fields, review_strings)
        self.reviews = map(Review, review_dicts)

2) Maybe here?
def reviewFile ( file, args):
    for file in glob.iglob("*.txt"):
      print "  Reviewing...." + file
      rf = ReviewFile(file)

3) Or maybe here?

def reviewDirectory ( args, dirname, filenames ):
   print 'Directory',dirname
   for fileName in filenames:
      reviewFile( dirname+'/'+fileName, args )      
def main(top_level_dir,csv_out_file_name):
    csv_out_file  = open(str(csv_out_file_name), "wb")
    writer = csv.writer(csv_out_file, delimiter=',')
    os.path.walk(top_level_dir, reviewDirectory, writer )
main(".","output.csv")

Thanks very much for any help!

Tyler


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100920/db85ae51/attachment-0001.html>

From mail at timgolden.me.uk  Mon Sep 20 17:41:28 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Mon, 20 Sep 2010 16:41:28 +0100
Subject: [Tutor] Can't process all my files (need to close?)
In-Reply-To: <8CD26EE5AC570D8-7E8-1B8B@web-mmc-d02.sysops.aol.com>
References: <8CD26EE5AC570D8-7E8-1B8B@web-mmc-d02.sysops.aol.com>
Message-ID: <4C9780A8.6040403@timgolden.me.uk>

On 20/09/2010 16:19, aeneas24 at priest.com wrote:
> My Python script needs to process 45,000 files, but it seems to blow
> up after about 10,000. Note that I'm outputting
> bazillions of rows to a csv, so that may be part of the issue.
>
> Here's the error I get (I'm running it through IDLE on Windows 7):
>
> Microsoft Visual C++ Runtime Library Runtime Error! Program:
> C:\Python26\pythonw.exe This application has requested the Runtime to
> terminate it in an usual way.

OK. Just for starters (and to eliminate other possible side-issues)
can you run the same code directly from the command line using
c:\python26\python.exe?

ie just open cmd.exe, cd to the directory where your code is and type:

c:\python26\python.exe <mystuff.py>

I assume that the same thing will happen, but if it doesn't then
that points the finger at IDLE or, possibly, at pythonw.exe. (And
might also give you a workaround).

> I think this might be because I don't specifically close the files
> I'm reading. Except that I'm not quite sure where to put the close.

On this note, it's worth learning about context managers. Or, rather,
the fact that files can be context-managed. That means that you can
open a file using the with ...: construct and it will automatically
close:

<code>

with open ("blah.csv", "wb") as f:
   f.write ("blah")

# at this point f will have been closed

</code>

> 1) During the self.string here:
>
> class ReviewFile: # In our movie corpus, each movie is one text file.
> That means that each text file has some "info" about the movie
> (genre, director, name, etc), followed by a bunch of reviews. This
> class extracts the relevant information about the movie, which is
> then attached to review-specific information. def __init__(self,
> filename): self.filename = filename self.string =
> codecs.open(filename, "r", "utf8").read() self.info =
> self.get_fields(self.get_field(self.string, "info")[0])
> review_strings = self.get_field(self.string, "review") review_dicts =
> map(self.get_fields, review_strings) self.reviews = map(Review,
> review_dicts)

So that could become:

<code>
with codecs.open (filename, "r", "utf8") as f:
   self.string = f.read ()

</code>

>
> 2) Maybe here? def reviewFile ( file, args): for file in
> glob.iglob("*.txt"): print "  Reviewing...." + file rf =
> ReviewFile(file)

Here, with that many files, I'd strongly recommend using the
FindFilesIterator exposed in the win32file module of the pywin32
extensions. glob.iglob simply does a glob (creating a moderately
large in-memory list) whose iterator it then returns. The
FindFilesIterator actually calls underlying Windows code to
iterate lazily over the files in the directory.

>
> 3) Or maybe here?
>
> def reviewDirectory ( args, dirname, filenames ): print
> 'Directory',dirname for fileName in filenames: reviewFile(
> dirname+'/'+fileName, args ) def
> main(top_level_dir,csv_out_file_name): csv_out_file  =
> open(str(csv_out_file_name), "wb") writer = csv.writer(csv_out_file,
> delimiter=',') os.path.walk(top_level_dir, reviewDirectory, writer )
> main(".","output.csv")

Again, here, you might use:

<code>
with open (str (csv_out_file_name), "wb") as csv_out_file:
   writer = csv.writer (csv_out_file, delimiter=",")

</code>

I'm fairly sure that the default delimiter is already "," so you
shouldn't need that, and I'm not sure where csv_out_file_name
is coming from but you almost certainly don't need to convert it
explicitly to a string.

Note, also, that the os.walk (*not* os.path.walk) function is often
an easier fit since it iterates lazily over directories, yielding a
(dirpath, dirnames, filenames) 3-tuple which you can then act upon.
However, you may prefer the callback style of the older os.path.walk.

TJG

From emile at fenx.com  Mon Sep 20 18:04:39 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 20 Sep 2010 09:04:39 -0700
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
Message-ID: <i780mo$go4$1@dough.gmane.org>

On 9/20/2010 7:16 AM Michael Scharf said...
> Why is it
>     list0.extend(list1)
> and not
>     extend(list 0, list1)
> or
>     stri0 = stri0.strip()
> and not
>     stri0 = strip(stri0)
> Why have arguments on the left side at all, when usually the dot notation
> left to right implies a hierarchical relation: file.class or class.method
> etc.
>

You can also have it your way...

 >>> def extend(*args):
...     try:
...         args[0].extend(*args[1:])
...     except:
...         raise AttributeError
...
 >>>
...
 >>>
 >>> a = []
 >>> a.extend([1,2,3])
 >>> a
[1, 2, 3]
 >>> extend(a,[4,5,6])
 >>> a
[1, 2, 3, 4, 5, 6]
 >>>


Emile



From joel.goldstick at gmail.com  Mon Sep 20 18:54:08 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 20 Sep 2010 12:54:08 -0400
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <i780mo$go4$1@dough.gmane.org>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>
	<i780mo$go4$1@dough.gmane.org>
Message-ID: <AANLkTi=11=Ct6pfmTKGSJE_1RMsZuCrKXyyXeY3LuoCS@mail.gmail.com>

On Mon, Sep 20, 2010 at 12:04 PM, Emile van Sebille <emile at fenx.com> wrote:

> On 9/20/2010 7:16 AM Michael Scharf said...
>
>  Why is it
>>    list0.extend(list1)
>> and not
>>    extend(list 0, list1)
>> or
>>    stri0 = stri0.strip()
>> and not
>>    stri0 = strip(stri0)
>> Why have arguments on the left side at all, when usually the dot notation
>> left to right implies a hierarchical relation: file.class or class.method
>> etc.
>>
>>
> You can also have it your way...
>
> >>> def extend(*args):
> ...     try:
> ...         args[0].extend(*args[1:])
> ...     except:
> ...         raise AttributeError
> ...
> >>>
> ...
> >>>
> >>> a = []
> >>> a.extend([1,2,3])
> >>> a
> [1, 2, 3]
> >>> extend(a,[4,5,6])
> >>> a
> [1, 2, 3, 4, 5, 6]
> >>>
>
>
> Emile
>
>
That's pretty creative I think, but not sure its quite on the mark for
beginners? ;)

Anyway, I was quick with my answer.  This is a good place to learn about
list and string methods:

http://docs.python.org/library/stdtypes.html#built-in-types



>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100920/0c7dcb1e/attachment.html>

From emile at fenx.com  Mon Sep 20 19:40:09 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 20 Sep 2010 10:40:09 -0700
Subject: [Tutor] Why are arguments sometimes on the left side?
In-Reply-To: <AANLkTi=11=Ct6pfmTKGSJE_1RMsZuCrKXyyXeY3LuoCS@mail.gmail.com>
References: <AANLkTinkE=fUnMmYtPzf2ohzjL7K2L7jBb6_Q4xduaQ4@mail.gmail.com>	<i780mo$go4$1@dough.gmane.org>
	<AANLkTi=11=Ct6pfmTKGSJE_1RMsZuCrKXyyXeY3LuoCS@mail.gmail.com>
Message-ID: <i7869q$cso$1@dough.gmane.org>

On 9/20/2010 9:54 AM Joel Goldstick said...
> That's pretty creative I think, but not sure its quite on the mark for
> beginners? ;)

With this one fitting into context so easily, it seemed appropriate.

Emile


From oberoc at gmail.com  Tue Sep 21 17:37:42 2010
From: oberoc at gmail.com (Tino Dai)
Date: Tue, 21 Sep 2010 11:37:42 -0400
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
Message-ID: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>

Hi All,

     In my journey from a hacker to a professional software developer, I
have started to learn
the finer points of Test Drive Development via Django (no questions about
Django though). I am
torn between the DocTest and UnitTest. I like the one "fileness" of the
DocTest, but am concerned
about the length of my tests being several orders of magnitude bigger than
the actual code. I
like the UnitTest having a separate file but am worried about the tests
getting lost or never getting
executed because a junior developer doesn't know about them. I'm wondering
in respect to TDD, which
is better or is it a matter of taste?

TIA,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/4ef7e18b/attachment.html>

From jammer10000 at gmail.com  Tue Sep 21 18:03:41 2010
From: jammer10000 at gmail.com (Joe Bennett)
Date: Tue, 21 Sep 2010 11:03:41 -0500
Subject: [Tutor] Opening C++ binary files
Message-ID: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>

I have some binary files created by a program written in C++... Anyone
have any experience with this and willing to share? ACSII test is
easy, but not sure how the rest is encoded....????




-Joe

From joel.goldstick at gmail.com  Tue Sep 21 18:34:02 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 21 Sep 2010 12:34:02 -0400
Subject: [Tutor] Opening C++ binary files
In-Reply-To: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
References: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
Message-ID: <AANLkTikY26vURUSi3aNSGsR_4fm3QH6VkRU-QHrBq6Hh@mail.gmail.com>

On Tue, Sep 21, 2010 at 12:03 PM, Joe Bennett <jammer10000 at gmail.com> wrote:

> I have some binary files created by a program written in C++... Anyone
> have any experience with this and willing to share? ACSII test is
> easy, but not sure how the rest is encoded....????
>
>
>
>
> -Joe
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

fileobj = open(filename, mode='wb')

will open the file.  Do you have any documentation on the file structure?



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/c5fc0a74/attachment.html>

From bgailer at gmail.com  Tue Sep 21 19:23:26 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 21 Sep 2010 13:23:26 -0400
Subject: [Tutor] Opening C++ binary files
In-Reply-To: <AANLkTikY26vURUSi3aNSGsR_4fm3QH6VkRU-QHrBq6Hh@mail.gmail.com>
References: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
	<AANLkTikY26vURUSi3aNSGsR_4fm3QH6VkRU-QHrBq6Hh@mail.gmail.com>
Message-ID: <4C98EA0E.7050502@gmail.com>

  On 9/21/2010 12:34 PM, Joel Goldstick wrote:
>
>
> On Tue, Sep 21, 2010 at 12:03 PM, Joe Bennett <jammer10000 at gmail.com 
> <mailto:jammer10000 at gmail.com>> wrote:
>
>     I have some binary files created by a program written in C++... Anyone
>     have any experience with this and willing to share? ACSII test is
>     easy, but not sure how the rest is encoded....????
>
>
>
>
>     -Joe
>     _______________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     http://mail.python.org/mailman/listinfo/tutor
>
>
> fileobj = open(filename, mode='wb')
Did you mean "rb"? OP says files were written by another program.
> will open the file.  Do you have any documentation on the file structure?
>

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/60d83838/attachment.html>

From joel.goldstick at gmail.com  Tue Sep 21 19:38:58 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 21 Sep 2010 13:38:58 -0400
Subject: [Tutor] Opening C++ binary files
In-Reply-To: <4C98EA0E.7050502@gmail.com>
References: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
	<AANLkTikY26vURUSi3aNSGsR_4fm3QH6VkRU-QHrBq6Hh@mail.gmail.com>
	<4C98EA0E.7050502@gmail.com>
Message-ID: <AANLkTimWPHB9EXZ24HYhAN7E1OCnZ5NgHpWGVRYS5+r7@mail.gmail.com>

On Tue, Sep 21, 2010 at 1:23 PM, bob gailer <bgailer at gmail.com> wrote:

>  On 9/21/2010 12:34 PM, Joel Goldstick wrote:
>
>
>
> On Tue, Sep 21, 2010 at 12:03 PM, Joe Bennett <jammer10000 at gmail.com>wrote:
>
>> I have some binary files created by a program written in C++... Anyone
>> have any experience with this and willing to share? ACSII test is
>> easy, but not sure how the rest is encoded....????
>>
>>
>>
>>
>> -Joe
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> fileobj = open(filename, mode='wb')
>
>  Did you mean "rb"? OP says files were written by another program.
>

oops.. of course!

>
>  will open the file.  Do you have any documentation on the file structure?
>
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/b793a6b7/attachment.html>

From joel.goldstick at gmail.com  Tue Sep 21 20:49:53 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 21 Sep 2010 14:49:53 -0400
Subject: [Tutor] Opening C++ binary files
In-Reply-To: <4C98EA0E.7050502@gmail.com>
References: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
	<AANLkTikY26vURUSi3aNSGsR_4fm3QH6VkRU-QHrBq6Hh@mail.gmail.com>
	<4C98EA0E.7050502@gmail.com>
Message-ID: <AANLkTiki4+Ft6KgZ=uGs1a72X_J3eR=u70_kbnm5wr6t@mail.gmail.com>

On Tue, Sep 21, 2010 at 1:23 PM, bob gailer <bgailer at gmail.com> wrote:
> On 9/21/2010 12:34 PM, Joel Goldstick wrote:
>
> On Tue, Sep 21, 2010 at 12:03 PM, Joe Bennett <jammer10000 at gmail.com> wrote:
>>
>> I have some binary files created by a program written in C++... Anyone
>> have any experience with this and willing to share? ACSII test is
>> easy, but not sure how the rest is encoded....????
>>
>>
>>
>>
>> -Joe
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> fileobj = open(filename, mode='wb')
>
> Did you mean "rb"? OP says files were written by another program.
>
> will open the file.? Do you have any documentation on the file structure?
>
>
I have not done this, but googling around I found a python library
called struct which has methods for reading C structured data, which
sounds like what you are looking for.  Go to your python shell, import
struct and type help(struct) to start.  Obviously you won't get far
unless you have a spec for how your data is structured in the file

-- 
Joel Goldstick

From jojo.mwebaze at gmail.com  Tue Sep 21 22:02:00 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Tue, 21 Sep 2010 22:02:00 +0200
Subject: [Tutor] intercepting and recored I/O function calls
In-Reply-To: <i7062s$388$1@dough.gmane.org>
References: <AANLkTinfWJKutb+H-QL7ZwVn+E0FvEuUJzWxNqnFPQ6=@mail.gmail.com>
	<i6reb1$h7l$1@dough.gmane.org>
	<AANLkTimLHnYQsbnpU+JDMhaKamr-eczc4AzZsiDh1Bzw@mail.gmail.com>
	<alpine.LNX.2.00.1009161816140.18450@paprika.renesys.com>
	<AANLkTimikH+vo9sFA=jOpBU1suHMPbGp-GvTP9joHgcA@mail.gmail.com>
	<i7062s$388$1@dough.gmane.org>
Message-ID: <AANLkTik9DCezcLRrqkrgBnTn9_kSGqea0M5K_kp0CP6d@mail.gmail.com>

I found this recipe quite related

http://code.activestate.com/recipes/198078/

it logs all methods calls with their parameters and return values.. Can this
be modified to include any other outputs of the module, which are not
specified with the return statement.

cheers



On Fri, Sep 17, 2010 at 6:47 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> "Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote
>
>  My applogies to begin with,  it seems i didnt state my problem clearly for
>> this particular case - perharps I/O was not the best way to describe my
>> problem.
>>
>
> Hmmm, perhaps not! :-)
>
>
>  Specifically, i would like to track all inputs/output to modules/functions
>> -
>> if a module  retrieved and used files and run some analysis on them and
>> produced other files in return, i would like to take not of this. i.e what
>> i
>> want is to recored input and outputs to a module. and also to record all
>> paramaters, attribute vaules used by the same module.
>>
>
> You could do some of that with static code analysis I think.
> And while I'm sure you could do this by delving into the innards of
> Python it will be a lot of work and I'm not sure what the impact
> would be on the performance of your code.
>
>
>  I thought i would build a wrapper around the orignial python program or
>> probably pick this information at OS level.
>>
>
> I don't think the OS will have much of what you want you will need to
> look inside Python itself I think. It might be best to tweak the
> interpreter
> to trap those details but that would need to be done in C. And it would
> slow the interpreter down for everything.
>
> The OS knows how your app is interacting with the network and file
> system but it doesn't know about the interactons between modules
> inside Python. Maybe there are some of the more obscure modules
> in the standard library that allow monitoring. The debug and profiling
> modules might yield clues too.
>
> An interesting challenge and I'm not sure how I'd go about it myself.
> Might be a good one to try on the main comp.lang.python list, its
> certainly not typical newbie stuff!
>
> Alan G.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/68768787/attachment.html>

From chuck.mayers at gmail.com  Tue Sep 21 22:50:38 2010
From: chuck.mayers at gmail.com (Chuck Mayers)
Date: Tue, 21 Sep 2010 15:50:38 -0500
Subject: [Tutor] trouble with a small Tkinter example
Message-ID: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>

Hello,

I'm having trouble with this small example program:

http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29

When I run it, I only get a blank grey window. I'm running Python 2.6 under
Windows XP.

If there's a problem with the code, I can't see it... it seems like it
should work. Can anyone else try this and see if it works for them?


If I stick this line in before the loop, it does draw a red line, so I know
my copy of Python/Tkinter is working:
canvas.create_line(10, 100, 5, 50 , fill='red')
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/1db8529f/attachment.html>

From lists at justuber.com  Tue Sep 21 23:06:50 2010
From: lists at justuber.com (lists)
Date: Tue, 21 Sep 2010 22:06:50 +0100
Subject: [Tutor] Getting/setting attributes
Message-ID: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>

Hi tutors,

I'm trying to each myself programming and come from a background in
system administration with some experience in scripting (so I'm very
new to it).

Currently I'm grappling with the concept of object orientating
programming and have a question about setting & getting attributes.

As I understand it, it makes most sense to set/get the attribute of an
object using a method rather than doing it directly. I've been reading
various ways of doing this, and the information seems a little
contradictory.

I've muddled my way through the code below to try and force setting or
getting the 'address' attribute through the address method rather than
allowing direct access.

Does this make sense to you?

Ta, Chris.

class Computer(object):

   def __init__(self):
       """instantiate the class with default values"""
       self.address = ""

   @property # use the property.getter decorator on this method
   def address(self):
       return self._address

   @address.setter #use the property.setter decorator on this method
   def address(self, addrvalue):
       self._address = addrvalue

computer1 = Computer()
computer1.address = "test"
print computer1.address

From evert.rol at gmail.com  Tue Sep 21 23:10:29 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 21 Sep 2010 23:10:29 +0200
Subject: [Tutor] trouble with a small Tkinter example
In-Reply-To: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
References: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
Message-ID: <DDF3492B-3C43-4672-B3B5-32A9B62CE6CD@gmail.com>

> I'm having trouble with this small example program:
> 
> http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29
> 
> When I run it, I only get a blank grey window. I'm running Python 2.6 under Windows XP.
> 
> If there's a problem with the code, I can't see it... it seems like it should work. Can anyone else try this and see if it works for them?

It appears that Tkinter (or probably the underling tcl/tk) is smart: if you create a line with the same start and end points, it won't draw a line.
Try it: create_line(10, 100, 10, 100, fill='red') won't work.


> If I stick this line in before the loop, it does draw a red line, so I know my copy of Python/Tkinter is working:
> canvas.create_line(10, 100, 5, 50 , fill='red')



From emile at fenx.com  Tue Sep 21 23:13:50 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 21 Sep 2010 14:13:50 -0700
Subject: [Tutor] trouble with a small Tkinter example
In-Reply-To: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
References: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
Message-ID: <i7b76h$9u8$1@dough.gmane.org>

On 9/21/2010 1:50 PM Chuck Mayers said...
> Hello,
>
> I'm having trouble with this small example program:
>
> http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29
>
> When I run it, I only get a blank grey window. I'm running Python 2.6 under
> Windows XP.

It looks like they've got you assembling the program from bits and 
pieces as it's presented and reviewed.  Can you post your program as 
you've reassembled it so we can see what's actually coded?

Emile


From chuck.mayers at gmail.com  Tue Sep 21 23:20:04 2010
From: chuck.mayers at gmail.com (Chuck Mayers)
Date: Tue, 21 Sep 2010 16:20:04 -0500
Subject: [Tutor] trouble with a small Tkinter example
In-Reply-To: <i7b76h$9u8$1@dough.gmane.org>
References: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
	<i7b76h$9u8$1@dough.gmane.org>
Message-ID: <AANLkTinbXduS_QrbNKgNXYg074yzOQucfvk4iN6TLUaT@mail.gmail.com>

There is a not-very-obvious 'Download Code' link at the very bottom of the
article.

Direct link:
http://en.literateprograms.org/Special:Downloadcode/Bresenham%27s_line_algorithm_%28Python%29


On Tue, Sep 21, 2010 at 4:13 PM, Emile van Sebille <emile at fenx.com> wrote:


> It looks like they've got you assembling the program from bits and pieces
> as it's presented and reviewed.  Can you post your program as you've
> reassembled it so we can see what's actually coded?
>
> Emile
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/2512c68f/attachment-0001.html>

From emile at fenx.com  Tue Sep 21 23:43:16 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 21 Sep 2010 14:43:16 -0700
Subject: [Tutor] trouble with a small Tkinter example
In-Reply-To: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
References: <AANLkTi=m1CA=Vc6bpK8hSvZAhNGDF+f6NKS1_wvtHGRh@mail.gmail.com>
Message-ID: <i7b8tn$ha6$1@dough.gmane.org>

On 9/21/2010 1:50 PM Chuck Mayers said...
> Hello,
>
> I'm having trouble with this small example program:
>
> http://en.literateprograms.org/Bresenham%27s_line_algorithm_%28Python%29
>
> When I run it, I only get a blank grey window. I'm running Python 2.6 under
> Windows XP.
>
> If there's a problem with the code, I can't see it... it seems like it
> should work. Can anyone else try this and see if it works for them?
>
>
> If I stick this line in before the loop, it does draw a red line, so I know
> my copy of Python/Tkinter is working:
> canvas.create_line(10, 100, 5, 50 , fill='red')


Using this form of the line,

canvas.create_line(xstart, ystart, xend, yend, fill="red")

seems to do it, although I can't say what versions allowed the author to 
(apparently successfully) write

canvas.draw_line(xstart, ystart, xend, yend, color="blue")

HTH,

Emile



From lists at justuber.com  Tue Sep 21 23:46:11 2010
From: lists at justuber.com (lists)
Date: Tue, 21 Sep 2010 22:46:11 +0100
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
Message-ID: <AANLkTi=NSV4RN_L194khD_m0-eJF42d-E3tnM+tcZnmS@mail.gmail.com>

> Currently I'm grappling with the concept of object orientating
> programming and have a question about setting & getting attributes.

Oops, just re-read that email. Anyone spot the obvious typo... Ahemmm
of course I meant object orientated ;-)

Chris

From lists at justuber.com  Wed Sep 22 00:05:08 2010
From: lists at justuber.com (lists)
Date: Tue, 21 Sep 2010 23:05:08 +0100
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <AANLkTimuw7kWLfXi41+BXb1kg-bbVLOdX71YBmkCbsZS@mail.gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
	<AANLkTi=NSV4RN_L194khD_m0-eJF42d-E3tnM+tcZnmS@mail.gmail.com>
	<AANLkTimuw7kWLfXi41+BXb1kg-bbVLOdX71YBmkCbsZS@mail.gmail.com>
Message-ID: <AANLkTim1BKsuktmYeopsxzP9W700NSgGava2nOCTutc3@mail.gmail.com>

>> > Currently I'm grappling with the concept of object orientating
>>
>> Oops, just re-read that email. Anyone spot the obvious typo... Ahemmm
>> of course I meant object orientated ;-)
>
>
> Actually I believe you mean object *oriented*.
> -Wayne

Wow, spelling lessons too. And I thought this place only helped people
out with Python ;-)

I hope you'll forgive my mistake. I'm English, although we invented
the language I guess sometimes we have to Americanise our speech to
fit in with common technical convention  :-P.

http://www.english-for-students.com/Oriented-or-Orientated.html

Thanks Wayne,

Chris

From bgailer at gmail.com  Wed Sep 22 00:16:38 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 21 Sep 2010 18:16:38 -0400
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
Message-ID: <4C992EC6.40909@gmail.com>

  On 9/21/2010 5:06 PM, lists wrote:
> Hi tutors,
>
> I'm trying to each myself programming and come from a background in
> system administration with some experience in scripting (so I'm very
> new to it).
>
> Currently I'm grappling with the concept of object orientating
> programming and have a question about setting&  getting attributes.
>
> As I understand it, it makes most sense to set/get the attribute of an
> object using a method rather than doing it directly.

My opinion - unless there is some verification or translation or action 
required it is better (easier, clearer) to just access and assign the 
attribute directly.

> I've been reading various ways of doing this, and the information seems a little
> contradictory.
>
Example, please?
> I've muddled my way through the code below to try and force setting or
> getting the 'address' attribute through the address method rather than
> allowing direct access.
Just because you have a getter and setter does not prohibit direct 
reference to _address.
> Does this make sense to you?
>
>
> class Computer(object):
>
>     def __init__(self):
>         """instantiate the class with default values"""
>         self.address = ""
>
I suggest (if you want to go the setter/getter route that you initialize 
_address, just in case someone tries to reference it without setting it.

>     @property # use the property.getter decorator on this method
>     def address(self):
>         return self._address
>
>     @address.setter #use the property.setter decorator on this method
>     def address(self, addrvalue):
>         self._address = addrvalue
>
> computer1 = Computer()
> computer1.address = "test"
> print computer1.address
>

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From steve at pearwood.info  Wed Sep 22 00:11:54 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 Sep 2010 08:11:54 +1000
Subject: [Tutor] Opening C++ binary files
In-Reply-To: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
References: <AANLkTin_g3Fp7iYbmKA9adxfjf_FUxGq1HawwzvLULWM@mail.gmail.com>
Message-ID: <201009220811.55274.steve@pearwood.info>

On Wed, 22 Sep 2010 02:03:41 am Joe Bennett wrote:
> I have some binary files created by a program written in C++...
> Anyone have any experience with this and willing to share? ACSII test
> is easy, but not sure how the rest is encoded....????

What difference does the language the program was written in make? What 
matters is the *type* of binary file: .avi, .mp3, .jpg, .png, .doc,
.zip, or any one of a million other kinds of binary file.

If the binary file is a standard data type, like .mp3 or .zip, your best 
strategy is to find a library specially desigined for that data type, 
and use it.

If it's a non-standard type, you can open and read the file yourself 
with:

f = open("name-of-binary-file", "rb")  # you MUST have the b
data = f.read()
f.close()

and then do whatever you want with the data. The struct module may be 
useful for that.

If you don't know what the structure of the data is, then there's 
probably not much you can do with it except make a mess.


-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep 22 00:28:51 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 Sep 2010 08:28:51 +1000
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
Message-ID: <201009220828.51844.steve@pearwood.info>

On Wed, 22 Sep 2010 07:06:50 am lists wrote:

> As I understand it, it makes most sense to set/get the attribute of
> an object using a method rather than doing it directly.

Heavens no!!! That's backwards!

It might be justified in languages like Java, where you can't easily 
change your mind about direct attribute access. There's also a school 
of thought that disapproves of direct attribute access for a number of 
philosophical reasons, but if you strongly agree with that philosophy 
you'll probably find Python isn't a good language for you. (It has to 
do how much the compiler should forbid the programmer from doing, and 
how much software reliability that buys you.)

90% of the time, stick to direct attribute access, especially for short 
scripts and pre-release versions of software. If and only if you find 
that too limiting, or perhaps not limiting enough, then change to using 
getter and setter functions and properties.



-- 
Steven D'Aprano

From norman at khine.net  Wed Sep 22 00:30:09 2010
From: norman at khine.net (Norman Khine)
Date: Wed, 22 Sep 2010 00:30:09 +0200
Subject: [Tutor] list.append(x) but at a specific 'i'
Message-ID: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>

hello, how do i extend a python list but from a given [i], for example:

>>> a = ['a', 'b', 'e']
>>> b = ['c', 'd']

>>> a + b
['a', 'b', 'e', 'c', 'd']
>>>

but i want to put the items of 'b' at [-2] for example.

thanks

-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From lists at justuber.com  Wed Sep 22 00:32:51 2010
From: lists at justuber.com (lists)
Date: Tue, 21 Sep 2010 23:32:51 +0100
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <4C992EC6.40909@gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
	<4C992EC6.40909@gmail.com>
Message-ID: <AANLkTi=sQyzMYmp+wSkcCZePx149b4=RsWQipWOLULGU@mail.gmail.com>

>
> My opinion - unless there is some verification or translation or action
> required it is better (easier, clearer) to just access and assign the
> attribute directly.

This makes sense. I guess my current way of doing it just reflects my
inexperience. At the moment I'm just fumbling this out so I guess I'm
being over-cautious.
>
>> I've been reading various ways of doing this, and the information seems a
>> little
>> contradictory.
>>
> Example, please?

Forgive me for any mistakes in this explanation, I'm still learning,
but as far as I can figure out, in some earlier versions (before 2.2
perhaps?) it wasn't possible to assign a decorator directly to a
method using the at sign, and it was necessary to do this elsewhere
within the class itself. I think this link explains what I mean:
http://docs.python.org/release/2.4.2/whatsnew/node6.html

It seems some tutorials I've been reading were written for this older syntax.

>>
>> I've muddled my way through the code below to try and force setting or
>> getting the 'address' attribute through the address method rather than
>> allowing direct access.
>
> Just because you have a getter and setter does not prohibit direct reference
> to _address.

I had read something about that. I wonder if the idea behind doing it
in the way I've shown is to help prevent the programmer from doing it
accidentally perhaps?
>>
>> class Computer(object):
>>
>> ? ?def __init__(self):
>> ? ? ? ?"""instantiate the class with default values"""
>> ? ? ? ?self.address = ""
>>
> I suggest (if you want to go the setter/getter route that you initialize
> _address, just in case someone tries to reference it without setting it.
>

Do you mean like:

class Computer(object):
   def __init__(self):
      address = ""
      self.address = address

Or am I missing the point?

Thanks for your time Bob,

Chris

From vince at vinces.ca  Wed Sep 22 00:40:40 2010
From: vince at vinces.ca (Vince Spicer)
Date: Tue, 21 Sep 2010 16:40:40 -0600
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <4C992EC6.40909@gmail.com>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
	<4C992EC6.40909@gmail.com>
Message-ID: <AANLkTinoUeTcF8EB5KNzUGNaFA4-qDGe3zfrqDB6uh1=@mail.gmail.com>

On Tue, Sep 21, 2010 at 4:16 PM, bob gailer <bgailer at gmail.com> wrote:

>  On 9/21/2010 5:06 PM, lists wrote:
>
>> Hi tutors,
>>
>> I'm trying to each myself programming and come from a background in
>> system administration with some experience in scripting (so I'm very
>> new to it).
>>
>> Currently I'm grappling with the concept of object orientating
>> programming and have a question about setting&  getting attributes.
>>
>> As I understand it, it makes most sense to set/get the attribute of an
>> object using a method rather than doing it directly.
>>
>
> My opinion - unless there is some verification or translation or action
> required it is better (easier, clearer) to just access and assign the
> attribute directly.
>
>
>  I've been reading various ways of doing this, and the information seems a
>> little
>> contradictory.
>>
>>  Example, please?
>
>  I've muddled my way through the code below to try and force setting or
>> getting the 'address' attribute through the address method rather than
>> allowing direct access.
>>
> Just because you have a getter and setter does not prohibit direct
> reference to _address.
>
>> Does this make sense to you?
>>
>>
>> class Computer(object):
>>
>>    def __init__(self):
>>        """instantiate the class with default values"""
>>        self.address = ""
>>
>>  I suggest (if you want to go the setter/getter route that you initialize
> _address, just in case someone tries to reference it without setting it.
>
>
>     @property # use the property.getter decorator on this method
>>    def address(self):
>>        return self._address
>>
>>    @address.setter #use the property.setter decorator on this method
>>    def address(self, addrvalue):
>>        self._address = addrvalue
>>
>> computer1 = Computer()
>> computer1.address = "test"
>> print computer1.address
>>
>>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Hello Bob,

Here is a working example of what I think you are trying to achieve. In this
example the address is set via the setter
and some simple validation is there and the private var isn't available as
__address but get rewritten to _Computer__address (so not private but not
obvious)


class Computer(object):
    def __init__(self):
        self.__address = None
        # see note on private vars in Python
http://docs.python.org/tutorial/classes.html?highlight=private#private-variables

   @property
    def address(self):
        return self.__address

    @address.setter
    def address(self, value):
        if value not in ("available", "criteria"):
            raise AttributeError("Nope")
        self.__address = value


Hope that helps,

Vince Spicer


-- 
Sent from Ubuntu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100921/456b457a/attachment.html>

From lists at justuber.com  Wed Sep 22 00:41:23 2010
From: lists at justuber.com (lists)
Date: Tue, 21 Sep 2010 23:41:23 +0100
Subject: [Tutor] Getting/setting attributes
In-Reply-To: <201009220828.51844.steve@pearwood.info>
References: <AANLkTimT3dbWvU9ziowz5=bpWd2rM4k5Ntx00n82if5L@mail.gmail.com>
	<201009220828.51844.steve@pearwood.info>
Message-ID: <AANLkTim+7DLqdahiCA0BHxnYpHEkZjHcsCZGK0naFvhG@mail.gmail.com>

>> As I understand it, it makes most sense to set/get the attribute of
>> an object using a method rather than doing it directly.
>
> Heavens no!!! That's backwards!
>
> It might be justified in languages like Java, where you can't easily
> change your mind about direct attribute access. There's also a school
> of thought that disapproves of direct attribute access for a number of
> philosophical reasons, but if you strongly agree with that philosophy
> you'll probably find Python isn't a good language for you. (It has to
> do how much the compiler should forbid the programmer from doing, and
> how much software reliability that buys you.)

Heh, at the moment I don't have a programming philosophy. It's slowly
being formed by conversations with people like you :-)

>
> 90% of the time, stick to direct attribute access, especially for short
> scripts and pre-release versions of software. If and only if you find
> that too limiting, or perhaps not limiting enough, then change to using
> getter and setter functions and properties.

This definitely seems to be the consensus. My instinct is telling me
that it's probably best to use getters and setters when requiring
input from a user that needs to be validated perhaps, but that my
initial reading on the matter seems to have over emphasised the
importance of accessing attributes via methods.

Chris

From steve at pearwood.info  Wed Sep 22 00:45:44 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 22 Sep 2010 08:45:44 +1000
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
Message-ID: <201009220845.45017.steve@pearwood.info>

On Wed, 22 Sep 2010 01:37:42 am Tino Dai wrote:

> I am 
> torn between the DocTest and UnitTest. I like the one "fileness" of
> the DocTest, but am concerned
> about the length of my tests being several orders of magnitude bigger
> than the actual code. I
> like the UnitTest having a separate file but am worried about the
> tests getting lost or never getting
> executed because a junior developer doesn't know about them. I'm
> wondering in respect to TDD, which
> is better or is it a matter of taste?

Neither is better. They're just different, with different purposes.

The *primary* purpose of doctests are to be executable examples. When 
you write documentation, including example code is the most natural 
thing in the world. doctest lets you execute those examples, to ensure 
that they work. They're certainly not meant as an exhaustive test of 
every single feature in the program, but as *documentation* that 
happens to also work as tests.

Unit tests can be a little heavyweight, but they're designed for 
exhaustive tests of the *entire* program, not just the parts with 
user-documentation. You should write whitebox tests, not just blackbox 
tests. That means don't just write tests for the published interface, 
but write tests for the unpublished internal details as well.

E.g. if your function has special processing to deal with lists of 
strings, then you need a test for input that is a list of strings. But 
it's not necessary to document that fact in the doc string. What do the 
users care that your function calls a special subroutine to deal with 
lists of strings? So it would be inappropriate to draw attention to 
this fact with a doctest.
    
Doctests don't just execute themselves. If your developers, junior or 
otherwise, don't know about the tests, don't keep the tests up to date, 
and don't run the tests, then it doesn't matter what testing framework 
you use.

Doctests and unittests are complementary. They work well together. In 
fact, the unittest module can even execute doctests.


-- 
Steven D'Aprano

From bgailer at gmail.com  Wed Sep 22 01:17:22 2010
From: bgailer at gmail.com (bob gailer)
Date: Tue, 21 Sep 2010 19:17:22 -0400
Subject: [Tutor] list.append(x) but at a specific 'i'
In-Reply-To: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>
References: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>
Message-ID: <4C993D02.8060408@gmail.com>

  On 9/21/2010 6:30 PM, Norman Khine wrote:
> a = ['a', 'b', 'e']
> >>>  b = ['c', 'd']
> i want to put the items of 'b' at [-2] for example.
>
 >>> a[-2:-2]=b
 >>> a
['a', 'c', 'd', 'b', 'e']
 >>>

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Wed Sep 22 09:10:36 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 22 Sep 2010 07:10:36 +0000
Subject: [Tutor] class function problem
Message-ID: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>



HEllo, 
 
I have this exercise :
 
3.Rewrite the increment function so that it doesn?t contain any loops.
 
The increment function looks like this :
 
def increment(time, seconds):
    time.seconds = time.seconds + seconds
    while time.seconds>= 60:
        time.seconds = time.seconds - 60
        time.minutes = time.minutes + 1
    while time.minutes>= 60:
        time.minutes = time.minutes - 60
        time.hours = time.hours + 1

 
So I thought that recursion can do the job.
 
So I wrote this :
 
class tijd :
    pass
 
def incrememt_seconds(time): 
       time.seconds = time.seconds - 60 
       time.minutes =  time.minutes + 1 
       if time.seconds>= 60 :
           increment_seconds(time,seconds, minutes)
       return  time 
           
def increment_minutes(time):
    time.minutes = time.minutes - 60
    time.hours = time.hours + 1
    if time.minutes>= 60 :
        increment_minutes(time, minutes,hours)
    return time
 
def increment(time, seconds):
    time.seconds = time.seconds + seconds 
    if time.seconds>= 60 :
        increment_seconds(time)
    if time.minutes>= 60 :
        increment_minutes(time)
    return time
 
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = increment(time, seconds)
 
But how can i Check the outcome.
print uitkomst gives the object and print time(uitkomst) gives this error message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 34, in <module>
    print time(uitkomst)
AttributeError: tijd instance has no __call__ method
 
Roelof 		 	   		  

From wprins at gmail.com  Wed Sep 22 09:53:46 2010
From: wprins at gmail.com (Walter Prins)
Date: Wed, 22 Sep 2010 08:53:46 +0100
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <201009220845.45017.steve@pearwood.info>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
	<201009220845.45017.steve@pearwood.info>
Message-ID: <AANLkTimMJfQF1Y32-vA=wHaaEFXiN4-nCqGkaYXoJdCw@mail.gmail.com>

You might also have a look at some of the other popular testing frameworks
e.g. Nose (http://somethingaboutorange.com/mrl/projects/nose/0.11.2/) and
py.test (http://wiki.python.org/moin/PyTest)  Both of these have the
advantage that they're discovery based, so they'll go and sniff out tests
from your source, whererver they may be.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/e074fbaa/attachment.html>

From oberoc at gmail.com  Wed Sep 22 13:44:17 2010
From: oberoc at gmail.com (Tino Dai)
Date: Wed, 22 Sep 2010 07:44:17 -0400
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <201009220845.45017.steve@pearwood.info>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
	<201009220845.45017.steve@pearwood.info>
Message-ID: <AANLkTinouf+azuNK1M6N4Kd_Pm17zEBx4QQZ61CuAKYb@mail.gmail.com>

>
> The *primary* purpose of doctests are to be executable examples. When
> you write documentation, including example code is the most natural
> thing in the world. doctest lets you execute those examples, to ensure
> that they work. They're certainly not meant as an exhaustive test of
> every single feature in the program, but as *documentation* that
> happens to also work as tests.
>
> Unit tests can be a little heavyweight, but they're designed for
> exhaustive tests of the *entire* program, not just the parts with
> user-documentation. You should write whitebox tests, not just blackbox
> tests. That means don't just write tests for the published interface,
> but write tests for the unpublished internal details as well.
>

So, the gist is write tests for everything and the "external testing" should
be
handled by unit tests and the "internal testing" by doctests. Is that
correct?

>
> E.g. if your function has special processing to deal with lists of
> strings, then you need a test for input that is a list of strings. But
> it's not necessary to document that fact in the doc string. What do the
> users care that your function calls a special subroutine to deal with
> lists of strings? So it would be inappropriate to draw attention to
> this fact with a doctest.
>
> Doctests don't just execute themselves. If your developers, junior or
> otherwise, don't know about the tests, don't keep the tests up to date,
> and don't run the tests, then it doesn't matter what testing framework
> you use.
>

Point taken.......

>
> Doctests and unittests are complementary. They work well together. In
> fact, the unittest module can even execute doctests.
>
>
This I didn't know this. I will have to do more investigation about this
today. I did find that
the Django doctest's were kind of limiting (at the documentation that I
read). This opens
up more possibilities to unify my tests.


Thanks Steven for the pointers
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/cf1de564/attachment.html>

From oberoc at gmail.com  Wed Sep 22 13:45:18 2010
From: oberoc at gmail.com (Tino Dai)
Date: Wed, 22 Sep 2010 07:45:18 -0400
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <AANLkTimMJfQF1Y32-vA=wHaaEFXiN4-nCqGkaYXoJdCw@mail.gmail.com>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
	<201009220845.45017.steve@pearwood.info>
	<AANLkTimMJfQF1Y32-vA=wHaaEFXiN4-nCqGkaYXoJdCw@mail.gmail.com>
Message-ID: <AANLkTinYunnD_uWS2Adf_QEZz2=D=kfYoWc=5qXwcw-b@mail.gmail.com>

On Wed, Sep 22, 2010 at 3:53 AM, Walter Prins <wprins at gmail.com> wrote:

> You might also have a look at some of the other popular testing frameworks
> e.g. Nose (http://somethingaboutorange.com/mrl/projects/nose/0.11.2/) and
> py.test (http://wiki.python.org/moin/PyTest)  Both of these have the
> advantage that they're discovery based, so they'll go and sniff out tests
> from your source, whererver they may be.
>
> Walter
>
> I will have to check this out. Django and doctest's seem kind of limited.
:( -Thanks, Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/5af20ebc/attachment.html>

From ranjand2005 at gmail.com  Wed Sep 22 14:55:22 2010
From: ranjand2005 at gmail.com (ranjan das)
Date: Wed, 22 Sep 2010 18:25:22 +0530
Subject: [Tutor] Help-Embedding Python in C#
In-Reply-To: <AANLkTimpN0=ULhkyU_L-csGV+zGZw2F0QtqcHKOSKt0-@mail.gmail.com>
References: <AANLkTimpN0=ULhkyU_L-csGV+zGZw2F0QtqcHKOSKt0-@mail.gmail.com>
Message-ID: <AANLkTi=4dP5VeM518FVugQzY9dtM3XoUn5wikETwQt4p@mail.gmail.com>

Please Advise:

I need to run/execute python module in C#.  I am using python 2.6 and visual
studio 10


Ranjan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/7da27f0f/attachment.html>

From waynejwerner at gmail.com  Wed Sep 22 15:08:48 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 22 Sep 2010 08:08:48 -0500
Subject: [Tutor] Help-Embedding Python in C#
In-Reply-To: <AANLkTi=4dP5VeM518FVugQzY9dtM3XoUn5wikETwQt4p@mail.gmail.com>
References: <AANLkTimpN0=ULhkyU_L-csGV+zGZw2F0QtqcHKOSKt0-@mail.gmail.com>
	<AANLkTi=4dP5VeM518FVugQzY9dtM3XoUn5wikETwQt4p@mail.gmail.com>
Message-ID: <AANLkTikhsG17kbaRa_9Mm8oOhEx7DcSsJuUR0fRFmvsc@mail.gmail.com>

On Wed, Sep 22, 2010 at 7:55 AM, ranjan das <ranjand2005 at gmail.com> wrote:

>
> Please Advise:
>
> I need to run/execute python module in C#.  I am using python 2.6 and
> visual studio 10
>

You should check out IronPython
http://www.ironpython.com/

<http://www.ironpython.com/>HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/ef430171/attachment.html>

From hugo.yoshi at gmail.com  Wed Sep 22 16:16:45 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 22 Sep 2010 16:16:45 +0200
Subject: [Tutor] class function problem
In-Reply-To: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>
References: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>
Message-ID: <AANLkTikwn-kh5ZQcnrPc-M6nL=MC+ao9TSfGzKcexp-E@mail.gmail.com>

On Wed, Sep 22, 2010 at 9:10 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>
> HEllo,
>
> I have this exercise :
>
> 3.Rewrite the increment function so that it doesn?t contain any loops.
>
> The increment function looks like this :
>
> def increment(time, seconds):
> ? ?time.seconds = time.seconds + seconds
> ? ?while time.seconds>= 60:
> ? ? ? ?time.seconds = time.seconds - 60
> ? ? ? ?time.minutes = time.minutes + 1
> ? ?while time.minutes>= 60:
> ? ? ? ?time.minutes = time.minutes - 60
> ? ? ? ?time.hours = time.hours + 1
>
>
> So I thought that recursion can do the job.
>

That's very clever. But you might argue that recursion is technically
still a loop, albeit an implicit one. There is a simpler way to do
this, without loops entirely.

Hint: repeated subtraction while your number is greater than some
constant, what you are doing, is essentially the same as doing one
division operation.

>
> But how can i Check the outcome.
> print uitkomst gives the object and print time(uitkomst) gives this error message :
>
> Traceback (most recent call last):
> ?File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 34, in <module>
> ? ?print time(uitkomst)
> AttributeError: tijd instance has no __call__ method
>

You can do "print uitkomst.seconds, uitkomst.minutes, uitkomst.hours".

Alternatively, write a suitable __str__ method for your tijd class.
Then you can just do "print uitkomst"

> Roelof

From knacktus at googlemail.com  Wed Sep 22 17:12:27 2010
From: knacktus at googlemail.com (Knacktus)
Date: Wed, 22 Sep 2010 17:12:27 +0200
Subject: [Tutor] Best practice for API design handeling collections and
	single objects
Message-ID: <4C9A1CDB.2000902@googlemail.com>

Hi all,

I've got a question for you about how to best design an API that has to 
handle requests for single objects and collections of those objects.

My naming conventions are: Plural nouns for collections, singular nouns 
for single objects. "Key_to_value"-style for dictionaries. So I normaly 
know in my code wether I'm handling collections, dicts or single types.

So, here's an simplified example:
#-----------------------------------------------------------------------
class Meals(object):

     def __init__(self, id_on_menu_to_meal):
         self.id_on_menu_to_meal = id_on_menu_to_meal

#-----------------------------------------------------------------------

Now I need to return one meal by one id_on_menu and also several meals 
by several ids_on_menu.

I can think of three options:

1) create two methods:
#-----------------------------------------------------------------------
     def get_meal_by_ident(self, ident):
         return self.id_on_menu_to_meal[ident]

     def get_meals_by_idents(self, idents):
         return [self.get_meal_by_ident(ident) for ident in idents]

#-----------------------------------------------------------------------


2) create one method, which is smart enough to discriminate between the 
input (having fun with the naming conventions ;-)):
#-----------------------------------------------------------------------
     def get_meal_or_meals_by_ident_or_idents(self, ident_or_idents):
         try:
             return self.id_on_menu_to_meal[ident_or_idents]
         except KeyError:
             return [self.id_on_menu_to_meal[ident] for
                     ident in ident_or_idents]

#-----------------------------------------------------------------------


3) handle by convention application-wide only collections:
#-----------------------------------------------------------------------
     def get_meals_by_idents(self, idents):
         return [self.id_on_menu_to_meal[ident] for ident in idents]

#-----------------------------------------------------------------------

Without having too much experience on things like that, my gut feeling 
tells me to use option 1). What would you guys consider as a best 
practice here?

Thanks in advance and cheers,

Jan


From rwobben at hotmail.com  Wed Sep 22 17:17:59 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 22 Sep 2010 15:17:59 +0000
Subject: [Tutor] class function problem
In-Reply-To: <AANLkTikwn-kh5ZQcnrPc-M6nL=MC+ao9TSfGzKcexp-E@mail.gmail.com>
References: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>,
	<AANLkTikwn-kh5ZQcnrPc-M6nL=MC+ao9TSfGzKcexp-E@mail.gmail.com>
Message-ID: <SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>




----------------------------------------
> From: hugo.yoshi at gmail.com
> Date: Wed, 22 Sep 2010 16:16:45 +0200
> Subject: Re: [Tutor] class function problem
> To: rwobben at hotmail.com
> CC: tutor at python.org
>
> On Wed, Sep 22, 2010 at 9:10 AM, Roelof Wobben wrote:
>>
>>
>> HEllo,
>>
>> I have this exercise :
>>
>> 3.Rewrite the increment function so that it doesn?t contain any loops.
>>
>> The increment function looks like this :
>>
>> def increment(time, seconds):
>> time.seconds = time.seconds + seconds
>> while time.seconds>= 60:
>> time.seconds = time.seconds - 60
>> time.minutes = time.minutes + 1
>> while time.minutes>= 60:
>> time.minutes = time.minutes - 60
>> time.hours = time.hours + 1
>>
>>
>> So I thought that recursion can do the job.
>>
>
> That's very clever. But you might argue that recursion is technically
> still a loop, albeit an implicit one. There is a simpler way to do
> this, without loops entirely.
>
> Hint: repeated subtraction while your number is greater than some
> constant, what you are doing, is essentially the same as doing one
> division operation.

 
Sorry. I don't get it.
When I have 62 seconds that's 1 minutes and 2 seconds.
I have no clue how I can this with a division.
 
 
>
>>
>> But how can i Check the outcome.
>> print uitkomst gives the object and print time(uitkomst) gives this error message :
>>
>> Traceback (most recent call last):
>> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 34, in 
>> print time(uitkomst)
>> AttributeError: tijd instance has no __call__ method
>>
>
> You can do "print uitkomst.seconds, uitkomst.minutes, uitkomst.hours".
>
> Alternatively, write a suitable __str__ method for your tijd class.
> Then you can just do "print uitkomst"
>
>> Roelof

 
Oke, thanks for the tip. Stupid I could thought that myself.
 
 
Roelof
  		 	   		  

From hugo.yoshi at gmail.com  Wed Sep 22 17:44:17 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 22 Sep 2010 17:44:17 +0200
Subject: [Tutor] class function problem
In-Reply-To: <SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>
References: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>
	<AANLkTikwn-kh5ZQcnrPc-M6nL=MC+ao9TSfGzKcexp-E@mail.gmail.com>
	<SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>
Message-ID: <AANLkTikEr74ivBBuFwTkrKTS4oZCKOUgwg7GNeFY-Ce0@mail.gmail.com>

On Wed, Sep 22, 2010 at 5:17 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>>
>> That's very clever. But you might argue that recursion is technically
>> still a loop, albeit an implicit one. There is a simpler way to do
>> this, without loops entirely.
>>
>> Hint: repeated subtraction while your number is greater than some
>> constant, what you are doing, is essentially the same as doing one
>> division operation.
>
>
> Sorry. I don't get it.
> When I have 62 seconds that's 1 minutes and 2 seconds.
> I have no clue how I can this with a division.
>

okay, let's take as an example 314 seconds. We need to convert that
into minutes and seconds:

>>> seconds = 314
>>> seconds / 60.0
5.2333333333333334

See what I did there? This means I can fit 5.2 minutes in 314
seconds.No loops or anything. I'm only interested in the whole
minutes, so I can use the "//" operator for integer division:

>>> seconds // 60
5

That's our minutes. Now all you need to do is find the number of
seconds left over. The remainder (that's another hint). See if you can
figure that one out for yourself.

Hugo

From carter.danforth at gmail.com  Wed Sep 22 19:59:49 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Wed, 22 Sep 2010 13:59:49 -0400
Subject: [Tutor] how to create a persistent dictionary w/ cpickle?
Message-ID: <AANLkTimTrU+OO31r04reko5+5k2eDkfEGJVPFP-uL=sj@mail.gmail.com>

Dave, Steve, and Alan: late reply here, but thanks a lot guys - really
appreciate the feedback. I had no idea what I was doing w/ that class in the
addressbook, needed to read up more, and I got the dictionary figured out w/
cpickle and now it's all working.

Thanks again, this input's really helping my learning curve.


On Thu, Sep 9, 2010 at 2:19 AM, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: how to create a persistent dictionary w/ cpickle?
>      (Steven D'Aprano)
>   2. Re: how to create a persistent dictionary w/ cpickle? (Dave Angel)
>   3. Re: how to create a persistent dictionary w/ cpickle? (Alan Gauld)
>   4. Re: slicing a string (Sandip Bhattacharya)
>   5. Re: slicing a string (Evert Rol)
>   6. Re: slicing a string (Sandip Bhattacharya)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Thu, 9 Sep 2010 07:50:13 +1000
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] how to create a persistent dictionary w/ cpickle?
> Message-ID: <201009090750.14230.steve at pearwood.info>
> Content-Type: text/plain;  charset="utf-8"
>
> On Thu, 9 Sep 2010 03:43:42 am Carter Danforth wrote:
> > Hi, I'm trying to a create a basic addressbook for practice. I'm
> > using a dictionary with cpickle, though I'm not sure how to
> > persistently store each instance in the dictionary. Below is the code
> > I have so far.
> >
> > If I run it once and add a contact and the details, it's fine.
> > p.load(f) shows the details next time I run it, but if I add another
> > contact, and run it again, the previous key:value doesn't show. It
> > gets replaced by the new one.
>
> Where do you think you are *adding* a new contact? You don't. You
> *replace* the existing contact with a brand new one, every time.
>
> The problem has nothing to do with pickle, or storing "each instance in
> the dictionary". Pickle is already storing each instance in the
> dictionary. The problem is that you never *add* anything to the address
> book, you *replace* it each time, so there is never more than two
> instances in the dictionary (one key, one value).
>
> You don't have an address BOOK, you only have a single address.
>
>
> > How can I fix this so that it adds the new key:value to the
> > dictionary instead of replacing the existing one? Appreciate any
> > help, thanks.
>
> I would dump the entire address class for now and just go for something
> nice and minimal. Get that working first, and then, *if necessary*,
> wrap it in a class. This is Python, not Java -- we use whatever works,
> and don't force everything to be a class when it doesn't have to be.
>
> What's the simplest address record you might have? How about a name
> linked to a telephone number and email?
>
> address_book = {name: (tel, email), another_name: (tel, email), ...}
>
> So, here's the basic algorithm:
>
> (1) Look for the address-book. If it doesn't exist, create an empty
> dictionary, and pickle it as the address-book.
>
> (2) Read the address-book from the pickle file. It will be a dictionary,
> possibly empty.
>
> (3) Add an address to the dictionary. Don't create a new dictionary:
>
> >>> addresses = {}  # creates a new, empty address book
> >>> addresses["Fred"] = ("1234 5678", "fred at example.com")
> >>> addresses["Betty"] = ("2468 1357", "betty at nowhere.com")
> >>> addresses  # not empty any more
> {'Betty': ('2468 1357', 'betty at nowhere.com'), 'Fred': ('1234
> 5678', 'fred at example.com')}
>
> (3) Save the dictionary to the pickle file.
>
>
> Once you have those steps happening manually, then wrap it into a class
> so they happen automatically.
>
>
> Some more comments on your code:
>
>
> > import cPickle as p
>
> Now that's just lazy. While laziness in a programmer in a good thing,
> this is taking it to extremes!!! You use pickle twice, three times if
> you count the import. Is it really such a burden on you to
> type "cPickle" (or "pickle") two more times, that you need to rename
> it "p"?
>
> Excessive use of one-character names is one of the worst programming
> habits you can have. Don't do this.
>
>
> > addressbook = 'addressbook.data'
>
> Misleading variable name. "addressbook" isn't an addressbook at all,
> it's a filename.
>
> > f = file(addressbook, 'r+')
>
> You shouldn't keep the file open for large periods of time. On Windows,
> it may mean that it will be locked from any other program accessing it
> during that time, and it risks data corruption if your program crashes
> or the power goes out.
>
> Open and close the file just when you need it.
>
>
> > class address:
>
> A minor point: it is the convention in Python that (most) classes start
> with a capital letter. So Address would be the class, leaving address
> available for an instance of the class:
>
> address = Address()
>
>
> >     def __init__(self, name, tel, email):
> >         self.name = name
> >         self.tel = tel
> >         self.email = email
> >         ab = {self.name : self.tel}
> >         f = file(addressbook, 'r+')
> >         p.dump(ab, f)
> >
> > print p.load(f)
> > x = raw_input()
> >
> > if x == 'add':
> >     name = raw_input('\nName: ')
>
> To get a blank line before the prompt, it might be nicer to do this:
>
> print
> name = raw_input('Name: ')
>
> That's a matter of personal preference though.
>
>
> >     tel = raw_input('Tel: ')
> >     email = raw_input('Email: ')
> >     contact = address(name, tel, email)
>
>
>
>
> Hope this helps,
>
>
>
> --
> Steven D'Aprano
>
>
> ------------------------------
>
> Message: 2
> Date: Wed, 08 Sep 2010 18:14:45 -0400
> From: Dave Angel <davea at ieee.org>
> To: Carter Danforth <carter.danforth at gmail.com>
> Cc: Tutor at python.org
> Subject: Re: [Tutor] how to create a persistent dictionary w/ cpickle?
> Message-ID: <4C880AD5.5040104 at ieee.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>  On 2:59 PM, Carter Danforth wrote:
> > Hi, I'm trying to a create a basic addressbook for practice. I'm using a
> > dictionary with cpickle, though I'm not sure how to persistently store
> each
> > instance in the dictionary. Below is the code I have so far.
> >
> > If I run it once and add a contact and the details, it's fine. p.load(f)
> > shows the details next time I run it, but if I add another contact, and
> run
> > it again, the previous key:value doesn't show. It gets replaced by the
> new
> > one.
> >
> > How can I fix this so that it adds the new key:value to the dictionary
> > instead of replacing the existing one? Appreciate any help, thanks.
> >
> > import cPickle as p
> > addressbook = 'addressbook.data'
> > f = file(addressbook, 'r+')
> >
> > class address:
> >      def __init__(self, name, tel, email):
> >          self.name = name
> >          self.tel = tel
> >          self.email = email
> >
> >          ab = {self.name : self.tel}
> >
> >          f = file(addressbook, 'r+')
> >          p.dump(ab, f)
> >
> > print p.load(f)
> > x = raw_input()
> >
> > if x == 'add':
> >      name = raw_input('\nName: ')
> >      tel = raw_input('Tel: ')
> >      email = raw_input('Email: ')
> >
> >      contact = address(name, tel, email)
> >
> I have no clue what you're trying to do with that address object;  it's
> confusing initialization with persistence, and you create such an
> object, but never actually use it.  I would remove any reference to the
> address book from that object.  I'd also rename it to Address, since
> class names are supposed to be uppercase (PEP8)
>
> But anyway, in your flow, you do a p.load(), but never save the result.
> Every time you save to the addressbook file, you start over with just
> the one entry.
>
> One way to fix this is to save the p.load() result as a variable,
> presumably of type dictionary, then add the 'contact' to that
> dictionary, and at the end of the script, save that variable with
> p.dump(addresses, f)
>
> addresses =   p.load(f)
>
> interact with user --
>            addresses[name] = Address(name, tel, email)
>
> p.dump(addresses, f)
>
> I also don' t know how you get away with running your script the first
> time, since it blows up if there's no existing pickle file.
>
> DaveA
>
>
>
> ------------------------------
>
> Message: 3
> Date: Thu, 9 Sep 2010 01:17:12 +0100
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> To: tutor at python.org
> Subject: Re: [Tutor] how to create a persistent dictionary w/ cpickle?
> Message-ID: <i69925$6rk$1 at dough.gmane.org>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
>
> "Carter Danforth" <carter.danforth at gmail.com> wrote
>
> > Hi, I'm trying to a create a basic addressbook for practice. I'm
> > using a
> > dictionary with cpickle, though I'm not sure how to persistently
> > store each
> > instance in the dictionary. Below is the code I have so far.
>
> If you use a dictionary it makes more sense to use shelve rather than
> pickle for storage.
> Shelve uses pickle under the hood but it makes a file look like a
> dictionary so you
> don't need to load all the data and store it all again as you would
> with pickle.
>
> Unfioortunately your code appears to be truncated, however...
>
> > import cPickle as p
> > addressbook = 'addressbook.data'
> > f = file(addressbook, 'r+')
>
> I think you should use a binary file for pickle so the mode should be
> 'rb' not 'r+'
>
> HTH,
>
> Alan G
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Thu, 9 Sep 2010 11:19:39 +0530
> From: Sandip Bhattacharya <sandipb at foss-community.com>
> To: Roel Schroeven <rschroev_nospam_ml at fastmail.fm>
> Cc: tutor at python.org
> Subject: Re: [Tutor] slicing a string
> Message-ID:
>        <AANLkTinnzizKw4Uadk6PDYpEczJJYra_OTxAAC7d8SNp at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On Tue, Sep 7, 2010 at 1:49 PM, Roel Schroeven
> <rschroev_nospam_ml at fastmail.fm> wrote:
> >
> > But remember that you can make it simpler if you simply don't specify
> > the start and end points:
> >
> >>>> 'hello'[::-1]
> > 'olleh'
> >
>
> While I know that idiom works, I haven't really found an explanation
> as to *why* it works that way.
>
> For a string S:
> * Using  range, you need range(len(S),-1,-1) to give you the indexes
> for the string in reverse.
> * For slices, if you dont specify the start and end indices, they are
> supposed to be filled in by 0 and len(S) respectively.
>  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
> 0 here, and then go to -1 (last char) and then into an infinite loop?
>  - Especially, when S[0:len(S):1] works that way?
>
> - Sandip
>
>
> ------------------------------
>
> Message: 5
> Date: Thu, 9 Sep 2010 08:04:04 +0200
> From: Evert Rol <evert.rol at gmail.com>
> To: Sandip Bhattacharya <sandipb at foss-community.com>
> Cc: Roel Schroeven <rschroev_nospam_ml at fastmail.fm>, tutor at python.org
> Subject: Re: [Tutor] slicing a string
> Message-ID: <DBA494E3-37EE-4035-A4E4-616241BFE5F8 at gmail.com>
> Content-Type: text/plain; charset=windows-1252
>
> >> But remember that you can make it simpler if you simply don't specify
> >> the start and end points:
> >>
> >>>>> 'hello'[::-1]
> >> 'olleh'
> >>
> >
> > While I know that idiom works, I haven't really found an explanation
> > as to *why* it works that way.
> >
> > For a string S:
> > * Using  range, you need range(len(S),-1,-1) to give you the indexes
> > for the string in reverse.
> > * For slices, if you dont specify the start and end indices, they are
> > supposed to be filled in by 0 and len(S) respectively.
> >  - So S[::-1] means, S[0:len(S):-1] , so why dont we start with index
> > 0 here, and then go to -1 (last char) and then into an infinite loop?
>
> I guess because Python "is smart", and works the way you want/expect it to.
> Read
> http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange, note 5 (about one "page" down), which explicitly says "If i or j are
> omitted or None, they become ?end? values (which end depends on the sign of
> k)", where the important bit for this discussion is actually between
> parentheses.
>
> And to quote part of the Zen of Python:
> "
> Special cases aren't special enough to break the rules.
> Although practicality beats purity.
> "
>
> Reversing the automatic end values is very practical when the step index <
> 0.
>
>
> >  - Especially, when S[0:len(S):1] works that way?
> >
> > - Sandip
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
>
>
> ------------------------------
>
> Message: 6
> Date: Thu, 9 Sep 2010 11:49:46 +0530
> From: Sandip Bhattacharya <sandipb at foss-community.com>
> To: Evert Rol <evert.rol at gmail.com>
> Cc: Roel Schroeven <rschroev_nospam_ml at fastmail.fm>, tutor at python.org
> Subject: Re: [Tutor] slicing a string
> Message-ID:
>        <AANLkTim+KPva5KPX2kq7v3EYFA68jL=dm5y87PYrkUdx at mail.gmail.com>
> Content-Type: text/plain; charset=windows-1252
>
> On Thu, Sep 9, 2010 at 11:34 AM, Evert Rol <evert.rol at gmail.com> wrote:
> > Read
> >
> http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange
> > , note 5 (about one "page" down), which explicitly says "If i or j are
> > omitted or None, they become ?end? values (which end depends on the
> > sign of k)", where the important bit for this discussion is actually
> > between parentheses.
>
> Great! That is exactly what I needed to know. The reference I learnt
> extended slices from, probably didn't include this subtlety.
>
> Thanks,
>  Sandip
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 79, Issue 32
> *************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100922/08d893f7/attachment-0001.html>

From steve at pearwood.info  Wed Sep 22 21:47:45 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 05:47:45 +1000
Subject: [Tutor] list.append(x) but at a specific 'i'
In-Reply-To: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>
References: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>
Message-ID: <201009230547.45894.steve@pearwood.info>

On Wed, 22 Sep 2010 08:30:09 am Norman Khine wrote:

> hello, how do i extend a python list but from a given [i], 

Do you mean to modify the list in place, like append() and extend() do, 
or do you mean to create a new list, like + does?


> for example: 
> >>> a = ['a', 'b', 'e']
> >>> b = ['c', 'd']
> >>>
> >>> a + b
>
> ['a', 'b', 'e', 'c', 'd']
>
>
> but i want to put the items of 'b' at [-2] for example.

When you ask a question, it usually helps to show the output you *want*, 
not the output you *don't want*, rather than to make assumptions about 
what other people will understand.

When you say that you want the items of b *at* -2, taken literally that 
could mean:

>>> a = ['a', 'b', 'e']
>>> b = ['c', 'd']
>>> a.insert(-2+1, b)
>>> print(a)
['a', 'b', ['c', 'd'], 'e']

Note that the items of b are kept as a single item, at the position you 
ask for, and the index you pass to insert() is one beyond when you want 
them to appear.

To create a new list, instead of insert() use slicing:

>>> a[:-2+1] + [b] + a[-2+1:]
['a', 'b', ['c', 'd'], 'e']


If you want the items of b to *start* at -2, since there are exactly two 
items, extend() will do the job for in-place modification, otherwise +. 
But you already know that, because that was your example.

If you want the items of b to *end* at -2, so that you get 
['a', 'b', 'c', 'd', 'e'] then you could use repeated insertions:

for c in b:
    a.insert(-2, c)

but that will likely be slow for large lists. Better to use slicing. To 
create a new list is just like the above, except you don't create a 
temporary list-of-b first:

>>> a[:-2+1] + b + a[-2+1:]
['a', 'b', 'c', 'd', 'e']


To do it in place, assign to a slice:

>>> a[-2:-2] = b
>>> print(a)
['a', 'c', 'd', 'b', 'e']



-- 
Steven D'Aprano

From steve at pearwood.info  Wed Sep 22 21:55:36 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 05:55:36 +1000
Subject: [Tutor] class function problem
In-Reply-To: <SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>
References: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>
	<AANLkTikwn-kh5ZQcnrPc-M6nL=MC+ao9TSfGzKcexp-E@mail.gmail.com>
	<SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>
Message-ID: <201009230555.36885.steve@pearwood.info>

On Thu, 23 Sep 2010 01:17:59 am Roelof Wobben wrote:

> Sorry. I don't get it.
> When I have 62 seconds that's 1 minutes and 2 seconds.
> I have no clue how I can this with a division.

If you have 60 seconds, you have one minute.

If you have 120 minutes, you have two minutes. Can you get from 120 to 2 
using a division?

You will find the divmod() function useful. divmod(a, b) returns two 
numbers:

a/b as a whole number, any remainder left only



-- 
Steven D'Aprano

From pkoek11 at xs4all.nl  Wed Sep 22 22:07:21 2010
From: pkoek11 at xs4all.nl (Pete)
Date: Wed, 22 Sep 2010 16:07:21 -0400
Subject: [Tutor] Dict of function calls
Message-ID: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>

For a plugin mechanism, I'm populating a dict with calls to the implemented plugins. 

Consider this:

>>> class foo:
...     def do(self):
...             print 'do foo'
... 
>>> class bar:
...     def do(self):
...             print 'do bar'
... 
>>> list = { 'foo': foo.do(), 'bar': bar.do() }
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method do() must be called with foo instance as first argument (got nothing instead)

===

Now I get that I need to instantiate foo and bar first before I can refer to them in the dict.

so something like

foo_instance = foo()
bar_instance = bar()

list = { 'foo': foo_instance.do(), 'bar': bar_instance.do() }

would probably work. But is that the best/pythonic way to do it? 
I first implemented "do" as a static method but that seemed... wrong (also because it needs to access some variables from the instance).

Any hints would be appreciated,

Pete



From steve at pearwood.info  Wed Sep 22 23:52:40 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 07:52:40 +1000
Subject: [Tutor] class function problem
In-Reply-To: <201009230555.36885.steve@pearwood.info>
References: <SNT118-W388C386B88976592456BE7AE600@phx.gbl>
	<SNT118-W59AE8F17E5954FF1FB7C48AE600@phx.gbl>
	<201009230555.36885.steve@pearwood.info>
Message-ID: <201009230752.40335.steve@pearwood.info>

On Thu, 23 Sep 2010 05:55:36 am Steven D'Aprano wrote:

> You will find the divmod() function useful. divmod(a, b) returns
> two numbers:
>
> a/b as a whole number, any remainder left only

Arggh! Of course I meant any reminder left OVER.


-- 
Steven D'Aprano 

From steve at pearwood.info  Wed Sep 22 23:50:16 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 07:50:16 +1000
Subject: [Tutor] Dict of function calls
In-Reply-To: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
References: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
Message-ID: <201009230750.16683.steve@pearwood.info>

On Thu, 23 Sep 2010 06:07:21 am Pete wrote:
> For a plugin mechanism, I'm populating a dict with calls to the
> implemented plugins.
[...]
> Now I get that I need to instantiate foo and bar first before I can
> refer to them in the dict.
>
> so something like
>
> foo_instance = foo()
> bar_instance = bar()
>
> list = { 'foo': foo_instance.do(), 'bar': bar_instance.do() }
>
> would probably work. But is that the best/pythonic way to do it?

(1) It's generally a bad idea to "shadow" the name of a built-in 
function like list. Particularly since your variable list isn't 
actually a list, but a mapping of name:function. Find a better 
name :)

(2) You end up calling the do() methods inside the dict. You probably 
mean to save the method itself as a callback function.

(3) There's no need to keep the instances floating around as 
independent names, unless you need direct access to them.

Putting these together, we get:

dispatch_table = { 'foo': foo().do, 'bar': bar().do }

Which you then later call using:

dispatch_table[name](args)

where name is "foo" or "bar", and args is anything you need to pass to 
the do() method.

Oh, and (4)... in Python circles, it's traditional but not compulsory 
to use metasyntactic variables named after Monty Python sketches 
rather than foo and bar. So spam, ham, eggs, parrot (dead or 
otherwise), names of cheeses, aardvark..., although there is no 
standard order.

  Indeed, when I design my killer language, the identifiers "foo" and
  "bar" will be reserved words, never used, and not even mentioned in
  the reference manual. Any program using one will simply dump core
  without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998

-- 
Steven D'Aprano 
Operations Manager 
Cybersource Pty Ltd, ABN 13 053 904 082 
Level 1, 130-132 Stawell St, Richmond VIC 3121 
Tel: +61 3 9428 6922   Fax: +61 3 9428 6944 
Web: http://www.cybersource.com.au 

From steve at pearwood.info  Thu Sep 23 00:48:13 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 08:48:13 +1000
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <AANLkTinouf+azuNK1M6N4Kd_Pm17zEBx4QQZ61CuAKYb@mail.gmail.com>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
	<201009220845.45017.steve@pearwood.info>
	<AANLkTinouf+azuNK1M6N4Kd_Pm17zEBx4QQZ61CuAKYb@mail.gmail.com>
Message-ID: <201009230848.14076.steve@pearwood.info>

On Wed, 22 Sep 2010 09:44:17 pm Tino Dai wrote:
> > The *primary* purpose of doctests are to be executable examples.
> > When you write documentation, including example code is the most
> > natural thing in the world. doctest lets you execute those
> > examples, to ensure that they work. They're certainly not meant
> > as an exhaustive test of every single feature in the program, but
> > as *documentation* that happens to also work as tests.
> >
> > Unit tests can be a little heavyweight, but they're designed for
> > exhaustive tests of the *entire* program, not just the parts with
> > user-documentation. You should write whitebox tests, not just
> > blackbox tests. That means don't just write tests for the
> > published interface, but write tests for the unpublished internal
> > details as well.
>
> So, the gist is write tests for everything and the "external
> testing" should be
> handled by unit tests and the "internal testing" by doctests. Is
> that correct?

I'm not sure I understand what you mean by "external" and "internal", 
but if I do understand, you should swap them around.

What I mean is this:

Functions and classes have (or at least should have) a published 
interface, the API, which tell the user what they can expect the 
function to do and what arguments they need to provide. This is the 
external interface. It could be as simple as:

    parrot.colour
    Read-only attribute giving the colour of the parrot. The 
    default colour is "blue".

or it could be thirty pages of tightly-written documentation. Either 
way, a small number of examples are useful, and having those examples 
be executable is even better:

    >>> p = Parrot()
    >>> p.colour
    'blue'

This should go in the function's __doc__ string, where it is easily 
discoverable by users using the interactive help() function, as well 
as documentation discovery tools.

But there's no need to give an example of *every* tiny facet of 
behaviour, even if your documentation specifically mentions it. 
There's very little gained from having *both* these additional tests, 
as far as documentation is concerned:

    >>> Parrot('light green').colour
    'light green'
    >>> Parrot('   LIGHT GREEN   ').colour
    'light green'

If you find yourself saying "Yes, yes, I get the point!" while reading 
documentation, then you've got too many examples and some tests need 
to be removed.

But you do need to have those tests *somewhere*, otherwise, how do you 
know they work as expected? You need to verify the promises you have 
made, that is, test the external interface. This is "blackbox 
testing": you can't see inside the function, only the outside 
behaviour:

    >>> Parrot().colour
    'blue'
    >>> Parrot(None).colour
    'blue'
    >>> Parrot('').colour
    'blue'
    >>> Parrot('BLUE').colour
    'blue'
    >>> Parrot(' \\v\\r  red   \\n\\t   ').colour
    'red'
    >>> Parrot('rEd').colour
    'red'
    >>> Parrot('yellow').colour
    'yellow'
    >>> p = Parrot()
    >>> p.resting = False
    >>> p.colour
    'blue'
    >>> p.resting = True
    >>> p.colour
    'blue'
    >>> Parrot(state='transparent').colour
    Traceback (most recent call last):
      ...
    ParrotError: invisible parrots don't have colour
    >>> Parrot(species='Norwegian Blue').colour  # are we bored yet?
    'blue'
    >>> Parrot(species='Giant Man-eating Kakapo').colour
    'green'


Nobody needs to see *all* of that in a docstring, but it does need to 
be tested somewhere. You can use doctest for that, in an external 
file rather than the __doc__ string, but often unit tests give you 
more power and flexibility.

Blackbox testing is good, but it's not complete. You should also use 
whitebox testing, where you are expected to consider all the paths 
the code might take, and ensure that each and every one of those are 
tested. (At least that's the ideal, in practice sometimes you can't 
test *every* corner of the code. But you should try.) This is testing 
the internal implementation, and it certainly doesn't belong in the 
external documentation!

Real world example: Python's list.sort() method and sorted() functions 
use a custom-made, high-performance sort algorithm written by Tim 
Peters, but it only kicks in for sufficiently large lists. For small 
lists, they use a simpler sort algorithm. Whitebox testing needs to 
have tests for both cases, but you don't want to make the cutoff 
between the two part of your published external interface:

    >>> # test a small list that uses algorithm 1
    ... sorted([1, 5, 3, 5, 9])
    [1, 3, 5, 5, 9]
    >>> # and test a big list that uses algorithm 2
    ... sorted([1, 5, 3, 5, 9, 8])
    [1, 3, 5, 5, 8, 9]


What if the cutoff changes? You will have to revise your manuals! Why 
do you think the users of sort() need to know exactly where the 
cutoff is? Nobody cares what the exact value is. (It's not 5 items, 
by the way.)

For whitebox testing, doctests are often too limiting, and they're 
certainly too noisy to include in the documentation, unless a 
specific implementation is part of the published specification. For 
every if...else in your code, you should (in an ideal world) have a 
test which takes the if branch and a second test which takes the else 
branch. This gets huge, quick, but you should at least test the major 
paths in the code, and ensure that all the subroutines are tested,  
special values are tested, etc. Again, unit tests are often better 
suited for this.

Finally, regression tests -- every time you find a bug, you write a 
test that demonstrates that bug. That test will fail. Now fix the 
bug, and the test will pass. If your code ever accidentally 
regresses, allowing the bug to return, your regression tests will 
start failing and you will know it immediately. It goes without 
saying that these shouldn't go in your external documentation!

The lines between doc tests, blackbox testing, whitebox testing, and 
regression testing is blurry. People may legitimately disagree on 
whether a specific test is documentation, testing the interface, 
testing the implementation, or all three.



-- 
Steven D'Aprano 
Operations Manager 
Cybersource Pty Ltd, ABN 13 053 904 082 
Level 1, 130-132 Stawell St, Richmond VIC 3121 
Tel: +61 3 9428 6922   Fax: +61 3 9428 6944 
Web: http://www.cybersource.com.au 

From pkoek11 at xs4all.nl  Thu Sep 23 01:21:27 2010
From: pkoek11 at xs4all.nl (Pete)
Date: Wed, 22 Sep 2010 19:21:27 -0400
Subject: [Tutor] Dict of function calls
In-Reply-To: <201009230750.16683.steve@pearwood.info>
References: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
	<201009230750.16683.steve@pearwood.info>
Message-ID: <54AB0DE4-9096-4CDD-B0B7-1603E679D925@xs4all.nl>


On 2010-09-22, at 5:50 PM, Steven D'Aprano wrote:

> On Thu, 23 Sep 2010 06:07:21 am Pete wrote:
>> For a plugin mechanism, I'm populating a dict with calls to the
>> implemented plugins.
> [...]
>> Now I get that I need to instantiate foo and bar first before I can
>> refer to them in the dict.
>> 
>> so something like
>> 
>> foo_instance = foo()
>> bar_instance = bar()
>> 
>> list = { 'foo': foo_instance.do(), 'bar': bar_instance.do() }
>> 
>> would probably work. But is that the best/pythonic way to do it?
> 
> (1) It's generally a bad idea to "shadow" the name of a built-in 
> function like list. Particularly since your variable list isn't 
> actually a list, but a mapping of name:function. Find a better 
> name :)

That was just for the example, of course, but point taken :)

> (2) You end up calling the do() methods inside the dict. You probably 
> mean to save the method itself as a callback function.

I did.

> (3) There's no need to keep the instances floating around as 
> independent names, unless you need direct access to them.
> 
> Putting these together, we get:
> 
> dispatch_table = { 'foo': foo().do, 'bar': bar().do }
> 
> Which you then later call using:
> 
> dispatch_table[name](args)
> 
> where name is "foo" or "bar", and args is anything you need to pass to 
> the do() method.

I see. And are those methods then unbound? (Because when instantiating the object it needs to do some initialization of instance variables,
and I think those were not available when calling an unbound method. (My understanding of the bound/unbound method distinction is rather vague at this point,
I apologise)

> Oh, and (4)... in Python circles, it's traditional but not compulsory 
> to use metasyntactic variables named after Monty Python sketches 
> rather than foo and bar. So spam, ham, eggs, parrot (dead or 
> otherwise), names of cheeses, aardvark..., although there is no 
> standard order.
> 
>  Indeed, when I design my killer language, the identifiers "foo" and
>  "bar" will be reserved words, never used, and not even mentioned in
>  the reference manual. Any program using one will simply dump core
>  without comment. Multitudes will rejoice. -- Tim Peters, 29 Apr 1998

THANK YOU! 

It's this kind of knowledge that I crave, sir.

:)

- Pete

From steve at pearwood.info  Thu Sep 23 03:33:33 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 11:33:33 +1000
Subject: [Tutor] Dict of function calls
In-Reply-To: <54AB0DE4-9096-4CDD-B0B7-1603E679D925@xs4all.nl>
References: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
	<201009230750.16683.steve@pearwood.info>
	<54AB0DE4-9096-4CDD-B0B7-1603E679D925@xs4all.nl>
Message-ID: <201009231133.33208.steve@pearwood.info>

On Thu, 23 Sep 2010 09:21:27 am Pete wrote:

> > (3) There's no need to keep the instances floating around as
> > independent names, unless you need direct access to them.
> >
> > Putting these together, we get:
> >
> > dispatch_table = { 'foo': foo().do, 'bar': bar().do }
[...]
> I see. And are those methods then unbound?

No, they're bound methods.


> (Because when 
> instantiating the object it needs to do some initialization of
> instance variables, and I think those were not available when
> calling an unbound method. (My understanding of the bound/unbound
> method distinction is rather vague at this point, I apologise)

Don't apologise :)  This is a tutor list, and the bound/unbound thing 
is one of the trickier parts of Python. This is what we're here for!

The def keyword always creates a function, whether you are outside a 
class or inside. So *inside* a class, at *creation* time, a "method" 
is really an ordinary function. Here's an example that prints the 
so-called method while the class is being built:


>>> class Test(object):
...     def spam(self, n):
...             return 'spam'*n
...     print spam
...
<function spam at 0xb7ee14fc>


Once the class is created, the function object is wrapped to become a 
method. Methods can be bound or unbound. If you get the method from 
the class object itself, it will be unbound:

>>> Test.spam
<unbound method Test.spam>

You can still get access to the original function object like this:

>>> Test.spam.im_func
<function spam at 0xb7ee14fc>


If you then try to call the method, or the underlying function, you 
need to supply something as the "self" attribute. Method objects 
enforce that this first argument must be an instance of Test, but the 
underlying function object doesn't, so you can try passing anything 
you like and hope it works :)

Unbound methods are useful for when you know what method you want to 
call, but not which instance you want to call it on:

>>> func = str.upper
>>> # much later
...
>>> func("do you have any cheese, my good man?")
'DO YOU HAVE ANY CHEESE, MY GOOD MAN?'


If you get the method from an instance, it will be bound to that 
instance:

>>> Test().spam
<bound method Test.spam of <__main__.Test object at 0xb7eece2c>>

and self will automatically be provided when you call the method.


-- 
Steven D'Aprano 

From ranjand2005 at gmail.com  Thu Sep 23 07:17:39 2010
From: ranjand2005 at gmail.com (ranjan das)
Date: Thu, 23 Sep 2010 10:47:39 +0530
Subject: [Tutor] Help-Embedding Python in C#
In-Reply-To: <AANLkTikhsG17kbaRa_9Mm8oOhEx7DcSsJuUR0fRFmvsc@mail.gmail.com>
References: <AANLkTimpN0=ULhkyU_L-csGV+zGZw2F0QtqcHKOSKt0-@mail.gmail.com>
	<AANLkTi=4dP5VeM518FVugQzY9dtM3XoUn5wikETwQt4p@mail.gmail.com>
	<AANLkTikhsG17kbaRa_9Mm8oOhEx7DcSsJuUR0fRFmvsc@mail.gmail.com>
Message-ID: <AANLkTin8J0_ADmvaRn6KJT3sz9oPdmMJmifvofLXEWFt@mail.gmail.com>

Hi Wayne,

Thanks for your reply. The problem is a bit more specific. I have come
across ironpython and I ran a test file and it works fine as far as the
wrapping is concerned.

What I want to do is write my code completely in Python (as gainst iron
python), copy it to the visual studio editor and create a web based
application (I want it to be interactive) as against building an exe file
which would mean params would have to be hard coded.

While trying this I faced problems. I would prefer to do it in pure python
code rather than resorting to iron python. Is that possible?

Objective: Write the code completely in python and then from it create a
windows web based application.

Any help is appreciated

Regards,
Ranjan




On Wed, Sep 22, 2010 at 6:38 PM, Wayne Werner <waynejwerner at gmail.com>wrote:

> On Wed, Sep 22, 2010 at 7:55 AM, ranjan das <ranjand2005 at gmail.com> wrote:
>
>>
>> Please Advise:
>>
>> I need to run/execute python module in C#.  I am using python 2.6 and
>> visual studio 10
>>
>
> You should check out IronPython
> http://www.ironpython.com/
>
> <http://www.ironpython.com/>HTH,
> Wayne
>



-- 
The inherent vice of capitalism is the unequal sharing of blessings; the
inherent virtue of socialism is the equal sharing of miseries.

~ Winston Churchill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/40847e68/attachment.html>

From ranceh at gmail.com  Thu Sep 23 08:30:45 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 23 Sep 2010 01:30:45 -0500
Subject: [Tutor] Windows printing
Message-ID: <AANLkTikgebjh8+i81u+gM3F4uvjzH0-YJB=d6BAnr97y@mail.gmail.com>

I'm using this page as a reference:
http://timgolden.me.uk/python/win32_how_do_i/print.html

I'm able to print to the default printer ok, but I can't seem to find
out how to get to pick the printer I want to use.

This is from a CLI app, so there is no gui.

win32print seems like it has everything I need, I just can't quite see
how to put it together

I'd like to have my python app ask which printer to use as opposed to
just using the default printer.

win32print.EnumPrinters() does give me a list, but its not just a list
of names. the list also includes other items like network paths
depending on the level of detail you specify in EnumPrinters.


Tim has two possible ways to print.  Tim shows how to use the win32api
to pass a ShellExecute command that prints.  The catch to this command
is you have to print a file type and it has to be the default type for
an app to open.

He also shows a way to skip the ShellExecute and use the print api
directly to gain some more control.

Based on my needs, I'm pretty sure that I'll need to use win32print,


Tim's how-to is likely not for my version of python (mine is 3.1)
since some of his command fail on my system because mine wants options
or parameters that Tim doesn't mention.

I'm going to be printing automatically generated check-in tickets.

I can make the ticket, save it as a temp file, but I can not print to
the default printer, I must be able to select the destination printer.

My plan is to ask the user what printer to use for the session, and
save that printer name in a variable and direct all automated prints
to that printer.

As we move the laptop from place to place the default printer is not
always available.  And the available printer changes depending on
location.

Ideally there would be a variation of the ShellExecute command that
would let me specify a printer name.

Windows 7 is the predominate windows platform we are using.

Thanks

From steve at pearwood.info  Thu Sep 23 08:58:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 23 Sep 2010 16:58:56 +1000
Subject: [Tutor] Help-Embedding Python in C#
In-Reply-To: <AANLkTin8J0_ADmvaRn6KJT3sz9oPdmMJmifvofLXEWFt@mail.gmail.com>
References: <AANLkTimpN0=ULhkyU_L-csGV+zGZw2F0QtqcHKOSKt0-@mail.gmail.com>
	<AANLkTikhsG17kbaRa_9Mm8oOhEx7DcSsJuUR0fRFmvsc@mail.gmail.com>
	<AANLkTin8J0_ADmvaRn6KJT3sz9oPdmMJmifvofLXEWFt@mail.gmail.com>
Message-ID: <201009231658.56601.steve@pearwood.info>

On Thu, 23 Sep 2010 03:17:39 pm ranjan das wrote:

> What I want to do is write my code completely in Python (as gainst
> iron python), 

Iron Python *is* Python. It's just a different implementation, with 
built-in support for Dot-Net.


> copy it to the visual studio editor and create a web 
> based application (I want it to be interactive) as against building
> an exe file which would mean params would have to be hard coded.


How does building an exe file mean that params would have to be hard 
coded? What sort of params?

And how does this description match what you asked earlier:

"I need to run/execute python module in C#.  I am using python 2.6 and 
visual studio 10"


So, which do you want to do: run Python code in a browser, or run it 
is C#?


> Objective: Write the code completely in python and then from it
> create a windows web based application.

If it's web-based, why does it have to be Windows-only?




-- 
Steven D'Aprano 

From mail at timgolden.me.uk  Thu Sep 23 10:40:02 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 23 Sep 2010 09:40:02 +0100
Subject: [Tutor] Windows printing
In-Reply-To: <AANLkTikgebjh8+i81u+gM3F4uvjzH0-YJB=d6BAnr97y@mail.gmail.com>
References: <AANLkTikgebjh8+i81u+gM3F4uvjzH0-YJB=d6BAnr97y@mail.gmail.com>
Message-ID: <4C9B1262.9040202@timgolden.me.uk>

On 23/09/2010 07:30, Rance Hall wrote:
> I'm using this page as a reference:
> http://timgolden.me.uk/python/win32_how_do_i/print.html
>
> I'm able to print to the default printer ok, but I can't seem to find
> out how to get to pick the printer I want to use.
>
> This is from a CLI app, so there is no gui.
>
> win32print seems like it has everything I need, I just can't quite see
> how to put it together
>
> I'd like to have my python app ask which printer to use as opposed to
> just using the default printer.
>
> win32print.EnumPrinters() does give me a list, but its not just a list
> of names. the list also includes other items like network paths
> depending on the level of detail you specify in EnumPrinters.
>
>
> Tim has two possible ways to print.  Tim shows how to use the win32api
> to pass a ShellExecute command that prints.  The catch to this command
> is you have to print a file type and it has to be the default type for
> an app to open.
>
> He also shows a way to skip the ShellExecute and use the print api
> directly to gain some more control.
>
> Based on my needs, I'm pretty sure that I'll need to use win32print,
>
>
> Tim's how-to is likely not for my version of python (mine is 3.1)
> since some of his command fail on my system because mine wants options
> or parameters that Tim doesn't mention.

I've fixed one issue: the win32print example now passes bytes for Py3.x
and str for 2.x; that example now works for me. I haven't worked through
the other examples yet but thanks for the heads-up.

> I'm going to be printing automatically generated check-in tickets.
>
> I can make the ticket, save it as a temp file, but I can not print to
> the default printer, I must be able to select the destination printer.
>
> My plan is to ask the user what printer to use for the session, and
> save that printer name in a variable and direct all automated prints
> to that printer.
>
> As we move the laptop from place to place the default printer is not
> always available.  And the available printer changes depending on
> location.
>
> Ideally there would be a variation of the ShellExecute command that
> would let me specify a printer name.
>
> Windows 7 is the predominate windows platform we are using.

OK. Thanks for the fairly clear explanation of the situation. I agree
that a ShellExecute variant which allowed printer selection would be
good, but I don't believe there is one. That's basically because
ShellExecute is really what the user indirectly actions when they
double-click or right-click on a file and choose one of the actions:
there's no scope for additional info within the ShellExecute mechanism.
Obviously a program called in this way is free to do whatever it wishes
in the way of selection dialogs and the like.

One thing which isn't entirely clear to me is whether your ticket-saved-
as-a-temp-file is printer-ready, eg plain text, PS or PCL, or whether
you'd really want to format it further before printing. On the basis
that it's ready to go direct, the following very slight variation should
do what I think you want: (tested only on XP; I'll try to get hold of
a W7 machine to double-check)

<code>
import os, sys
import win32print

printer_info = win32print.EnumPrinters (
   win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
)
printer_names = [name for (flags, description, name, comment) in 
printer_info]
for i, name in enumerate (printer_names):
   print ("%d) %s" % (i + 1, name))

n_printer = int (input ("Which printer: "))
printer_name = printer_names[n_printer+1]
print ("Using", printer_name)

hPrinter = win32print.OpenPrinter (printer_name)
#
# ... and so on, per the original example
#

</code>

Is this what you're after? Or have I missed the point?

TJG

From rwobben at hotmail.com  Thu Sep 23 10:58:39 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 23 Sep 2010 08:58:39 +0000
Subject: [Tutor] pure function problem
Message-ID: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>



Hello, 
 
I have to rewrite a function to a pure function.
So i have this :
 

class tijd :
    pass
def increment(time, seconds):
    sum = tijd()
    sum.seconds = time.seconds + seconds 
    
    if sum.seconds> 60 :
        minutes, seconds = divmod(sum.seconds, 60)
        sum.seconds = seconds 
        sum.minutes = time.minutes + minutes
    return sum
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = tijd()
uitkomst = increment(time, seconds)
print uitkomst.minutes, uitkomst.seconds
 
But now I get this error message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 22, in <module>
    print uitkomst.minutes, uitkomst.seconds
AttributeError: tijd instance has no attribute 'minutes'
 
So it looks like uitkomst has no attribute minutes but uitkomst is a instance of tijd which has a attribute minutes.
 
Roelof
  		 	   		  

From jemejones at gmail.com  Thu Sep 23 11:36:58 2010
From: jemejones at gmail.com (Jeremy Jones)
Date: Thu, 23 Sep 2010 05:36:58 -0400
Subject: [Tutor] pure function problem
In-Reply-To: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>
Message-ID: <AANLkTi=Gd4Hj9ngk1Sw5eoNaxxTUYqLCz4bMNEbGVk7c@mail.gmail.com>

The problem is that your class definition doesn't do anything to
explicitly set those attributes.

On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
<snip>
> class tijd :
> ? ?pass

You're not doing any explicit setting of attributes at the class level.

<snip>
> time = tijd()
> time.hour = 20
> time.minutes = 20
> time.seconds = 20

You set them on this instance.

> seconds = 20
> uitkomst = tijd()

But not on this one.

What you probably want to do is something like this:

class tijd(object):
    def __init__(self):
        self.hour = 20
        self.minutes = 20
        self.seconds = 20

Or if you prefer to set these when you create the instance, you can
pass in values like this:

class tijd(object):
    def __init__(self, hour=20, minutes=20, seconds=20):
        self.hour = hour
        self.minutes = minutes
        self.seconds = seconds

I noticed something odd just a sec ago.  You have this:
> uitkomst = tijd()
> uitkomst = increment(time, seconds)
> print uitkomst.minutes, uitkomst.seconds

You're creating a tijd instance, binding uitkomst to it, then
overwriting that instance with what you return from increment().

Anyway, hth.

- jmj

From rwobben at hotmail.com  Thu Sep 23 12:15:07 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 23 Sep 2010 10:15:07 +0000
Subject: [Tutor] pure function problem
In-Reply-To: <AANLkTi=Gd4Hj9ngk1Sw5eoNaxxTUYqLCz4bMNEbGVk7c@mail.gmail.com>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>,
	<AANLkTi=Gd4Hj9ngk1Sw5eoNaxxTUYqLCz4bMNEbGVk7c@mail.gmail.com>
Message-ID: <SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>




> Date: Thu, 23 Sep 2010 05:36:58 -0400
> Subject: Re: [Tutor] pure function problem
> From: jemejones at gmail.com
> To: tutor at python.org
> CC: rwobben at hotmail.com
> 
> The problem is that your class definition doesn't do anything to
> explicitly set those attributes.
> 
> On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
> <snip>
> > class tijd :
> >    pass
> 
> You're not doing any explicit setting of attributes at the class level.
> 
> <snip>
> > time = tijd()
> > time.hour = 20
> > time.minutes = 20
> > time.seconds = 20
> 
> You set them on this instance.
> 
> > seconds = 20
> > uitkomst = tijd()
> 
> But not on this one.
> 
> What you probably want to do is something like this:
> 
> class tijd(object):
>     def __init__(self):
>         self.hour = 20
>         self.minutes = 20
>         self.seconds = 20
> 
> Or if you prefer to set these when you create the instance, you can
> pass in values like this:
> 
> class tijd(object):
>     def __init__(self, hour=20, minutes=20, seconds=20):
>         self.hour = hour
>         self.minutes = minutes
>         self.seconds = seconds
> 
> I noticed something odd just a sec ago.  You have this:
> > uitkomst = tijd()
> > uitkomst = increment(time, seconds)
> > print uitkomst.minutes, uitkomst.seconds
> 
> You're creating a tijd instance, binding uitkomst to it, then
> overwriting that instance with what you return from increment().
> 
> Anyway, hth.
> 
> - jmj


Correct, 

I try to find a way to solve this error message.

Roelof

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/f65182cf/attachment.html>

From ranceh at gmail.com  Thu Sep 23 15:05:14 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 23 Sep 2010 08:05:14 -0500
Subject: [Tutor] Windows printing
In-Reply-To: <4C9B1262.9040202@timgolden.me.uk>
References: <AANLkTikgebjh8+i81u+gM3F4uvjzH0-YJB=d6BAnr97y@mail.gmail.com>
	<4C9B1262.9040202@timgolden.me.uk>
Message-ID: <AANLkTi=GjbDXr5oKqU1uwn3=Lz-UaCN55UPdNZQqLX7P@mail.gmail.com>

On Thu, Sep 23, 2010 at 3:40 AM, Tim Golden <mail at timgolden.me.uk> wrote:
> On 23/09/2010 07:30, Rance Hall wrote:
>>
<snip>
>>
>> Tim's how-to is likely not for my version of python (mine is 3.1)
>> since some of his command fail on my system because mine wants options
>> or parameters that Tim doesn't mention.
>
> I've fixed one issue: the win32print example now passes bytes for Py3.x
> and str for 2.x; that example now works for me. I haven't worked through
> the other examples yet but thanks for the heads-up.
>

Thanks for the rapid turn around on this one.

<snip>

>
> OK. Thanks for the fairly clear explanation of the situation. I agree
> that a ShellExecute variant which allowed printer selection would be
> good, but I don't believe there is one. That's basically because
> ShellExecute is really what the user indirectly actions when they
> double-click or right-click on a file and choose one of the actions:
> there's no scope for additional info within the ShellExecute mechanism.
> Obviously a program called in this way is free to do whatever it wishes
> in the way of selection dialogs and the like.
>
> One thing which isn't entirely clear to me is whether your ticket-saved-
> as-a-temp-file is printer-ready, eg plain text, PS or PCL, or whether
> you'd really want to format it further before printing. On the basis
> that it's ready to go direct, the following very slight variation should
> do what I think you want: (tested only on XP; I'll try to get hold of
> a W7 machine to double-check)
>

For the first roll-out and testing I figured plaintext was good enough.

Future revisions will probably use the PDF library you also referred
to on your page.

Either way that is as printer ready as I expect I will be able to get it.

> <code>
> import os, sys
> import win32print
>
> printer_info = win32print.EnumPrinters (
> ?win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
> )
> printer_names = [name for (flags, description, name, comment) in
> printer_info]
> for i, name in enumerate (printer_names):
> ?print ("%d) %s" % (i + 1, name))
>
> n_printer = int (input ("Which printer: "))
> printer_name = printer_names[n_printer+1]
> print ("Using", printer_name)
>
> hPrinter = win32print.OpenPrinter (printer_name)
> #
> # ... and so on, per the original example
> #
>
> </code>
>
> Is this what you're after? Or have I missed the point?
>
> TJG

This has the logic of what I want, I'll test it later today on Win7
and see if I have any issues I can't resolve, I tried some of this
from the python console and dont get any errors, so it lools
promising.



Thanks again for the rapid response.

From mail at timgolden.me.uk  Thu Sep 23 15:22:02 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 23 Sep 2010 14:22:02 +0100
Subject: [Tutor] Windows printing
In-Reply-To: <AANLkTi=GjbDXr5oKqU1uwn3=Lz-UaCN55UPdNZQqLX7P@mail.gmail.com>
References: <AANLkTikgebjh8+i81u+gM3F4uvjzH0-YJB=d6BAnr97y@mail.gmail.com>	<4C9B1262.9040202@timgolden.me.uk>
	<AANLkTi=GjbDXr5oKqU1uwn3=Lz-UaCN55UPdNZQqLX7P@mail.gmail.com>
Message-ID: <4C9B547A.3000608@timgolden.me.uk>

On 23/09/2010 14:05, Rance Hall wrote:
> For the first roll-out and testing I figured plaintext was good enough.
>
> Future revisions will probably use the PDF library you also referred
> to on your page.
>
> Either way that is as printer ready as I expect I will be able to get it.

One option you might want to consider is to use IE as a print
engine. Here's some code I use to print stuff via IE, converting
it to HTML via Pygments. (Handy for printing Python code).

Obviously you could skip the conversion step and just format your
ticket as HTML in the normal way. The key bit is the multipurpose
ExecWB function. The second param controls whether the printer
selection dialog is shown or not. I generally tell it not to
prompt, which goes to the default. In this example I've set it to
1 which forces a prompt.

<code>
import os, sys
import codecs
import glob
import tempfile
import time

import pygments
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import HtmlFormatter
import win32com.client


css_filepath = os.path.join (os.path.dirname (__file__), "print.css")

def main (fileglob, encoding="utf-8"):
   ie = win32com.client.gencache.EnsureDispatch 
("InternetExplorer.Application")
   html_filepaths = []
   try:
     for filepath in glob.glob (fileglob):
       formatter = HtmlFormatter (
         title=filepath,
         linenos="inline",
         full=True,
         cssfile=css_filepath,
         noclobber_cssfile=True
       )
       lexer = get_lexer_for_filename (filepath)
       with tempfile.NamedTemporaryFile (suffix=".html", delete=False) 
as html_file:
         utext = codecs.open (filepath, encoding=encoding).read ()
         highlighted = pygments.highlight (utext, lexer, formatter)
         html_file.write (highlighted.encode ("utf8"))

       #
       # Load the temporary HTML file up in IE and
       # print it to the default printer, relying
       # on the fact the IE will load Windows filepaths
       # without strictly requiring file:// URLs with
       # escaped paths.
       #
       ie.Navigate (html_file.name)
       while ie.ReadyState != 4 or ie.Busy:
         pass
       ie.ExecWB (6, 1, None, None)
       while ie.ReadyState != 4 or ie.Busy:
         pass
       html_filepaths.append (html_file.name)
   finally:
     #
     # This is arbitrary, but avoids having to implement
     # event handlers. It takes a while for the print
     # handler to complete; wait until it does before
     # closing IE.
     #
     time.sleep (5)
     ie.Quit ()
     for filepath in html_filepaths:
       os.unlink (filepath)

if __name__ == '__main__':
   main (*sys.argv[1:])



</code>

TJG

From pkoek11 at xs4all.nl  Thu Sep 23 17:26:45 2010
From: pkoek11 at xs4all.nl (Pete)
Date: Thu, 23 Sep 2010 11:26:45 -0400
Subject: [Tutor] __import__()
Message-ID: <2683D022-51EA-4E64-9134-0EA2B677F9A8@xs4all.nl>

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 *

?

thanks,

Pete

From pkoek11 at xs4all.nl  Thu Sep 23 17:45:29 2010
From: pkoek11 at xs4all.nl (Pete)
Date: Thu, 23 Sep 2010 11:45:29 -0400
Subject: [Tutor] Dict of function calls
In-Reply-To: <201009230750.16683.steve@pearwood.info>
References: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
	<201009230750.16683.steve@pearwood.info>
Message-ID: <10F2C778-2383-4D8F-9A0F-DDC99493954B@xs4all.nl>

> Oh, and (4)... in Python circles, it's traditional but not compulsory 
> to use metasyntactic variables named after Monty Python sketches 
> rather than foo and bar. So spam, ham, eggs, parrot (dead or 
> otherwise), names of cheeses, aardvark..., although there is no 
> standard order.

Hm, someone maybe should update http://en.wikipedia.org/wiki/Foobar
... as there is a python example listed there...

- Pete

From ranceh at gmail.com  Thu Sep 23 20:18:33 2010
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 23 Sep 2010 13:18:33 -0500
Subject: [Tutor] Windows Printing, Round 2
Message-ID: <AANLkTimOkZ6TLFwmBqD-cWY4fzdGqwHdb=-GhJ4O2B8i@mail.gmail.com>

Again I'm referencing Tim Golden from

http://timgolden.me.uk/python/win32_how_do_i/print.html


This code block is relevant:

<code>

import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()
#
# raw_data could equally be raw PCL/PS read from
#  some print-to-file operation
#
if sys.version_info >= (3,):
  raw_data = bytes ("This is a test", "utf-8")
else:
  raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
  hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data",
None, "RAW"))
  try:
    win32print.WritePrinter (hPrinter, raw_data)
  finally:
    win32print.EndDocPrinter (hPrinter)
finally:
  win32print.ClosePrinter (hPrinter)

</code>



Things are progressing along and I'm really more and more excited
about python, every time I try to do something, It just seems to work
and be straightforward.

Notes:  AFAICS win32pring.StartDocPrinter(hPrinter, 1, (jobname, None,
None)) might be better as the last "None" tells the system to process
through the print driver, Raw Data bypasses the print driver.
Due to the variety of printers involved, I think bypassing the print
driver with "RAW" will come back and bite me later.

I also added a variable to catch the output from
win32print.WritePrinter() so it would not display on the screen.  I
called it hSize.

Questions:

Under python 3 I need to send a byte string to the printer.  But I
wont have a byte string, I'll have a filename

What is the pythonic way to convert a file to a bytestream?

I can open the file for reading, and loop line by line through the
file appending bytes(line, "utf-8") to variable but this doesn't seem
right to me somehow.

Is there a better way to do this?


My HP laserjet 1100 does not print the job automatically.  It accepts
the job, processes the job, and then lights up the lights on the front
of the printer and waits.  When I hit the button, then the document
prints.

I have only seen this behavior before when printing envelopes.  When
an envelope print job goes to the printer it behaves the same way my
python print jobs are.

I suspect that this has to do with the fact that the page size of the
printjob is either not specified or different from the standard 8.5 in
wide x 11 in long it can handle.

win32print documentation mentions DocumentProperties and
DeviceCapabilities that might help, but I don't see how to use them to
implement a solution for my problem.

I further suspect that there are other printers out there that will
behave similarly if they don't have specified what they needed.

How do you deal with this problem?

From mail at timgolden.me.uk  Thu Sep 23 21:15:41 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 23 Sep 2010 20:15:41 +0100
Subject: [Tutor] Windows Printing, Round 2
In-Reply-To: <AANLkTimOkZ6TLFwmBqD-cWY4fzdGqwHdb=-GhJ4O2B8i@mail.gmail.com>
References: <AANLkTimOkZ6TLFwmBqD-cWY4fzdGqwHdb=-GhJ4O2B8i@mail.gmail.com>
Message-ID: <4C9BA75D.4040405@timgolden.me.uk>

On 23/09/2010 7:18 PM, Rance Hall wrote:
> Again I'm referencing Tim Golden from
>
> http://timgolden.me.uk/python/win32_how_do_i/print.html
>
>
> This code block is relevant:
>
> <code>
>
> import os, sys
> import win32print
> printer_name = win32print.GetDefaultPrinter ()
> #
> # raw_data could equally be raw PCL/PS read from
> #  some print-to-file operation
> #
> if sys.version_info>= (3,):
>    raw_data = bytes ("This is a test", "utf-8")
> else:
>    raw_data = "This is a test"
>
> hPrinter = win32print.OpenPrinter (printer_name)
> try:
>    hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data",
> None, "RAW"))
>    try:
>      win32print.WritePrinter (hPrinter, raw_data)
>    finally:
>      win32print.EndDocPrinter (hPrinter)
> finally:
>    win32print.ClosePrinter (hPrinter)
>
> </code>
>
>
>
> Things are progressing along and I'm really more and more excited
> about python, every time I try to do something, It just seems to work
> and be straightforward.
>
> Notes:  AFAICS win32pring.StartDocPrinter(hPrinter, 1, (jobname, None,
> None)) might be better as the last "None" tells the system to process
> through the print driver, Raw Data bypasses the print driver.
> Due to the variety of printers involved, I think bypassing the print
> driver with "RAW" will come back and bite me later.
>
> I also added a variable to catch the output from
> win32print.WritePrinter() so it would not display on the screen.  I
> called it hSize.
>
> Questions:
>
> Under python 3 I need to send a byte string to the printer.  But I
> wont have a byte string, I'll have a filename
>
> What is the pythonic way to convert a file to a bytestream?
>
> I can open the file for reading, and loop line by line through the
> file appending bytes(line, "utf-8") to variable but this doesn't seem
> right to me somehow.
>
> Is there a better way to do this?
>
>
> My HP laserjet 1100 does not print the job automatically.  It accepts
> the job, processes the job, and then lights up the lights on the front
> of the printer and waits.  When I hit the button, then the document
> prints.
>
> I have only seen this behavior before when printing envelopes.  When
> an envelope print job goes to the printer it behaves the same way my
> python print jobs are.
>
> I suspect that this has to do with the fact that the page size of the
> printjob is either not specified or different from the standard 8.5 in
> wide x 11 in long it can handle.
>
> win32print documentation mentions DocumentProperties and
> DeviceCapabilities that might help, but I don't see how to use them to
> implement a solution for my problem.
>
> I further suspect that there are other printers out there that will
> behave similarly if they don't have specified what they needed.
>
> How do you deal with this problem?

Essentially the complexity of the answer to this question -- the big
gap between raw (textish) data and any other formatted output -- was
what prompted my earlier suggestion to use IE as a print engine.

An easy answer to your questions above would be:

send the file's byte contents (see snippet below) followed by a formfeed
to prompt the printer into actually doing something.

<code>
import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()  # for simplicity

raw_data = open ("filename.txt", "rb").read () + b"\x0c"

# OpenPrinter / ClosePrinter dance as above

</code>

Does that help?

TJG

From mehgcap at gmail.com  Thu Sep 23 21:32:55 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 23 Sep 2010 15:32:55 -0400
Subject: [Tutor] functions: use return or exceptions?
Message-ID: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>

Hi all,
A general coding question: is it better to use return(False) (or 0, or
-1, or whatever) or to raise whateverError("oops")? Are there cases
for each?

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From waynejwerner at gmail.com  Thu Sep 23 21:47:21 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Thu, 23 Sep 2010 14:47:21 -0500
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
Message-ID: <AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>

On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> A general coding question: is it better to use return(False) (or 0, or
> -1, or whatever) or to raise whateverError("oops")? Are there cases
> for each?


It depends on your prevailing philosophy - if you like the EAFP that
prevails in python, it's better to raise an error. Usually that indicates
that something has failed.

OTOH, a lot of people feel that using exceptions as control flow is bad
practice - they're exceptional so they should only arise in exceptional
case.

There may be performance issues, though I'm not familiar enough with that
yet.

just my two bits,
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/850c35d0/attachment.html>

From rabidpoobear at gmail.com  Thu Sep 23 22:06:25 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Thu, 23 Sep 2010 15:06:25 -0500
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
	<AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
Message-ID: <2679255D-8483-4952-96DE-A3448F38DC7C@gmail.com>

You should do both. Raise an exception in the exceptional case.

My general pattern is to return None if no results exist, return the results if they do exist, and raise an exception if I couldn't perform the function.

Eg. If I have a function that creates a list of users with a first name of bob, I'll return the users or None (or probably an empty list) but if the db connection is unsuccessful I'll let the exception it throws propagate back up from my function, or possibly trap and rethrow the exception.

Or if a db connection error shouldn't matter to the calling function, I just won't re raise the exception.

I may not actually do that in practice, depending on the implications, but that's my general idea usually.

-----------------------------
Sent from a mobile device with a bad e-mail client.
-----------------------------

On Sep 23, 2010, at 2:47 PM, Wayne Werner <waynejwerner at gmail.com> wrote:

> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall <mehgcap at gmail.com> wrote:
> Hi all,
> A general coding question: is it better to use return(False) (or 0, or
> -1, or whatever) or to raise whateverError("oops")? Are there cases
> for each?
> 
> It depends on your prevailing philosophy - if you like the EAFP that prevails in python, it's better to raise an error. Usually that indicates that something has failed.
> 
> OTOH, a lot of people feel that using exceptions as control flow is bad practice - they're exceptional so they should only arise in exceptional case.
> 
> There may be performance issues, though I'm not familiar enough with that yet.
> 
> just my two bits,
> -Wayne
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/563a6bc2/attachment.html>

From rwobben at hotmail.com  Thu Sep 23 22:20:25 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 23 Sep 2010 20:20:25 +0000
Subject: [Tutor] pure function problem
In-Reply-To: <SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>,
	<AANLkTi=Gd4Hj9ngk1Sw5eoNaxxTUYqLCz4bMNEbGVk7c@mail.gmail.com>,
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>
Message-ID: <SNT118-W157053C951007428D08BBBAE610@phx.gbl>




________________________________
> From: rwobben at hotmail.com
> To: tutor at python.org
> Subject: RE: [Tutor] pure function problem
> Date: Thu, 23 Sep 2010 10:15:07 +0000
>
>
>
>> Date: Thu, 23 Sep 2010 05:36:58 -0400
>> Subject: Re: [Tutor] pure function problem
>> From: jemejones at gmail.com
>> To: tutor at python.org
>> CC: rwobben at hotmail.com
>>
>> The problem is that your class definition doesn't do anything to
>> explicitly set those attributes.
>>
>> On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben wrote:
>>
>>> class tijd :
>>> pass
>>
>> You're not doing any explicit setting of attributes at the class level.
>>
>>
>>> time = tijd()
>>> time.hour = 20
>>> time.minutes = 20
>>> time.seconds = 20
>>
>> You set them on this instance.
>>
>>> seconds = 20
>>> uitkomst = tijd()
>>
>> But not on this one.
>>
>> What you probably want to do is something like this:
>>
>> class tijd(object):
>> def __init__(self):
>> self.hour = 20
>> self.minutes = 20
>> self.seconds = 20
>>
>> Or if you prefer to set these when you create the instance, you can
>> pass in values like this:
>>
>> class tijd(object):
>> def __init__(self, hour=20, minutes=20, seconds=20):
>> self.hour = hour
>> self.minutes = minutes
>> self.seconds = seconds
>>
>> I noticed something odd just a sec ago. You have this:
>>> uitkomst = tijd()
>>> uitkomst = increment(time, seconds)
>>> print uitkomst.minutes, uitkomst.seconds
>>
>> You're creating a tijd instance, binding uitkomst to it, then
>> overwriting that instance with what you return from increment().
>>
>> Anyway, hth.
>>
>> - jmj
>
>
> Correct,
>
> I try to find a way to solve this error message.
>
> Roelof
>

 
Oke, 
 
I changed everything to this : 
 
class tijd :
    pass
 
def increment(time, seconds):
    sum = tijd()
    sum.seconds = time.seconds + seconds 
    
    if sum.seconds> 60 :
        minutes, seconds = divmod(sum.seconds, 60)
        sum.seconds = seconds 
        sum.minutes = time.minutes + minutes
    return sum
 
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = increment(time, seconds)
print time(uitkomst)
 
But now Im getting this error message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 21, in <module>
    print time(uitkomst)
AttributeError: tijd instance has no __call__ method
 
 
 
Roelof
  		 	   		  

From oberoc at gmail.com  Thu Sep 23 22:27:11 2010
From: oberoc at gmail.com (Tino Dai)
Date: Thu, 23 Sep 2010 16:27:11 -0400
Subject: [Tutor] Test Drive Development, DocTest, UnitTest
In-Reply-To: <201009230848.14076.steve@pearwood.info>
References: <AANLkTinLZv12WX-9E6a0Hju2Qohk13VDMooWYKThyLA5@mail.gmail.com>
	<201009220845.45017.steve@pearwood.info>
	<AANLkTinouf+azuNK1M6N4Kd_Pm17zEBx4QQZ61CuAKYb@mail.gmail.com>
	<201009230848.14076.steve@pearwood.info>
Message-ID: <AANLkTimL1TUKFuJmysGv7pDCPkr4S-zm-W0-WHiACP7n@mail.gmail.com>

> The lines between doc tests, blackbox testing, whitebox testing, and
> regression testing is blurry. People may legitimately disagree on
> whether a specific test is documentation, testing the interface,
> testing the implementation, or all three.
>

Wow!!! Ok that clears up a lot. Thank you!!!!
Just to clear some things up:

                Internal == doctest
                External == blackbox testng (using unit tests)

Thanks again! Now off to go write some doctests and unit tests! :)
-Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/53b568ad/attachment.html>

From mehgcap at gmail.com  Fri Sep 24 00:38:34 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Thu, 23 Sep 2010 18:38:34 -0400
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <2679255D-8483-4952-96DE-A3448F38DC7C@gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
	<AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
	<2679255D-8483-4952-96DE-A3448F38DC7C@gmail.com>
Message-ID: <AANLkTimwmpmjdMJBcsnYg2xpy2wkNnR0wgrgsCxe-M3G@mail.gmail.com>

Thanks for the responses. Up to now, despite using some Java and a lot
of Python, I have not even tried raising exceptions. I can see
situations where they would be useful, but was not sure if I should
use them as much as possible or just keep relying on the return codes
that I am used to. Sounds like either way works and, as was stated,
exceptions should be used in "exceptional" cases.

On 9/23/10, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> You should do both. Raise an exception in the exceptional case.
>
> My general pattern is to return None if no results exist, return the results
> if they do exist, and raise an exception if I couldn't perform the function.
>
> Eg. If I have a function that creates a list of users with a first name of
> bob, I'll return the users or None (or probably an empty list) but if the db
> connection is unsuccessful I'll let the exception it throws propagate back
> up from my function, or possibly trap and rethrow the exception.
>
> Or if a db connection error shouldn't matter to the calling function, I just
> won't re raise the exception.
>
> I may not actually do that in practice, depending on the implications, but
> that's my general idea usually.
>
> -----------------------------
> Sent from a mobile device with a bad e-mail client.
> -----------------------------
>
> On Sep 23, 2010, at 2:47 PM, Wayne Werner <waynejwerner at gmail.com> wrote:
>
>> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall <mehgcap at gmail.com> wrote:
>> Hi all,
>> A general coding question: is it better to use return(False) (or 0, or
>> -1, or whatever) or to raise whateverError("oops")? Are there cases
>> for each?
>>
>> It depends on your prevailing philosophy - if you like the EAFP that
>> prevails in python, it's better to raise an error. Usually that indicates
>> that something has failed.
>>
>> OTOH, a lot of people feel that using exceptions as control flow is bad
>> practice - they're exceptional so they should only arise in exceptional
>> case.
>>
>> There may be performance issues, though I'm not familiar enough with that
>> yet.
>>
>> just my two bits,
>> -Wayne
>> _______________________________________________
>> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From steve at pearwood.info  Fri Sep 24 02:54:01 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Sep 2010 10:54:01 +1000
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <2679255D-8483-4952-96DE-A3448F38DC7C@gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
	<AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
	<2679255D-8483-4952-96DE-A3448F38DC7C@gmail.com>
Message-ID: <201009241054.02432.steve@pearwood.info>

On Fri, 24 Sep 2010 06:06:25 am Luke Paireepinart wrote:
> You should do both. Raise an exception in the exceptional case.
>
> My general pattern is to return None if no results exist, return the
> results if they do exist, and raise an exception if I couldn't
> perform the function.

I hate that! I find that idiom, as used by the re module, to be the 
worst of all possible worlds.

To do something with a search result, you have to:

be prepared for an exception (either catch it, or let it bubble up the 
call chain);

if you get a result, you have to compare it to None and be prepared to 
ignore it;

if the result isn't None, then you can do something with it. This itself 
may include further tests or catching exceptions.

At the interactive interpreter, you can't write (say):

regex.search(text).group()

because the result is sometimes None. So you have to split it into two 
operations:

mo = regex.search(text)
if mo: mo.group()

That's a nuisance when working interactively. I would prefer it if the 
re search functions returned a "blank" match object, so you could say:


re.search('sp.m', 'I like spam and eggs').group(0)
=> prints 'spam'

re.search('sp.m', 'I like ham and eggs').group(0)
=> prints ''


> Eg. If I have a function that creates a list of users with a first
> name of bob, I'll return the users or None (or probably an empty
> list) 

Returning an empty list makes sense. Returning None makes no sense at 
all.


> but if the db connection is unsuccessful I'll let the exception 
> it throws propagate back up from my function, or possibly trap and
> rethrow the exception.

That's okay.


> Or if a db connection error shouldn't matter to the calling function,
> I just won't re raise the exception.

That's a reasonable approach as well.




-- 
Steven D'Aprano

From emile at fenx.com  Fri Sep 24 03:02:18 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 23 Sep 2010 18:02:18 -0700
Subject: [Tutor] __import__()
In-Reply-To: <2683D022-51EA-4E64-9134-0EA2B677F9A8@xs4all.nl>
References: <2683D022-51EA-4E64-9134-0EA2B677F9A8@xs4all.nl>
Message-ID: <i7gt6v$iqn$1@dough.gmane.org>

On 9/23/2010 8:26 AM Pete said...
> 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 *

Something you probably really don't want to do as it will pollute your 
namespace. But, if you insist, you could play with:

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38)
[MSC v.1500 32 bit (Intel)] on win32
 >>> xx = __import__('httplib')
 >>> dir(xx)
['ACCEPTED', 'BAD_GATEWAY', ...]

 >>> for ii in dir(xx): globals()[ii] = xx.__dict__[ii]
...
 >>> dir()
['ACCEPTED', 'BAD_GATEWAY', ...]
 >>>

Note, this really is for consenting adults only, and changing globals() 
is not really supported and may change in the future.  Note that from 
the docs, globals() is defined to "Return a dictionary representing the 
current global symbol table" and not as "Return the dictionary holding 
the current global symbol table" so the fact that it works on may 
version (and perhaps all others) doesn't mean it'll work everywhere.

HTH,

Emile










































From steve at pearwood.info  Fri Sep 24 03:06:09 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Sep 2010 11:06:09 +1000
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
	<AANLkTindcUYC4oLDkzYf5nYfN_kVesAmrHpOmPtmEWey@mail.gmail.com>
Message-ID: <201009241106.10518.steve@pearwood.info>

On Fri, 24 Sep 2010 05:47:21 am Wayne Werner wrote:

> OTOH, a lot of people feel that using exceptions as control flow is
> bad practice - they're exceptional so they should only arise in
> exceptional case.

That's not the Python philosophy. Python uses exceptions for flow 
control: iteration catching StopIteration is just the most common 
example. There's nothing wrong with using exceptions in your own code 
for the same purpose.

Note carefully that exceptions *cannot* be used to implement 
unstructured GOTOs, since you can't jump into the middle of a function, 
or backwards.

Speaking of GOTO, and it's even more evil cousin COME FROM, see this 
wonderful April 1st joke:

http://mail.python.org/pipermail/python-announce-list/2004-April/002982.html


> There may be performance issues, though I'm not familiar enough with
> that yet.

Setting up a try...except block is fast, about as fast as the "pass" 
statement. "Do nothing" is about as fast as you can get in Python, so 
you need not fear wrapping things in a try block.

But catching an exception is about 100 times more expensive. If you're 
using *lots* of exceptions for flow control, then your code will 
probably be slow. A single exception to end the flow, like 
StopIteration, doesn't matter.



-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 24 03:35:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Sep 2010 11:35:28 +1000
Subject: [Tutor] functions: use return or exceptions?
In-Reply-To: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
References: <AANLkTikjUE+kkbDWEsztfsVOrYEUrB9qVCON9L=E2W7R@mail.gmail.com>
Message-ID: <201009241135.28361.steve@pearwood.info>

On Fri, 24 Sep 2010 05:32:55 am Alex Hall wrote:
> Hi all,
> A general coding question: is it better to use return(False) (or 0,
> or -1, or whatever) or to raise whateverError("oops")? Are there
> cases for each?

Yes.

There is absolutely no point whatsoever raising an exception, or 
returning a "magic" sentinel value, if an ordinary value would do. For 
example, this would be silly:


def is_spam(string):
    """Return True if string equals "spam", otherwise 
    raise an exception."""
    if string.lower().strip() == "spam":
        return True
    raise ValueError("not spam")


If is_spam can only ever return True, there's no need to look at the 
return result. So why bother to return anything? This would be better:

def verify_spam(string):
    """Raise ValueError unless string is spam."""
    if string.lower().strip() != "spam":
        raise ValueError("not spam")

(Technically, this will return None, but that's just because Python 
doesn't have procedures, only functions.)

This is appropriate if your use-case is something like this:

def prepare_meal(meat, condiments):
    """Prepare a yummy meal from the only meat-like substance 
    worth eating."""
    verify_spam(meat)
    if "pickle" in condiments:
        # I don't like pickle
        condiments.remove("pickle")
    # but I do like spam
    condiments.append("mashed spam")
    return "spam" + spread(condiments, meat) + "spam spam spam"


On the other hand, returning True or False would be better if your 
use-case was like this:

def prepare_meal(meat, condiments):
    """Prepare a yummy meal."""
    if is_spam(meat):
        vikings.sing("spam spam spam LOVELY SPAM!!!")
    if "pickle" in condiments:
        condiments.remove("pickle")
    return "bread" + spread(condiments, meat) + "bread"



A good guide is to look at what functions in the standard library do. 
You'll find examples of functions that return a magic value or raise an 
exception:

"ethel the aardvark".find('spam')
=> -1

"ethel the aardvark".index('spam')
=> raises exception

Of course, functions should generally raise exceptions for errors:

"ethel the aardvark".find(42)
=> raises exception

There are very few places in Python that suppress and hide arbitrary 
errors from the user. This should be done with care, if at all.


-- 
Steven D'Aprano

From steve at pearwood.info  Fri Sep 24 04:47:22 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Sep 2010 12:47:22 +1000
Subject: [Tutor] Dict of function calls
In-Reply-To: <10F2C778-2383-4D8F-9A0F-DDC99493954B@xs4all.nl>
References: <032EDA0A-B635-44C8-9927-CF814E2CA386@xs4all.nl>
	<201009230750.16683.steve@pearwood.info>
	<10F2C778-2383-4D8F-9A0F-DDC99493954B@xs4all.nl>
Message-ID: <201009241247.22521.steve@pearwood.info>

On Fri, 24 Sep 2010 01:45:29 am you wrote:
> > Oh, and (4)... in Python circles, it's traditional but not
> > compulsory to use metasyntactic variables named after Monty Python
> > sketches rather than foo and bar. So spam, ham, eggs, parrot (dead
> > or otherwise), names of cheeses, aardvark..., although there is no
> > standard order.
>
> Hm, someone maybe should update http://en.wikipedia.org/wiki/Foobar
> ... as there is a python example listed there...

If only Wikipedia was an encyclopedia anyone can edit!

*wink*



-- 
Steven D'Aprano

From kb1pkl at aim.com  Fri Sep 24 04:51:37 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 23 Sep 2010 22:51:37 -0400
Subject: [Tutor] Plotting a Linear Equation
Message-ID: <4C9C1239.5090509@aim.com>

  Hello tutors. Probably the wrong mailing list, but someone might know.
I want to use matplotlib (or similar) to plot an equation in 
slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've 
read and tested, you can only plot with a series of points. I could make 
two points out of those manually, but I was wondering if anyone knew of 
an easier way. Thanks.

From steve at pearwood.info  Fri Sep 24 05:00:40 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 24 Sep 2010 13:00:40 +1000
Subject: [Tutor] pure function problem
In-Reply-To: <SNT118-W157053C951007428D08BBBAE610@phx.gbl>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>
	<SNT118-W157053C951007428D08BBBAE610@phx.gbl>
Message-ID: <201009241300.40989.steve@pearwood.info>

Roelof, please learn to delete unnecessarily quoted text. There's no 
need to quoted the entire discussion every time you answer.

On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:

> time = tijd()
[...]
> print time(uitkomst)

Why are you calling time as a function, when it is a tijd instance?




-- 
Steven D'Aprano

From rwobben at hotmail.com  Fri Sep 24 07:43:42 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 24 Sep 2010 05:43:42 +0000
Subject: [Tutor] pure function problem
In-Reply-To: <201009241300.40989.steve@pearwood.info>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>,
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>,
	<SNT118-W157053C951007428D08BBBAE610@phx.gbl>,
	<201009241300.40989.steve@pearwood.info>
Message-ID: <SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>




----------------------------------------
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Fri, 24 Sep 2010 13:00:40 +1000
> Subject: Re: [Tutor] pure function problem
>
> Roelof, please learn to delete unnecessarily quoted text. There's no
> need to quoted the entire discussion every time you answer.
>
> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
>
>> time = tijd()
> [...]
>> print time(uitkomst)
>
> Why are you calling time as a function, when it is a tijd instance?
>
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
 
Hello Steve,
 
I found this in my tutorial.
 
13.8. Instances as return values?
Functions can return instances. For example, find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle:
def find_center(box):
    p = Point()
    p.x = box.corner.x + box.width/2.0
    p.y = box.corner.y - box.height/2.0
    return p
To call this function, pass box as an argument and assign the result to a variable:
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)

 
So i followed it but appearently not the good way.
 
Roelof
  		 	   		  

From gregbair at gmail.com  Fri Sep 24 09:28:10 2010
From: gregbair at gmail.com (Greg)
Date: Fri, 24 Sep 2010 03:28:10 -0400
Subject: [Tutor] Plotting a Linear Equation
In-Reply-To: <4C9C1239.5090509@aim.com>
References: <4C9C1239.5090509@aim.com>
Message-ID: <AANLkTimK_-FfWQZAFuo0YiejU-Mv_QydF98QhQVcEqdt@mail.gmail.com>

On Thu, Sep 23, 2010 at 10:51 PM, Corey Richardson <kb1pkl at aim.com> wrote:

>  Hello tutors. Probably the wrong mailing list, but someone might know.
> I want to use matplotlib (or similar) to plot an equation in
> slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've read
> and tested, you can only plot with a series of points. I could make two
> points out of those manually, but I was wondering if anyone knew of an
> easier way. Thanks.
>

You could just have your program compute the x- and y- intercepts, then plug
them into matplotlib.  Am I correct in that?


-- 
Greg Bair
gregbair at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100924/26087397/attachment.html>

From smokefloat at gmail.com  Fri Sep 24 09:39:30 2010
From: smokefloat at gmail.com (David Hutto)
Date: Fri, 24 Sep 2010 03:39:30 -0400
Subject: [Tutor] pure function problem
In-Reply-To: <SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>
	<SNT118-W157053C951007428D08BBBAE610@phx.gbl>
	<201009241300.40989.steve@pearwood.info>
	<SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>
Message-ID: <AANLkTikXejk+FFA=+0mdpEVhScz=4Tq_MEMHSQw1aaay@mail.gmail.com>

On Fri, Sep 24, 2010 at 1:43 AM, Roelof Wobben <rwobben at hotmail.com> wrote:
>
>
>
> ----------------------------------------
>> From: steve at pearwood.info
>> To: tutor at python.org
>> Date: Fri, 24 Sep 2010 13:00:40 +1000
>> Subject: Re: [Tutor] pure function problem
>>
>> Roelof, please learn to delete unnecessarily quoted text. There's no
>> need to quoted the entire discussion every time you answer.
>>
>> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
>>
>>> time = tijd()
>> [...]
>>> print time(uitkomst)
>>
>> Why are you calling time as a function, when it is a tijd instance?
>>
>>
>>
>>
>> --
>> Steven D'Aprano
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> Hello Steve,
>
> I found this in my tutorial.
>
> 13.8. Instances as return values?
> Functions can return instances. For example, find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle:
> def find_center(box):
> ? ?p = Point()
> ? ?p.x = box.corner.x + box.width/2.0
> ? ?p.y = box.corner.y - box.height/2.0
> ? ?return p
> To call this function, pass box as an argument and assign the result to a variable:
>>>> center = find_center(box)
>>>> print_point(center)
> (50.0, 100.0)
>
>
> So i followed it but appearently not the good way.
>
> Roelof
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
If I'm understanding the question correctly(I skim alot)
It looks like you're trying to use a class like a function.

If you had:

class tijd(object):
    def bob:
        pass

then you would call bob from the class in an instance like this:

aclass = tijd()
calledClassFunction = aclass.bob

but if you have

aclass = tijd()
calledClassFunction = aclass.notbob

then you can't access it, because notbob is not in tijd(), therefore
not in aclass, which is still the same as being tijd().bob, you just
have to call the
class instance before the function can be accessed.

From davea at ieee.org  Fri Sep 24 12:29:03 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 24 Sep 2010 06:29:03 -0400
Subject: [Tutor] pure function problem
In-Reply-To: <SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>,
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>,
	<SNT118-W157053C951007428D08BBBAE610@phx.gbl>,
	<201009241300.40989.steve@pearwood.info>
	<SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>
Message-ID: <4C9C7D6F.5080700@ieee.org>

  On 2:59 PM, Roelof Wobben wrote:
>
>
> ----------------------------------------
>> From: steve at pearwood.info
>> <snip>
>> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
>>
>>> time =ijd()
>> [...]
>>> print time(uitkomst)
>> Why are you calling time as a function, when it is a tijd instance?
>>
>> <snip>
>
> Hello Steve,
>
> I found this in my tutorial.
>
> 13.8. Instances as return values?
> Functions can return instances. For example, find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle:
> def find_center(box):
>      p =oint()
>      p.x =ox.corner.x + box.width/2.0
>      p.y =ox.corner.y - box.height/2.0
>      return p
> To call this function, pass box as an argument and assign the result to a variable:
>>>> center =ind_center(box)
>>>> print_point(center)
> (50.0, 100.0)
>
>
> So i followed it but appearently not the good way.
>
> Roelof
There's a big difference between   print_point() and   print time().

print_point() in your tutorial is a function, presumably defined 
someplace else.

You used print time(),  (no underscore), which uses the print statement, 
and tries to call a function called time().

Since you defined time as an instance of your class, and didn't do 
anything special, it's not callable.

DaveA


From rwobben at hotmail.com  Fri Sep 24 12:40:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 24 Sep 2010 10:40:46 +0000
Subject: [Tutor] pure function problem
In-Reply-To: <4C9C7D6F.5080700@ieee.org>
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>,
	<SNT118-W57C61465FD9605E6E3E500AE610@phx.gbl>,
	<SNT118-W157053C951007428D08BBBAE610@phx.gbl>,
	<201009241300.40989.steve@pearwood.info>
	<SNT118-W16A9A804819BE048BBD6DDAE620@phx.gbl>,
	<4C9C7D6F.5080700@ieee.org>
Message-ID: <SNT118-W46627FE73899BE912DE70DAE620@phx.gbl>




----------------------------------------
> Date: Fri, 24 Sep 2010 06:29:03 -0400
> From: davea at ieee.org
> To: rwobben at hotmail.com
> CC: tutor at python.org
> Subject: Re: [Tutor] pure function problem
>
> On 2:59 PM, Roelof Wobben wrote:
>>
>>
>> ----------------------------------------
>>> From: steve at pearwood.info
>>> 
>>> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
>>>
>>>> time =ijd()
>>> [...]
>>>> print time(uitkomst)
>>> Why are you calling time as a function, when it is a tijd instance?
>>>
>>> 
>>
>> Hello Steve,
>>
>> I found this in my tutorial.
>>
>> 13.8. Instances as return values?
>> Functions can return instances. For example, find_center takes a Rectangle as an argument and returns a Point that contains the coordinates of the center of the Rectangle:
>> def find_center(box):
>> p =oint()
>> p.x =ox.corner.x + box.width/2.0
>> p.y =ox.corner.y - box.height/2.0
>> return p
>> To call this function, pass box as an argument and assign the result to a variable:
>>>>> center =ind_center(box)
>>>>> print_point(center)
>> (50.0, 100.0)
>>
>>
>> So i followed it but appearently not the good way.
>>
>> Roelof
> There's a big difference between print_point() and print time().
>
> print_point() in your tutorial is a function, presumably defined
> someplace else.
>
> You used print time(), (no underscore), which uses the print statement,
> and tries to call a function called time().
>
> Since you defined time as an instance of your class, and didn't do
> anything special, it's not callable.
>
> DaveA
>
 
Oke, 
 
I see it now.
I have to us a function that i had to write a few questions before.
 
Thanks everybody 

Roelof

  		 	   		  

From kb1pkl at aim.com  Fri Sep 24 18:26:31 2010
From: kb1pkl at aim.com (kb1pkl at aim.com)
Date: Fri, 24 Sep 2010 12:26:31 -0400 (EDT)
Subject: [Tutor] Plotting a Linear Equation
In-Reply-To: <AANLkTimK_-FfWQZAFuo0YiejU-Mv_QydF98QhQVcEqdt@mail.gmail.com>
References: <4C9C1239.5090509@aim.com>
	<AANLkTimK_-FfWQZAFuo0YiejU-Mv_QydF98QhQVcEqdt@mail.gmail.com>
Message-ID: <8CD2A1C6185AFCF-854-182@webmail-m060.sysops.aol.com>




-----Original Message-----
From: Greg <gregbair at gmail.com>
To: tutor <tutor at python.org>
Sent: Fri, Sep 24, 2010 3:29 am
Subject: Re: [Tutor] Plotting a Linear Equation


On Thu, Sep 23, 2010 at 10:51 PM, Corey Richardson <kb1pkl at aim.com> 
wrote:

?Hello tutors. Probably the wrong mailing list, but someone might know.
I want to use matplotlib (or similar) to plot an equation in 
slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've 
read and tested, you can only plot with a series of points. I could 
make two points out of those manually, but I was wondering if anyone 
knew of an easier way. Thanks.



You could just have your program compute the x- and y- intercepts, then 
plug them into matplotlib. ?Am I correct in that??


--
Greg Bair
gregbair at gmail.com
______________________________________________________________________
Yes, you are correct. That's what I planned on doing if I couldn't plug 
the equation right into matplotlib.

  

From norman at khine.net  Fri Sep 24 19:58:44 2010
From: norman at khine.net (Norman Khine)
Date: Fri, 24 Sep 2010 19:58:44 +0200
Subject: [Tutor] list.append(x) but at a specific 'i'
In-Reply-To: <201009230547.45894.steve@pearwood.info>
References: <AANLkTikA9vcj_kk3ZwDOp6qCSVyEhZxLzAjovxAJ46ot@mail.gmail.com>
	<201009230547.45894.steve@pearwood.info>
Message-ID: <AANLkTinq++Wr+N6FHtObjXs2AOOG8O1o4CK1NvUAzgts@mail.gmail.com>

On Wed, Sep 22, 2010 at 9:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Wed, 22 Sep 2010 08:30:09 am Norman Khine wrote:
>
>> hello, how do i extend a python list but from a given [i],
>
> Do you mean to modify the list in place, like append() and extend() do,
> or do you mean to create a new list, like + does?
>
>
>> for example:
>> >>> a = ['a', 'b', 'e']
>> >>> b = ['c', 'd']
>> >>>
>> >>> a + b
>>
>> ['a', 'b', 'e', 'c', 'd']
>>
>>
>> but i want to put the items of 'b' at [-2] for example.
>
> When you ask a question, it usually helps to show the output you *want*,
> not the output you *don't want*, rather than to make assumptions about
> what other people will understand.
>
> When you say that you want the items of b *at* -2, taken literally that
> could mean:
>
>>>> a = ['a', 'b', 'e']
>>>> b = ['c', 'd']
>>>> a.insert(-2+1, b)
>>>> print(a)
> ['a', 'b', ['c', 'd'], 'e']
>
> Note that the items of b are kept as a single item, at the position you
> ask for, and the index you pass to insert() is one beyond when you want
> them to appear.
>
> To create a new list, instead of insert() use slicing:
>
>>>> a[:-2+1] + [b] + a[-2+1:]
> ['a', 'b', ['c', 'd'], 'e']
>
>
> If you want the items of b to *start* at -2, since there are exactly two
> items, extend() will do the job for in-place modification, otherwise +.
> But you already know that, because that was your example.
>
> If you want the items of b to *end* at -2, so that you get
> ['a', 'b', 'c', 'd', 'e'] then you could use repeated insertions:
>
> for c in b:
> ? ?a.insert(-2, c)
>
> but that will likely be slow for large lists. Better to use slicing. To
> create a new list is just like the above, except you don't create a
> temporary list-of-b first:
>
>>>> a[:-2+1] + b + a[-2+1:]
> ['a', 'b', 'c', 'd', 'e']
>
>
> To do it in place, assign to a slice:
>
>>>> a[-2:-2] = b
>>>> print(a)
> ['a', 'c', 'd', 'b', 'e']

thanks for all the replies, and the detailed information
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From flebber.crue at gmail.com  Sat Sep 25 11:29:34 2010
From: flebber.crue at gmail.com (Sayth Renshaw)
Date: Sat, 25 Sep 2010 19:29:34 +1000
Subject: [Tutor] Python And reading the Web - Javascript
Message-ID: <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J@mail.gmail.com>

Was hoping some could push me in the right direction about reading
data from web pages and what modules to use. Is there support for
reading if the page uses javascript?

If you know any good links to tutorials for this it would be great. I
was planning to use python 2.6 currently.

I want to read some data from the web it will be text and numeric i
was planning to export it to a database. I was thinking while I am
learning maybe something simple like Sqlite or MySQL.

I then want to read back data to perform sorting and some calculations on.

Any ideas in general in how to do this appreciated. i don't mind
reading so if you have some good links they are appreciated.

Thank You

Sayth

From ahmedn82 at hotmail.com  Thu Sep 23 07:04:14 2010
From: ahmedn82 at hotmail.com (Ahmed AL-Masri)
Date: Thu, 23 Sep 2010 13:04:14 +0800
Subject: [Tutor] input and raw input
Message-ID: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>

Hi,
any one have an idea about how we can input many number in the one time and change it to list.
for example:

a=input("Enter the number of your class in the school:")     # the number can be enter as: 12,13,14 or 12 13 14 with a space in between.

now how I can put these numbers into list like b=[12,13,14] with len( a ) =3

I tried with that but it's working only for a numbers less than 10 ex. 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in example above.

a=raw_input("Enter the number of your class in the school:")
m=[]
 for I range (len( a)):
    if a[I]==',':
        pass
    elif a[I]==' ':
        pass
    else:
        m.append(a[I])
m=map(float,m)
print m;print len( m )
>> [1,2,3]
>> 3

looking forward to seeing your help,
regards,
Ahmed


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100923/9590f33e/attachment.html>

From cfuller at thinkingplanet.net  Fri Sep 24 15:10:37 2010
From: cfuller at thinkingplanet.net (Chris Fuller)
Date: Fri, 24 Sep 2010 08:10:37 -0500
Subject: [Tutor] Plotting a Linear Equation
In-Reply-To: <4C9C1239.5090509@aim.com>
References: <4C9C1239.5090509@aim.com>
Message-ID: <201009240810.37599.cfuller@thinkingplanet.net>


It sounds to me like you need to set a nonzero linewidth.  The default is to 
not fill in the space between points.  Check out the documentation at 
http://matplotlib.sourceforge.net/contents.html.  It's a lot to wade through, 
but worth it when you learn how to unlock the power of the software.

Cheers

On Thursday 23 September 2010, Corey Richardson wrote:
>   Hello tutors. Probably the wrong mailing list, but someone might know.
> I want to use matplotlib (or similar) to plot an equation in
> slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've
> read and tested, you can only plot with a series of points. I could make
> two points out of those manually, but I was wondering if anyone knew of
> an easier way. Thanks.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From eq742 at ncf.ca  Mon Sep 20 12:35:13 2010
From: eq742 at ncf.ca (pierre dagenais)
Date: Mon, 20 Sep 2010 06:35:13 -0400
Subject: [Tutor] plotting pixels
In-Reply-To: <813627.27084.qm@web86704.mail.ird.yahoo.com>
References: <AANLkTimpvMoXtez2y_gqaFGKcm+oLkM+AKBxe=0pSUQ4@mail.gmail.com>
	<i6v9dk$rhf$1@dough.gmane.org>
	<AANLkTinWhmLgWg19KYJ+GCXcyjtoLDFEqvPYtk24J74h@mail.gmail.com>
	<AANLkTik=cnymQ8+0Ky0nK6F=EGtKY1y5G9FfNyAAY5Ck@mail.gmail.com>
	<813627.27084.qm@web86704.mail.ird.yahoo.com>
Message-ID: <4C9738E1.4060805@ncf.ca>

On 10-09-18 07:39 PM, ALAN GAULD wrote:
> > It appears that the Tk canvas widget does not support simply 
> plotting a pixel.
>
> Correct, and I agree it seems odd, but in practice drawing either 
> lines or
> ovals of one-pixel do the equivalent job - albeit a little more slowly.
>
> > The primitive obviously exists in the underlying code,
>
> It probably exists in the native graphics toolkit (Xlib or Win32 or Aqua)
> but it doesn't exist at the Tk level which is why Tkinter can't expose it.
>
> FWIW wxPython does provide a DrawPoint() method as part of its
> DeviceContext class.
>
> Digging a little deeper it seems the idiomatic way to do this in Python
> is to use PIL the Python Imaging Library to create a GIF or bitmap
> image and then insert that into Tkinters cancvas as an image object.
>
> The Pil ImageDraw class has a point() ethod
>
> I've never tried this but it is described in Grayson's (now out of 
> print?)
> book on Tkinter where he uses it to draw a Mandelbrot....
> The book may be available online these days...
>
> Nowdownloadall.com seems to have it although I've no idea
> of the legality of it!
>
> HTH,
>
> Alan G.
>
Here's a link, just don't download everything. It would be excessively 
large.

http://isohunt.com/download/212380933/%22Python+and+Tkinter+Programming%22.torrent

From knacktus at googlemail.com  Sat Sep 25 15:20:41 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sat, 25 Sep 2010 15:20:41 +0200
Subject: [Tutor] Python And reading the Web - Javascript
In-Reply-To: <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J@mail.gmail.com>
References: <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J@mail.gmail.com>
Message-ID: <4C9DF729.8080602@googlemail.com>

>
> Any ideas in general in how to do this appreciated. i don't mind
> reading so if you have some good links they are appreciated.
>

I have no experience myself with this task, but I would look at those 
resource:

1) For reading html pages in addition to the standard-lib modules:

http://www.crummy.com/software/BeautifulSoup/

2) For more advanced stuff it might be worth looking at a webkit 
implementation of Qt via PyQt Bindings:

http://doc.trolltech.com/4.7/qtwebkit.html

here the Python bindings

http://www.riverbankcomputing.co.uk/news

HTH,

Jan

From evert.rol at gmail.com  Sat Sep 25 15:40:12 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 25 Sep 2010 15:40:12 +0200
Subject: [Tutor] input and raw input
In-Reply-To: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
References: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
Message-ID: <C4714E5B-714B-4609-B902-EE8E14B4FBC0@gmail.com>

> any one have an idea about how we can input many number in the one time and change it to list.
> for example:
>  
> a=input("Enter the number of your class in the school:")     # the number can be enter as: 12,13,14 or 12 13 14 with a space in between.
>  
> now how I can put these numbers into list like b=[12,13,14] with len( a ) =3

A string has a method split(); that may help you.
In your case, where you want either a space or a comma as a separator, it depends whether both can be used at the same time. If not, you can check for the occurrence of one or the other separator and run split() with the correct separator. If both can occur in the same line, you may want to use the regex module instead: re.split()

hth,

  Evert

 
> I tried with that but it's working only for a numbers less than 10 ex. 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in example above.
>  
> a=raw_input("Enter the number of your class in the school:")
> m=[]
>  for I range (len( a)):
>     if a[I]==',':
>         pass
>     elif a[I]==' ':
>         pass
>     else:
>         m.append(a[I])
> m=map(float,m)
> print m;print len( m )
> >> [1,2,3]
> >> 3
>  
> looking forward to seeing your help,
> regards,
> Ahmed
>  
>  
>  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From flebber.crue at gmail.com  Sat Sep 25 17:30:28 2010
From: flebber.crue at gmail.com (Sayth Renshaw)
Date: Sun, 26 Sep 2010 01:30:28 +1000
Subject: [Tutor] Tutor Digest, Vol 79, Issue 134
In-Reply-To: <mailman.15.1285408803.13622.tutor@python.org>
References: <mailman.15.1285408803.13622.tutor@python.org>
Message-ID: <AANLkTik+_9KwgW-UPPd_9CFWq44SO1Gq_02LNmD4P1rp@mail.gmail.com>

I started seting up django. the only issue I am having is that all
instructions seem to assume that I am on linux.Don't suppose there are any
good instructions for those on a windows based system.

On Sat, Sep 25, 2010 at 8:00 PM, <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-request at python.org
>
> You can reach the person managing the list at
>        tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>   1. Re: pure function problem (Dave Angel)
>   2. Re: pure function problem (Roelof Wobben)
>   3. Re: Plotting a Linear Equation (kb1pkl at aim.com)
>   4. Re: list.append(x) but at a specific 'i' (Norman Khine)
>   5. Python And reading the Web - Javascript (Sayth Renshaw)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Fri, 24 Sep 2010 06:29:03 -0400
> From: Dave Angel <davea at ieee.org>
> To: Roelof Wobben <rwobben at hotmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] pure function problem
> Message-ID: <4C9C7D6F.5080700 at ieee.org>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
>  On 2:59 PM, Roelof Wobben wrote:
> >
> >
> > ----------------------------------------
> >> From: steve at pearwood.info
> >> <snip>
> >> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
> >>
> >>> time =ijd()
> >> [...]
> >>> print time(uitkomst)
> >> Why are you calling time as a function, when it is a tijd instance?
> >>
> >> <snip>
> >
> > Hello Steve,
> >
> > I found this in my tutorial.
> >
> > 13.8. Instances as return values?
> > Functions can return instances. For example, find_center takes a
> Rectangle as an argument and returns a Point that contains the coordinates
> of the center of the Rectangle:
> > def find_center(box):
> >      p =oint()
> >      p.x =ox.corner.x + box.width/2.0
> >      p.y =ox.corner.y - box.height/2.0
> >      return p
> > To call this function, pass box as an argument and assign the result to a
> variable:
> >>>> center =ind_center(box)
> >>>> print_point(center)
> > (50.0, 100.0)
> >
> >
> > So i followed it but appearently not the good way.
> >
> > Roelof
> There's a big difference between   print_point() and   print time().
>
> print_point() in your tutorial is a function, presumably defined
> someplace else.
>
> You used print time(),  (no underscore), which uses the print statement,
> and tries to call a function called time().
>
> Since you defined time as an instance of your class, and didn't do
> anything special, it's not callable.
>
> DaveA
>
>
>
> ------------------------------
>
> Message: 2
> Date: Fri, 24 Sep 2010 10:40:46 +0000
> From: Roelof Wobben <rwobben at hotmail.com>
> Cc: <tutor at python.org>
> Subject: Re: [Tutor] pure function problem
> Message-ID: <SNT118-W46627FE73899BE912DE70DAE620 at phx.gbl>
> Content-Type: text/plain; charset="iso-8859-1"
>
>
>
>
> ----------------------------------------
> > Date: Fri, 24 Sep 2010 06:29:03 -0400
> > From: davea at ieee.org
> > To: rwobben at hotmail.com
> > CC: tutor at python.org
> > Subject: Re: [Tutor] pure function problem
> >
> > On 2:59 PM, Roelof Wobben wrote:
> >>
> >>
> >> ----------------------------------------
> >>> From: steve at pearwood.info
> >>>
> >>> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
> >>>
> >>>> time =ijd()
> >>> [...]
> >>>> print time(uitkomst)
> >>> Why are you calling time as a function, when it is a tijd instance?
> >>>
> >>>
> >>
> >> Hello Steve,
> >>
> >> I found this in my tutorial.
> >>
> >> 13.8. Instances as return values?
> >> Functions can return instances. For example, find_center takes a
> Rectangle as an argument and returns a Point that contains the coordinates
> of the center of the Rectangle:
> >> def find_center(box):
> >> p =oint()
> >> p.x =ox.corner.x + box.width/2.0
> >> p.y =ox.corner.y - box.height/2.0
> >> return p
> >> To call this function, pass box as an argument and assign the result to
> a variable:
> >>>>> center =ind_center(box)
> >>>>> print_point(center)
> >> (50.0, 100.0)
> >>
> >>
> >> So i followed it but appearently not the good way.
> >>
> >> Roelof
> > There's a big difference between print_point() and print time().
> >
> > print_point() in your tutorial is a function, presumably defined
> > someplace else.
> >
> > You used print time(), (no underscore), which uses the print statement,
> > and tries to call a function called time().
> >
> > Since you defined time as an instance of your class, and didn't do
> > anything special, it's not callable.
> >
> > DaveA
> >
>
> Oke,
>
> I see it now.
> I have to us a function that i had to write a few questions before.
>
> Thanks everybody
>
> Roelof
>
>
>
> ------------------------------
>
> Message: 3
> Date: Fri, 24 Sep 2010 12:26:31 -0400 (EDT)
> From: kb1pkl at aim.com
> To: tutor at python.org
> Subject: Re: [Tutor] Plotting a Linear Equation
> Message-ID: <8CD2A1C6185AFCF-854-182 at webmail-m060.sysops.aol.com>
> Content-Type: text/plain; charset="utf-8"; format=flowed
>
>
>
>
> -----Original Message-----
> From: Greg <gregbair at gmail.com>
> To: tutor <tutor at python.org>
> Sent: Fri, Sep 24, 2010 3:29 am
> Subject: Re: [Tutor] Plotting a Linear Equation
>
>
> On Thu, Sep 23, 2010 at 10:51 PM, Corey Richardson <kb1pkl at aim.com>
> wrote:
>
> ?Hello tutors. Probably the wrong mailing list, but someone might know.
> I want to use matplotlib (or similar) to plot an equation in
> slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've
> read and tested, you can only plot with a series of points. I could
> make two points out of those manually, but I was wondering if anyone
> knew of an easier way. Thanks.
>
>
>
> You could just have your program compute the x- and y- intercepts, then
> plug them into matplotlib. ?Am I correct in that??
>
>
> --
> Greg Bair
> gregbair at gmail.com
> ______________________________________________________________________
> Yes, you are correct. That's what I planned on doing if I couldn't plug
> the equation right into matplotlib.
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Fri, 24 Sep 2010 19:58:44 +0200
> From: Norman Khine <norman at khine.net>
> To: Python tutor <tutor at python.org>
> Subject: Re: [Tutor] list.append(x) but at a specific 'i'
> Message-ID:
>        <AANLkTinq++Wr+N6FHtObjXs2AOOG8O1o4CK1NvUAzgts at mail.gmail.com<AANLkTinq%2B%2BWr%2BN6FHtObjXs2AOOG8O1o4CK1NvUAzgts at mail.gmail.com>
> >
> Content-Type: text/plain; charset=UTF-8
>
> On Wed, Sep 22, 2010 at 9:47 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> > On Wed, 22 Sep 2010 08:30:09 am Norman Khine wrote:
> >
> >> hello, how do i extend a python list but from a given [i],
> >
> > Do you mean to modify the list in place, like append() and extend() do,
> > or do you mean to create a new list, like + does?
> >
> >
> >> for example:
> >> >>> a = ['a', 'b', 'e']
> >> >>> b = ['c', 'd']
> >> >>>
> >> >>> a + b
> >>
> >> ['a', 'b', 'e', 'c', 'd']
> >>
> >>
> >> but i want to put the items of 'b' at [-2] for example.
> >
> > When you ask a question, it usually helps to show the output you *want*,
> > not the output you *don't want*, rather than to make assumptions about
> > what other people will understand.
> >
> > When you say that you want the items of b *at* -2, taken literally that
> > could mean:
> >
> >>>> a = ['a', 'b', 'e']
> >>>> b = ['c', 'd']
> >>>> a.insert(-2+1, b)
> >>>> print(a)
> > ['a', 'b', ['c', 'd'], 'e']
> >
> > Note that the items of b are kept as a single item, at the position you
> > ask for, and the index you pass to insert() is one beyond when you want
> > them to appear.
> >
> > To create a new list, instead of insert() use slicing:
> >
> >>>> a[:-2+1] + [b] + a[-2+1:]
> > ['a', 'b', ['c', 'd'], 'e']
> >
> >
> > If you want the items of b to *start* at -2, since there are exactly two
> > items, extend() will do the job for in-place modification, otherwise +.
> > But you already know that, because that was your example.
> >
> > If you want the items of b to *end* at -2, so that you get
> > ['a', 'b', 'c', 'd', 'e'] then you could use repeated insertions:
> >
> > for c in b:
> > ? ?a.insert(-2, c)
> >
> > but that will likely be slow for large lists. Better to use slicing. To
> > create a new list is just like the above, except you don't create a
> > temporary list-of-b first:
> >
> >>>> a[:-2+1] + b + a[-2+1:]
> > ['a', 'b', 'c', 'd', 'e']
> >
> >
> > To do it in place, assign to a slice:
> >
> >>>> a[-2:-2] = b
> >>>> print(a)
> > ['a', 'c', 'd', 'b', 'e']
>
> thanks for all the replies, and the detailed information
> >
> >
> >
> > --
> > Steven D'Aprano
> > _______________________________________________
> > Tutor maillist ?- ?Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>
> --
> ?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
> ?q s,??? ???
> %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
> chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )
>
>
> ------------------------------
>
> Message: 5
> Date: Sat, 25 Sep 2010 19:29:34 +1000
> From: Sayth Renshaw <flebber.crue at gmail.com>
> To: Tutor at python.org
> Subject: [Tutor] Python And reading the Web - Javascript
> Message-ID:
>        <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> Was hoping some could push me in the right direction about reading
> data from web pages and what modules to use. Is there support for
> reading if the page uses javascript?
>
> If you know any good links to tutorials for this it would be great. I
> was planning to use python 2.6 currently.
>
> I want to read some data from the web it will be text and numeric i
> was planning to export it to a database. I was thinking while I am
> learning maybe something simple like Sqlite or MySQL.
>
> I then want to read back data to perform sorting and some calculations on.
>
> Any ideas in general in how to do this appreciated. i don't mind
> reading so if you have some good links they are appreciated.
>
> Thank You
>
> Sayth
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 79, Issue 134
> **************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/4d00412d/attachment-0001.html>

From evert.rol at gmail.com  Sat Sep 25 17:37:50 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 25 Sep 2010 17:37:50 +0200
Subject: [Tutor] Tutor Digest, Vol 79, Issue 134
In-Reply-To: <AANLkTik+_9KwgW-UPPd_9CFWq44SO1Gq_02LNmD4P1rp@mail.gmail.com>
References: <mailman.15.1285408803.13622.tutor@python.org>
	<AANLkTik+_9KwgW-UPPd_9CFWq44SO1Gq_02LNmD4P1rp@mail.gmail.com>
Message-ID: <88A88944-977A-482A-9B5E-EBBE554FEDF0@gmail.com>

> I started seting up django. the only issue I am having is that all instructions seem to assume that I am on linux.Don't suppose there are any good instructions for those on a windows based system.

Firstly: please don't reply to an unrelated message, but start a new one (with a proper subject line). Especially a reply to a digest message contains a lot of unrelated info.
Secondly: there is a Django mailing list, which may be more helpful than a generic Python tutoring list.

That said: what's wrong with the Django installation notes: I see mentions of Windows there, not just Linux; does that not work? http://docs.djangoproject.com/en/1.2/topics/install/
Googling 'django windows install' also works. Eg, http://www.instantdjango.com/

Cheers,

  Evert


From bkjones at gmail.com  Sat Sep 25 18:36:40 2010
From: bkjones at gmail.com (Brian Jones)
Date: Sat, 25 Sep 2010 12:36:40 -0400
Subject: [Tutor] input and raw input
In-Reply-To: <C4714E5B-714B-4609-B902-EE8E14B4FBC0@gmail.com>
References: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
	<C4714E5B-714B-4609-B902-EE8E14B4FBC0@gmail.com>
Message-ID: <AANLkTi=hCOUo5M0Kz=+rHJfqOBtPMteoR5ic22FF9qpi@mail.gmail.com>

On Sat, Sep 25, 2010 at 9:40 AM, Evert Rol <evert.rol at gmail.com> wrote:

> > any one have an idea about how we can input many number in the one time
> and change it to list.
> > for example:
> >
> > a=input("Enter the number of your class in the school:")     # the number
> can be enter as: 12,13,14 or 12 13 14 with a space in between.
> >
> > now how I can put these numbers into list like b=[12,13,14] with len( a )
> =3
>
> A string has a method split(); that may help you.
> In your case, where you want either a space or a comma as a separator, it
> depends whether both can be used at the same time. If not, you can check for
> the occurrence of one or the other separator and run split() with the
> correct separator. If both can occur in the same line, you may want to use
> the regex module instead: re.split()
>

No need for the 're' module. Even in the case where both can be used
together, you can still just use string methods:

>>> s
'12, 13 14'
>>> s.replace(',', '').split(' ')
['12', '13', '14']




> hth,
>
>  Evert
>
>
> > I tried with that but it's working only for a numbers less than 10 ex.
> 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in
> example above.
> >
> > a=raw_input("Enter the number of your class in the school:")
> > m=[]
> >  for I range (len( a)):
> >     if a[I]==',':
> >         pass
> >     elif a[I]==' ':
> >         pass
> >     else:
> >         m.append(a[I])
> > m=map(float,m)
> > print m;print len( m )
> > >> [1,2,3]
> > >> 3
> >
> > looking forward to seeing your help,
> > regards,
> > Ahmed
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100925/75de2e3b/attachment.html>

From evert.rol at gmail.com  Sat Sep 25 19:14:31 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Sat, 25 Sep 2010 19:14:31 +0200
Subject: [Tutor] input and raw input
In-Reply-To: <AANLkTi=hCOUo5M0Kz=+rHJfqOBtPMteoR5ic22FF9qpi@mail.gmail.com>
References: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
	<C4714E5B-714B-4609-B902-EE8E14B4FBC0@gmail.com>
	<AANLkTi=hCOUo5M0Kz=+rHJfqOBtPMteoR5ic22FF9qpi@mail.gmail.com>
Message-ID: <08B5B5CC-8065-41E5-9C61-8CC3DB76516B@gmail.com>

> > any one have an idea about how we can input many number in the one time and change it to list.
> > for example:
> >
> > a=input("Enter the number of your class in the school:")     # the number can be enter as: 12,13,14 or 12 13 14 with a space in between.
> >
> > now how I can put these numbers into list like b=[12,13,14] with len( a ) =3
> 
> A string has a method split(); that may help you.
> In your case, where you want either a space or a comma as a separator, it depends whether both can be used at the same time. If not, you can check for the occurrence of one or the other separator and run split() with the correct separator. If both can occur in the same line, you may want to use the regex module instead: re.split()
> 
> No need for the 're' module. Even in the case where both can be used together, you can still just use string methods: 
> 
> >>> s
> '12, 13 14'
> >>> s.replace(',', '').split(' ')
> ['12', '13', '14']

Good point.
To be finicky, you'll probably want to replace ',' by ' ' and let split work on whitespace instead of a single space. In case of tabs or a 12,13,14 input.


> > I tried with that but it's working only for a numbers less than 10 ex. 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in example above.
> >
> > a=raw_input("Enter the number of your class in the school:")
> > m=[]
> >  for I range (len( a)):
> >     if a[I]==',':
> >         pass
> >     elif a[I]==' ':
> >         pass
> >     else:
> >         m.append(a[I])
> > m=map(float,m)
> > print m;print len( m )
> > >> [1,2,3]
> > >> 3
> >
> > looking forward to seeing your help,
> > regards,
> > Ahmed
> >
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> -- 
> Brian K. Jones
> My Blog          http://www.protocolostomy.com
> Follow me      http://twitter.com/bkjones


From __peter__ at web.de  Sat Sep 25 19:17:19 2010
From: __peter__ at web.de (Peter Otten)
Date: Sat, 25 Sep 2010 19:17:19 +0200
Subject: [Tutor] input and raw input
References: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
	<C4714E5B-714B-4609-B902-EE8E14B4FBC0@gmail.com>
	<AANLkTi=hCOUo5M0Kz=+rHJfqOBtPMteoR5ic22FF9qpi@mail.gmail.com>
Message-ID: <i7laqq$pu1$1@dough.gmane.org>

Brian Jones wrote:

> No need for the 're' module. Even in the case where both can be used
> together, you can still just use string methods:
> 
>>>> s
> '12, 13 14'
>>>> s.replace(',', '').split(' ')
> ['12', '13', '14']

I think to replace "," with " " and then split() without explicit separator 
is slightly more robust. Compare:
 
>>> s = "12,34, 56  789"
>>> s.replace(",", " ").split()
['12', '34', '56', '789']
>>> s.replace(",", "").split(" ")
['1234', '56', '', '789']

Peter


From rwobben at hotmail.com  Sat Sep 25 20:15:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 25 Sep 2010 18:15:03 +0000
Subject: [Tutor] class method problem
Message-ID: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>



Hello, 
 
I have this code:
 
class zoeken() :
    pass
    def __len__(self):
        return 0 
    def __str__(self):
        return test2
    def find(self, strng, ch, start, stop):
        index = start
        while index < len(strng) and index < stop:
            if strng[index] == ch:
                return index
            index += 1
            return -1
    

test = zoeken()
test.woord = "tamara"
test2 = zoeken.find(test, "a", 1,5)
print test(test2)
 
But now I get this message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in <module>
    test2 = zoeken.find(test, "a", 1,5)
TypeError: find() takes exactly 5 arguments (4 given)
 
I can do zoeken.find (test2,test, "a", 1,5) but then I get this message:
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in <module>
    zoeken.find( test2, test, "a", 1,5)
NameError: name 'test2' is not defined
 
 
Roelof
  		 	   		  

From rwobben at hotmail.com  Sat Sep 25 20:51:10 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 25 Sep 2010 18:51:10 +0000
Subject: [Tutor]  class method problem
In-Reply-To: <SNT118-W2515C56B1240D36CC5446AAE630@phx.gbl>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>,
	<AANLkTinfPYwtCrtFPQMSEsDEB0ABiG4wdf59jym=101x@mail.gmail.com>,
	<SNT118-W2515C56B1240D36CC5446AAE630@phx.gbl>
Message-ID: <SNT118-W21590BBDAE6B605566CB8EAE630@phx.gbl>



Hello,

Still the same errors

Roelof


> ----------------------------------------
>> Date: Sat, 25 Sep 2010 19:33:52 +0100
>> Subject: Re: [Tutor] class method problem
>> From: andrefsp at gmail.com
>> To: rwobben at hotmail.com
>>
>> Your method receives 4 arguments and you didn't define one default.
>> Try to do something like this:
>>
>> def find(self, strng=None, ch=None, start=None, stop=None):
>>
>> Or any other default values that matches your needs.
>>
>>
>>
>> On 25 September 2010 19:15, Roelof Wobben wrote:
>>>
>>>
>>> Hello,
>>>
>>> I have this code:
>>>
>>> class zoeken() :
>>> ? ?pass
>>> ? ?def __len__(self):
>>> ? ? ? ?return 0
>>> ? ?def __str__(self):
>>> ? ? ? ?return test2
>>> ? ?def find(self, strng, ch, start, stop):
>>> ? ? ? ?index = start
>>> ? ? ? ?while index < len(strng) and index < stop:
>>> ? ? ? ? ? ?if strng[index] == ch:
>>> ? ? ? ? ? ? ? ?return index
>>> ? ? ? ? ? ?index += 1
>>> ? ? ? ? ? ?return -1
>>>
>>>
>>> test = zoeken()
>>> test.woord = "tamara"
>>> test2 = zoeken.find(test, "a", 1,5)
>>> print test(test2)
>>>
>>> But now I get this message :
>>>
>>> Traceback (most recent call last):
>>> ?File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in
>>> ? ?test2 = zoeken.find(test, "a", 1,5)
>>> TypeError: find() takes exactly 5 arguments (4 given)
>>>
>>> I can do zoeken.find (test2,test, "a", 1,5) but then I get this message:
>>>
>>> Traceback (most recent call last):
>>> ?File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in
>>> ? ?zoeken.find( test2, test, "a", 1,5)
>>> NameError: name 'test2' is not defined
>>>
>>>
>>> Roelof
>>>
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>>
>> --
>> Andreh Palma 		 	   		  

From smokefloat at gmail.com  Sat Sep 25 21:03:40 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 25 Sep 2010 15:03:40 -0400
Subject: [Tutor] class method problem
In-Reply-To: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
Message-ID: <AANLkTikfttE3xMQmYuTnEB8xUBCV613fu2jbdzdZWV=A@mail.gmail.com>

This returns a if "a" in, or -1 if using "z":

class zoeken() :
	pass
	def __len__(self):
		return 0
	def __str__(self):
		return test2
	def find(self, strng, ch, start, stop):
		index = start
		while index < len(strng) and index < stop:
			if strng[index] == ch:
				return ch
			index += 1
			return -1


test = zoeken()
test.woord = "tamara"
stop = len(test.woord)
test2 = test.find(test.woord, "a", 1,stop)
print test2

David

From smokefloat at gmail.com  Sat Sep 25 21:18:43 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 25 Sep 2010 15:18:43 -0400
Subject: [Tutor] class method problem
In-Reply-To: <AANLkTikfttE3xMQmYuTnEB8xUBCV613fu2jbdzdZWV=A@mail.gmail.com>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<AANLkTikfttE3xMQmYuTnEB8xUBCV613fu2jbdzdZWV=A@mail.gmail.com>
Message-ID: <AANLkTikjXYZAOrUwn6sDoOJbJLx5Pv1+C37WELvo4yba@mail.gmail.com>

This is a little better, it returns a if "a" in, or None if using "z":

class zoeken() :
	pass
	def __len__(self):
		return 0
	def __str__(self):
		return test2
	def find(self, strng, ch, start, stop):
		index = start
		while index < len(strng) and index < stop:
			if strng[index] == ch:
				return ch
			index += 1

test = zoeken()
test.woord = raw_input('Enter string of letters to search: ' )
stop = len(test.woord)
search = raw_input('Enter character to find: ')
#print 'search =' ,search
test2 = test.find(test.woord, search, 1,stop)
print test2

Of course, there are other ways to accomplish this.

David

From smokefloat at gmail.com  Sun Sep 26 00:13:23 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sat, 25 Sep 2010 18:13:23 -0400
Subject: [Tutor] class method problem
In-Reply-To: <AANLkTikjXYZAOrUwn6sDoOJbJLx5Pv1+C37WELvo4yba@mail.gmail.com>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<AANLkTikfttE3xMQmYuTnEB8xUBCV613fu2jbdzdZWV=A@mail.gmail.com>
	<AANLkTikjXYZAOrUwn6sDoOJbJLx5Pv1+C37WELvo4yba@mail.gmail.com>
Message-ID: <AANLkTim0=0r=LDyw1C84Ebjv7L6TdYkdob8TNDriqggy@mail.gmail.com>

Since I had nothing else to do, but practice, this looks much better:

def find(word, search):
	if search in word:
		print True
	else:
		print False


word = raw_input('Enter string of letters to search: ' )
search = raw_input('Enter character to find: ')

find(word,search)

From steve at pearwood.info  Sun Sep 26 02:50:30 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 Sep 2010 10:50:30 +1000
Subject: [Tutor] class method problem
In-Reply-To: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
Message-ID: <201009261050.31802.steve@pearwood.info>

On Sun, 26 Sep 2010 04:15:03 am Roelof Wobben wrote:
> Hello,
>
> I have this code:
>
> class zoeken() :

It is traditional to name classes with an initial capital letter, so 
Zoeken would be better.

>     pass

What is the point of the "pass" statement there? That does nothing. Why 
did you put that there?

>     def __len__(self):
>         return 0
>     def __str__(self):
>         return test2

What is test2? It doesn't exist.

>     def find(self, strng, ch, start, stop):

Count the arguments: 5, including self. Remember that number. This is 
important later on.


>         index = start
>         while index < len(strng) and index < stop:
>             if strng[index] == ch:
>                 return index
>             index += 1
>             return -1

Watch the indentation. The "return -1" is *inside* the loop.

> test = zoeken()
> test.woord = "tamara"
> test2 = zoeken.find(test, "a", 1,5)
> print test(test2)
> ?
> But now I get this message :
>
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20,
> in <module> test2 = zoeken.find(test, "a", 1,5)
> TypeError: find() takes exactly 5 arguments (4 given)

Right. READ THE ERROR, don't just immediately cry for help. Being a 
programmer means you must have ATTENTION TO DETAIL -- the error tells 
you *exactly* what the problem is: the find() method takes five 
arguments, *including* self. You have only given four arguments:

find method expects:
1: self
2: strng
3: ch 
4: start
5: stop

find method actually gets 
1: test
2: "a"
3: 1
4: 5
5: ??????????????


> I can do zoeken.find (test2,test, "a", 1,5) but then I get this
> message:
>
> Traceback (most recent call last):
>   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20,
> in <module> zoeken.find( test2, test, "a", 1,5)
> NameError: name 'test2' is not defined

Exactly. That's because test2 does not exist.




-- 
Steven D'Aprano

From steve at pearwood.info  Sun Sep 26 03:16:13 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 Sep 2010 11:16:13 +1000
Subject: [Tutor] class method problem
In-Reply-To: <AANLkTim0=0r=LDyw1C84Ebjv7L6TdYkdob8TNDriqggy@mail.gmail.com>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<AANLkTikjXYZAOrUwn6sDoOJbJLx5Pv1+C37WELvo4yba@mail.gmail.com>
	<AANLkTim0=0r=LDyw1C84Ebjv7L6TdYkdob8TNDriqggy@mail.gmail.com>
Message-ID: <201009261116.13948.steve@pearwood.info>

On Sun, 26 Sep 2010 08:13:23 am David Hutto wrote:
> Since I had nothing else to do, but practice, this looks much better:
>
> def find(word, search):
> 	if search in word:
> 		print True
> 	else:
> 		print False


For some definition of "better".

If I called a function:

find("anti-disestablishmentarianism", "lish")

and got back an answer:

True

I'd feel ripped off and cheated. That would be like going to Google, 
typing in something into the search box, and Google comes back with:

    Yes, we found your terms on the Internet, but we won't tell you
    where. If you would like to find something else, we won't tell 
    you where that is either.

Aside from the name of the function, which is deceptive because it 
doesn't describe what the function does, the names of the arguments are 
also poor. The first argument is not necessarily a word. Nor is there 
any need for it to be -- it can be any text. The second argument is 
poorly described as "search" -- search is a verb. 

A better function signature might be:

def search(text, target):
    # Search for target in text and print whether it is found or not.

Even this is slightly misleading, because "text" doesn't need to be an 
actual string. It could be any sequence, such as a list. But this gives 
the *intention* of the function, which is to do text searches. So this 
is (in my opinion) an acceptable compromise between intention and 
generality.

Now on to the code itself. The body of the function is needlessly 
verbose. You say:

if search in word:
    print True
else:
    print False

This is so simple we can trace the entire function by hand. Say we call 
search("I like spam and eggs", "spam"):

(1) target in text? => True
(2) take the if branch
(3) print True

Now say we call find("I like spam and eggs", "cheese"):

(1) target in text? => False
(2) take the else branch
(3) print False

Can you see the common factor? The object which is printed is always 
precisely the same object generated by the `in` test. So we can 
simplify the body of the function:

def search(text, target):
    print target in text


But this is so simple, there's no point to wrapping it in a function!

Small functions that do one thing are good, up to a point, but when the 
function is so small that it is just as easy to include the body in the 
caller code, the function is pointless. It's not like "search(b, a)" is 
easier to write or remember than "print a in b" -- if anything the 
opposite is the case, because I would never remember which order to 
pass the arguments.



-- 
Steven D'Aprano

From rdmoores at gmail.com  Sun Sep 26 04:14:24 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 25 Sep 2010 19:14:24 -0700
Subject: [Tutor] How to start IPython in Windows
In-Reply-To: <AANLkTimQeQ4qh0Njw1zaCZgMM09Gs55vbwTOb01NjFZJ@mail.gmail.com>
References: <AANLkTimQeQ4qh0Njw1zaCZgMM09Gs55vbwTOb01NjFZJ@mail.gmail.com>
Message-ID: <AANLkTik3jCKCT=wcJTQbDkUcp55LCuaN0oYoM5qvhD8Z@mail.gmail.com>

(I posted this to the ipython-user list 11 hours ago, with no response
-- too dumb a question?)

64-bit Vista.

I've downloaded "A binary Windows installer (an executable setup
file)" from http://ipython.scipy.org/moin/Download , and run it.
IPython is now installed in my Python26/Lib/site-packages folder. I
also installed win64-unicode version of wxPython. I also have
winconsole.py.

Sorry for the dumb question, but how do I start IPython?

Dick Moores

From smokefloat at gmail.com  Sun Sep 26 06:12:35 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 26 Sep 2010 00:12:35 -0400
Subject: [Tutor] How to start IPython in Windows
In-Reply-To: <AANLkTik3jCKCT=wcJTQbDkUcp55LCuaN0oYoM5qvhD8Z@mail.gmail.com>
References: <AANLkTimQeQ4qh0Njw1zaCZgMM09Gs55vbwTOb01NjFZJ@mail.gmail.com>
	<AANLkTik3jCKCT=wcJTQbDkUcp55LCuaN0oYoM5qvhD8Z@mail.gmail.com>
Message-ID: <AANLkTinvsZgA7qL7i++poqe2DY1qRkx13WiwxksYWJak@mail.gmail.com>

IIRC, it's like idle, just run:
python C:\\Python\\Scripts\\ipython.py

From smokefloat at gmail.com  Sun Sep 26 06:26:25 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 26 Sep 2010 00:26:25 -0400
Subject: [Tutor] class method problem
In-Reply-To: <201009261116.13948.steve@pearwood.info>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<AANLkTikjXYZAOrUwn6sDoOJbJLx5Pv1+C37WELvo4yba@mail.gmail.com>
	<AANLkTim0=0r=LDyw1C84Ebjv7L6TdYkdob8TNDriqggy@mail.gmail.com>
	<201009261116.13948.steve@pearwood.info>
Message-ID: <AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>

On Sat, Sep 25, 2010 at 9:16 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 26 Sep 2010 08:13:23 am David Hutto wrote:
>> Since I had nothing else to do, but practice, this looks much better:
>>
>> def find(word, search):
>> ? ? ? if search in word:
>> ? ? ? ? ? ? ? print True
>> ? ? ? else:
>> ? ? ? ? ? ? ? print False
>
>
> For some definition of "better".
>
> If I called a function:
>
> find("anti-disestablishmentarianism", "lish")
>
> and got back an answer:
>
> True
>
> I'd feel ripped off and cheated. That would be like going to Google,
> typing in something into the search box, and Google comes back with:

OP wanted to find if a in b. Does my function do that?...Yep

>
> ? ?Yes, we found your terms on the Internet, but we won't tell you
> ? ?where. If you would like to find something else, we won't tell
> ? ?you where that is either.

It's not supposed to be a four line version of Google.

>
> Aside from the name of the function, which is deceptive because it
> doesn't describe what the function does, the names of the arguments are
> also poor. The first argument is not necessarily a word.

Badly named yes, but I know it just finds a string in a string

 Nor is there
> any need for it to be -- it can be any text. The second argument is
> poorly described as "search" -- search is a verb.
>
> A better function signature might be:
>
> def search(text, target):
> ? ?# Search for target in text and print whether it is found or not.
>
> Even this is slightly misleading, because "text" doesn't need to be an
> actual string. It could be any sequence, such as a list. But this gives
> the *intention* of the function, which is to do text searches. So this
> is (in my opinion) an acceptable compromise between intention and
> generality.

Semantics, are only important to those who didn't write it.

>
> Now on to the code itself. The body of the function is needlessly
> verbose. You say:
>
> if search in word:
> ? ?print True
> else:
> ? ?print False
>
> This is so simple we can trace the entire function by hand. Say we call
> search("I like spam and eggs", "spam"):
>
> (1) target in text? => True
> (2) take the if branch
> (3) print True
>
> Now say we call find("I like spam and eggs", "cheese"):
>
> (1) target in text? => False
> (2) take the else branch
> (3) print False
>
> Can you see the common factor? The object which is printed is always
> precisely the same object generated by the `in` test. So we can
> simplify the body of the function:
>
> def search(text, target):
> ? ?print target in text
>
>
> But this is so simple, there's no point to wrapping it in a function!
>
> Small functions that do one thing are good, up to a point, but when the
> function is so small that it is just as easy to include the body in the
> caller code, the function is pointless. It's not like "search(b, a)" is
> easier to write or remember than "print a in b" -- if anything the
> opposite is the case, because I would never remember which order to
> pass the arguments.

The reason I put it in a function, was the same reason the OP put it in a
class, to eventually expand on the initial program being created.(also
I had it in a snippets file, accompanied by an instance for it, a way
to conveniently call
it later if needed)

I do know I could have shortened it further, I'm not all omniscient
like yourself.

Breath deeply, and remember it's someone elses code who hasn't had
the same experience writing code that you have.

But thanks for pointing it out, I'll know to eliminate the excess in the
future, knowing that the all seeing steven is watching my every
function.

>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From rdmoores at gmail.com  Sun Sep 26 06:34:37 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 25 Sep 2010 21:34:37 -0700
Subject: [Tutor] How to start IPython in Windows
In-Reply-To: <AANLkTinvsZgA7qL7i++poqe2DY1qRkx13WiwxksYWJak@mail.gmail.com>
References: <AANLkTimQeQ4qh0Njw1zaCZgMM09Gs55vbwTOb01NjFZJ@mail.gmail.com>
	<AANLkTik3jCKCT=wcJTQbDkUcp55LCuaN0oYoM5qvhD8Z@mail.gmail.com>
	<AANLkTinvsZgA7qL7i++poqe2DY1qRkx13WiwxksYWJak@mail.gmail.com>
Message-ID: <AANLkTimFJZM61fTLoxWUus8-q3_iH2Z=bh1dFFUUcfoL@mail.gmail.com>

On Sat, Sep 25, 2010 at 21:12, David Hutto <smokefloat at gmail.com> wrote:
> IIRC, it's like idle, just run:
> python C:\\Python\\Scripts\\ipython.py

Yes! Thank you! Here what that got me:

=====================================================
C:\Python26\Scripts>ipython
**********************************************************************
Welcome to IPython. I will try to create a personal configuration directory
where you can customize many aspects of IPython's functionality in:

C:\Users\Dick\_ipython
Initializing from configuration:
C:\Python26\lib\site-packages\IPython\UserConfig

Successful installation!

Please read the sections 'Initial Configuration' and 'Quick Tips' in the
IPython manual (there are both HTML and PDF versions supplied with the
distribution) to make sure that your system environment is properly configured
to take advantage of IPython's features.

Important note: the configuration system has changed! The old system is
still in place, but its setting may be partly overridden by the settings in
"~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
if some of the new settings bother you.


Please press <RETURN> to start IPython.
**********************************************************************
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.

IPython 0.10 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]:
======================================================

Dick

From steve at pearwood.info  Sun Sep 26 09:14:49 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 26 Sep 2010 17:14:49 +1000
Subject: [Tutor] class method problem
In-Reply-To: <AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<201009261116.13948.steve@pearwood.info>
	<AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>
Message-ID: <201009261714.49330.steve@pearwood.info>

On Sun, 26 Sep 2010 02:26:25 pm David Hutto wrote:
> On Sat, Sep 25, 2010 at 9:16 PM, Steven D'Aprano <steve at pearwood.info> 
wrote:
> > On Sun, 26 Sep 2010 08:13:23 am David Hutto wrote:
> >> Since I had nothing else to do, but practice, this looks much
> >> better:
> >>
> >> def find(word, search):
> >> ? ? ? if search in word:
> >> ? ? ? ? ? ? ? print True
> >> ? ? ? else:
> >> ? ? ? ? ? ? ? print False
[...]
> OP wanted to find if a in b. Does my function do that?...Yep

I didn't say that the function did the wrong thing, I said the name was 
misleading for what it actually did.

Why didn't you call the function len(), or deleteItemsFromPage()? 
Because those names would be misleading, deceptive and silly. And so is 
calling a function find() when it does something completely different 
from the commonly understood meaning of the word "find".

When you find something, you know where it is afterwards. In the context 
of text searches, that means returning an offset to where the target is 
found, or something similar. That's what str.find() does, and regular 
expressions, and list.index(). Your "find" function is a membership 
test, which is what the `in` operator is for.




> > ? ?Yes, we found your terms on the Internet, but we won't tell you
> > ? ?where. If you would like to find something else, we won't tell
> > ? ?you where that is either.
>
> It's not supposed to be a four line version of Google.

I didn't say it was. I tried to inject a little humour into the email, 
but it clearly didn't work.


[...]
> > Even this is slightly misleading, because "text" doesn't need to be
> > an actual string. It could be any sequence, such as a list. But
> > this gives the *intention* of the function, which is to do text
> > searches. So this is (in my opinion) an acceptable compromise
> > between intention and generality.
>
> Semantics, are only important to those who didn't write it.

"Semantics" means "meaning". If you are trying to tell me that the 
meaning of programs -- their *purpose* -- is unimportant, that it 
doesn't matter what a function does, I'm afraid you'll have your work 
cut out to convince me.

The most important reader of your functions is... you. The function 
might be fresh in your mind *today*, but tomorrow? Next week? Six 
months from now when you discover a bug in your program and are trying 
to remember how it works so you can fix it?

Trust me, any non-trivial program that you don't just use once and throw 
away needs to be written with a careful eye to naming functions and 
arguments. The ideal is that you should never need to write 
documentation, because the functions and arguments document themselves. 
(This is an ideal that never quite works in practice, but we can at 
least *try*.)

An excellent piece of advice I've been given is to write your program's 
API -- the names of functions, the calling signatures, and so forth -- 
as if the next person to maintain that code will be a psychopath with a 
hair-trigger temper and a gun and who knows where you live. Since the 
next person to maintain it will likely be you, you will save *much* 
more time in the future by careful and consistent naming than it costs 
to think of those names right now.



-- 
Steven D'Aprano

From smokefloat at gmail.com  Sun Sep 26 20:32:41 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 26 Sep 2010 14:32:41 -0400
Subject: [Tutor] class method problem
In-Reply-To: <201009261714.49330.steve@pearwood.info>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<201009261116.13948.steve@pearwood.info>
	<AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>
	<201009261714.49330.steve@pearwood.info>
Message-ID: <AANLkTi=K3kSMWBLyyyoevjtJ_j71f_0d8s86p6-uG9cS@mail.gmail.com>

On Sun, Sep 26, 2010 at 3:14 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sun, 26 Sep 2010 02:26:25 pm David Hutto wrote:
>> On Sat, Sep 25, 2010 at 9:16 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>> > On Sun, 26 Sep 2010 08:13:23 am David Hutto wrote:
>> >> Since I had nothing else to do, but practice, this looks much
>> >> better:
>> >>
>> >> def find(word, search):
>> >> ? ? ? if search in word:
>> >> ? ? ? ? ? ? ? print True
>> >> ? ? ? else:
>> >> ? ? ? ? ? ? ? print False
> [...]
>> OP wanted to find if a in b. Does my function do that?...Yep
>
> I didn't say that the function did the wrong thing, I said the name was
> misleading for what it actually did.
>
> Why didn't you call the function len(), or deleteItemsFromPage()?
> Because those names would be misleading, deceptive and silly. And so is
> calling a function find() when it does something completely different
> from the commonly understood meaning of the word "find".



>
> When you find something, you know where it is afterwards.

Find to me, in the since of the OP's question means a hit. It was found in
the furtherence into where, is up to the OP and their next question on the list
that says now that I know it's there, where is it?

In the context
> of text searches, that means returning an offset to where the target is
> found, or something similar. That's what str.find() does, and regular
> expressions, and list.index(). Your "find" function is a membership
> test, which is what the `in` operator is for.

And I'm sure that with google, and my trust Building Skills in Python
Manual at my side, I would have found those string/list functions, and overtime
so will the OP, just as did at one point Mr. Miyagi.

>
>
>
>
>> > ? ?Yes, we found your terms on the Internet, but we won't tell you
>> > ? ?where. If you would like to find something else, we won't tell
>> > ? ?you where that is either.
>>
>> It's not supposed to be a four line version of Google.
>
> I didn't say it was. I tried to inject a little humour into the email,
> but it clearly didn't work.

It did work, so I injected a little sarcasm back.

>
>
> [...]
>> > Even this is slightly misleading, because "text" doesn't need to be
>> > an actual string. It could be any sequence, such as a list.

I know this from a brief exercise I was working on before, but when
learning, you can
just give everything at once and expect it to be absorbed, you have to
practive with the different types you can manipulate, but knowing what
they are is helpful.

But
>> > this gives the *intention* of the function, which is to do text
>> > searches. So this is (in my opinion) an acceptable compromise
>> > between intention and generality.
>>
>> Semantics, are only important to those who didn't write it.
>
> "Semantics" means "meaning". If you are trying to tell me that the
> meaning of programs -- their *purpose* -- is unimportant, that it
> doesn't matter what a function does, I'm afraid you'll have your work
> cut out to convince me.

I meant if it's a small function that you might use once in a blue moon,
and you know what it does for you, and since you wrote this small
function, you're able to
tell exactly what it does, and then it does this task as expected for
you, then ok.

If I was working with someone else on it, then I'm sure, they would suggest,
that we use overlapping terminology we could agree on for the code at hand.
(it would probably require a meeting or something.)


>
> The most important reader of your functions is... you. The function
> might be fresh in your mind *today*, but tomorrow? Next week? Six
> months from now when you discover a bug in your program and are trying
> to remember how it works so you can fix it?

It's five lines long.

>
> Trust me, any non-trivial program that you don't just use once and throw
> away needs to be written with a careful eye to naming functions and
> arguments. The ideal is that you should never need to write
> documentation, because the functions and arguments document themselves.
> (This is an ideal that never quite works in practice, but we can at
> least *try*.)

and I do.

>
> An excellent piece of advice I've been given is to write your program's
> API -- the names of functions, the calling signatures, and so forth --
> as if the next person to maintain that code will be a psychopath with a
> hair-trigger temper and a gun and who knows where you live. Since the
> next person to maintain it will likely be you, you will save *much*
> more time in the future by careful and consistent naming than it costs
> to think of those names right now.

Your comments are in the suggestion box, and you'll be happy to know, I even
take advice from my critics...when it suits me.

>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

David Hutto

From wallenpb at gmail.com  Sun Sep 26 22:01:35 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 26 Sep 2010 15:01:35 -0500
Subject: [Tutor] a logic problem in an if statement
Message-ID: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>

Ok, I am have a problem with some logic in a piece of code I am working
on.   I have tinkered with it for hours and am stumped.  Pretty sure I have
lost sight of the forest for the trees...

The purpose of this code is to take the coordinates on screen of the mouse
at the time of two mouse clicks, store that information and then make some
decisions based on that.  No matter what I do, I am finding that the second
if statement block falls through to the last option.   In the if I am try to
say "if the mouse click cursor position with the first click was in the
upper half of the screen (i.e. < height/2) and the second mouse click was in
the lower half of the screen (i.e. > height/2)".  elif "both clicks happened
in the upper half of the screen"   else "assume the clicks occurred in the
lower half of the screen".  The second case and last case always seem to
work out ok.  The first case falls through to the final case even though the
coordinates were appropriate for the first case logic.

Any thoughts how I am going wrong here?

--Bill

#This captures the coordinates the two mouse clicks, successfully.
mouse_pos is in the form (x,y), such as (204,102).
if mouse_pressed == (1,0,0) and first_click == False:
        first_click = True
        mouse_pos1 = mouse_pos
elif mouse_pressed == (1,0,0) and first_click == True:
        mouse_pos2 = mouse_pos

#This is the decisional logic based on the mouse click coordinates,
previously captured.
#This first case fails although the print statement give me feedback on the
coordinates,
#that suggest it should have worked.  It always falls through to the final
else.
if mouse_pos[1] < height/2 and mouse_pos2[1] > height/2:
    print("use 0 for new yadjust")
    print(height/2,"did first one", mouse_pos1[1], mouse_pos2[1])

#This case always works.
elif mouse_pos[1] < height/2 and mouse_pos2[1] < height/2:
    print("use {0} for new
yadjust".format(1.05+(1-((height/2)-mouse_pos1[1])/(height/2))))
    print(height/2,"did 2nd one", mouse_pos1[1], mouse_pos2[1])

#this case always works.
else:
    print("use {0} for new
yadjust".format(-1.07+(1+((height/2)-mouse_pos2[1])/(height/2))))
    print(height/2,"did last one", mouse_pos1[1], mouse_pos2[1])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/cfe64e1f/attachment.html>

From marc.tompkins at gmail.com  Sun Sep 26 22:12:36 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 Sep 2010 13:12:36 -0700
Subject: [Tutor] a logic problem in an if statement
In-Reply-To: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
References: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
Message-ID: <AANLkTi=X9PYbwfhv120Z-9pSNj+ALNFZcuYHFOnh-4=d@mail.gmail.com>

On Sun, Sep 26, 2010 at 1:01 PM, Bill Allen <wallenpb at gmail.com> wrote:

>
> Any thoughts how I am going wrong here?
>
> Looks like you've got two different names for the first mouse click...

        mouse_pos1 = mouse_pos
>

but

> if mouse_pos[1] < height/2 and mouse_pos2[1] > height/2:
>


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/31c2dd01/attachment.html>

From ranceh at gmail.com  Sun Sep 26 22:16:34 2010
From: ranceh at gmail.com (Rance Hall)
Date: Sun, 26 Sep 2010 15:16:34 -0500
Subject: [Tutor] generating formatted output
Message-ID: <AANLkTimkQDetvCa9FfXRUfHcesVMBVNeqimHP_p+mmdb@mail.gmail.com>

My app will be printing a series of documents that are the same each
time the doc is printed with the exception of the variables.  Sort of
a MailMerge if you will.

It seems to me that the easiest approach is to create a series of text
files with the layout and placeholders I need (again much like
MailMerge)

And then do something like this:

    file = open(fileName, "r") #Opens the file in read-mode
    text = file.read() #Reads the file and assigns the value to a variable
    file.close() #Closes the file (read session)
    text = text.replace(sourceText, replaceText)  #there will be a
series of these.
    file = open(fileName2, "w") #Opens a new file in write-mode.
    file.write(text)
    file.close() #Closes the file (write session)

Then you can print the file or email it or whatever you need to do.

There wont be too many of these replacements (think invoice template
with substitutes for customer information and a billing detail
section.)

So my question is about the approach.  Is this reasonable? Is there a
better way to do this?

From wallenpb at gmail.com  Sun Sep 26 22:36:56 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 26 Sep 2010 15:36:56 -0500
Subject: [Tutor] a logic problem in an if statement
In-Reply-To: <AANLkTi=X9PYbwfhv120Z-9pSNj+ALNFZcuYHFOnh-4=d@mail.gmail.com>
References: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
	<AANLkTi=X9PYbwfhv120Z-9pSNj+ALNFZcuYHFOnh-4=d@mail.gmail.com>
Message-ID: <AANLkTim_-FmhNJvoNWCAU_Kw8daODJ0pvjpjtiqJvvdj@mail.gmail.com>

On Sun, Sep 26, 2010 at 3:12 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:

> On Sun, Sep 26, 2010 at 1:01 PM, Bill Allen <wallenpb at gmail.com> wrote:
>
>>
>> Any thoughts how I am going wrong here?
>>
>> Looks like you've got two different names for the first mouse click...
>
>         mouse_pos1 = mouse_pos
>>
>
> but
>
> if mouse_pos[1] < height/2 and mouse_pos2[1] > height/2:
>>
>
>
> Bingo!  Yes, that's the problem.  Should have  been if mouse_pos1[1] <
height/2 and mouse_pos2[1] > height/2:  rather than if mouse_pos[1] <
height/2 and mouse_pos2[1] > height/2:

That was basically a typo to which I had become completely blind.  I did it
in the second case as well, but it did not affect the result in that case,
making it even harder for me to spot.

I hate it when I do something like that!    A combination of poor choice of
names for the variables and programming tunnel vision....

Many thanks,
Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/e2a4c3e3/attachment-0001.html>

From marc.tompkins at gmail.com  Sun Sep 26 22:52:32 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 Sep 2010 13:52:32 -0700
Subject: [Tutor] a logic problem in an if statement
In-Reply-To: <AANLkTim_-FmhNJvoNWCAU_Kw8daODJ0pvjpjtiqJvvdj@mail.gmail.com>
References: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
	<AANLkTi=X9PYbwfhv120Z-9pSNj+ALNFZcuYHFOnh-4=d@mail.gmail.com>
	<AANLkTim_-FmhNJvoNWCAU_Kw8daODJ0pvjpjtiqJvvdj@mail.gmail.com>
Message-ID: <AANLkTi=QkBBipCGW0ba1DhbKrbOPD2vMNQ-FcpVKSxd+@mail.gmail.com>

On Sun, Sep 26, 2010 at 1:36 PM, Bill Allen <wallenpb at gmail.com> wrote:

> I hate it when I do something like that!    A combination of poor choice of
> names for the variables and programming tunnel vision....
>

Been there, done that!
-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/573e81a8/attachment.html>

From wallenpb at gmail.com  Sun Sep 26 23:19:23 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 26 Sep 2010 16:19:23 -0500
Subject: [Tutor] Python And reading the Web - Javascript
In-Reply-To: <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J@mail.gmail.com>
References: <AANLkTinM5XOc8riMeoGF6eLqg5PGxW-e4fDpEy0evg3J@mail.gmail.com>
Message-ID: <AANLkTimv0S7Eu4cWEyKWCMn9n8h+L32s_50ky7hkxY=d@mail.gmail.com>

On Sat, Sep 25, 2010 at 4:29 AM, Sayth Renshaw <flebber.crue at gmail.com>wrote:

> I want to read some data from the web it will be text and numeric i
> was planning to export it to a database. I was thinking while I am
> learning maybe something simple like Sqlite or MySQL.
>
> I then want to read back data to perform sorting and some calculations on.
>
> This might be a good starting place for you.

http://diveintopython.org/html_processing/extracting_data.html

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/ec31e4fa/attachment.html>

From hugo.yoshi at gmail.com  Sun Sep 26 23:21:30 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Sun, 26 Sep 2010 23:21:30 +0200
Subject: [Tutor] generating formatted output
In-Reply-To: <AANLkTimkQDetvCa9FfXRUfHcesVMBVNeqimHP_p+mmdb@mail.gmail.com>
References: <AANLkTimkQDetvCa9FfXRUfHcesVMBVNeqimHP_p+mmdb@mail.gmail.com>
Message-ID: <AANLkTi=7mNesuMQOA7C9Lbxj0phZLepeTRrm4VmW+U3t@mail.gmail.com>

On Sun, Sep 26, 2010 at 10:16 PM, Rance Hall <ranceh at gmail.com> wrote:
> My app will be printing a series of documents that are the same each
> time the doc is printed with the exception of the variables. ?Sort of
> a MailMerge if you will.
>
> It seems to me that the easiest approach is to create a series of text
> files with the layout and placeholders I need (again much like
> MailMerge)
>
> And then do something like this:
>
> ? ?file = open(fileName, "r") #Opens the file in read-mode
> ? ?text = file.read() #Reads the file and assigns the value to a variable
> ? ?file.close() #Closes the file (read session)
> ? ?text = text.replace(sourceText, replaceText) ?#there will be a
> series of these.
> ? ?file = open(fileName2, "w") #Opens a new file in write-mode.
> ? ?file.write(text)
> ? ?file.close() #Closes the file (write session)
>
> Then you can print the file or email it or whatever you need to do.
>
> There wont be too many of these replacements (think invoice template
> with substitutes for customer information and a billing detail
> section.)
>
> So my question is about the approach. ?Is this reasonable? Is there a
> better way to do this?
>

I would suggest you take a look at string.Template or the str.format
method. It may be somewhat simpler than doing a whole lot of replaces,
perhaps faster as well.

http://docs.python.org/library/string.html#template-strings
http://docs.python.org/library/stdtypes.html#str.format

Hugo

From bill.debroglie at gmail.com  Sun Sep 26 23:55:40 2010
From: bill.debroglie at gmail.com (Bill DeBroglie)
Date: Sun, 26 Sep 2010 17:55:40 -0400
Subject: [Tutor] Issues In Terminal
Message-ID: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>

Hello all,

Totally new to this stuff and community so I very much appreciate the  
help and apologize in advance for asking what might be a stupid  
question... Oh, and I'm new to the lingo too!!

I'm having issues running Python in Terminal. When I run code through  
the interpreter I get:

	Python 2.6.5 (r236:73959, Mar 24 2010, 01:32:55)
	[GCC 4.0.1 (Apple Inc. build 5943)] on darwin
	Type "help", "copyright", "credits" or "license" for more information.
	>>> print("Hello World")
	Hello World

Which is great, but when I try and run the same code in the Terminal  
by calling a program I've written (print("hello world") again) I get  
the following:

	matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
	./chapter_2.py: line 4: syntax error near unexpected token `"Hello  
World"'
	./chapter_2.py: line 4: `print("Hello World")'

I'm using a Mac OS X 10.5.8. I had previously downloaded Python 2.6.5  
AND 3.1 and had them both on this computer simultaneously but was  
having trouble with 3.1 crashing. I have since put both in the trash  
but obviously still have 2.6.5 on my system, I assume that was the  
version pre-installed on this Mac.

Any guidance at all would be much appreciated-- I'm totally lost and  
have spent hours trying to figure this out.

bdb

From smokefloat at gmail.com  Mon Sep 27 00:03:49 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 26 Sep 2010 18:03:49 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
Message-ID: <AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>

On Sun, Sep 26, 2010 at 5:55 PM, Bill DeBroglie
<bill.debroglie at gmail.com> wrote:
> Hello all,
>
> Totally new to this stuff and community so I very much appreciate the help
> and apologize in advance for asking what might be a stupid question... Oh,
> and I'm new to the lingo too!!
>
> I'm having issues running Python in Terminal. When I run code through the
> interpreter I get:
>
> ? ? ? ?Python 2.6.5 (r236:73959, Mar 24 2010, 01:32:55)
> ? ? ? ?[GCC 4.0.1 (Apple Inc. build 5943)] on darwin
> ? ? ? ?Type "help", "copyright", "credits" or "license" for more
> information.
> ? ? ? ?>>> print("Hello World")
> ? ? ? ?Hello World
>
> Which is great, but when I try and run the same code in the Terminal by
> calling a program I've written (print("hello world") again) I get the
> following:
>
> ? ? ? ?matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
> ? ? ? ?./chapter_2.py: line 4: syntax error near unexpected token `"Hello
> World"'
> ? ? ? ?./chapter_2.py: line 4: `print("Hello World")'

Pretty sure it's the parentheses, but I'm not an expert. In python 3 you use
print(), in 2.6 you either use import from __futur__ or print "string here".

>
> I'm using a Mac OS X 10.5.8. I had previously downloaded Python 2.6.5 AND
> 3.1 and had them both on this computer simultaneously but was having trouble
> with 3.1 crashing. I have since put both in the trash but obviously still
> have 2.6.5 on my system, I assume that was the version pre-installed on this
> Mac.
>
> Any guidance at all would be much appreciated-- I'm totally lost and have
> spent hours trying to figure this out.
>
> bdb
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From smokefloat at gmail.com  Mon Sep 27 00:04:59 2010
From: smokefloat at gmail.com (David Hutto)
Date: Sun, 26 Sep 2010 18:04:59 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>
Message-ID: <AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>

On Sun, Sep 26, 2010 at 6:03 PM, David Hutto <smokefloat at gmail.com> wrote:
> On Sun, Sep 26, 2010 at 5:55 PM, Bill DeBroglie
> <bill.debroglie at gmail.com> wrote:
>> Hello all,
>>
>> Totally new to this stuff and community so I very much appreciate the help
>> and apologize in advance for asking what might be a stupid question... Oh,
>> and I'm new to the lingo too!!
>>
>> I'm having issues running Python in Terminal. When I run code through the
>> interpreter I get:
>>
>> ? ? ? ?Python 2.6.5 (r236:73959, Mar 24 2010, 01:32:55)
>> ? ? ? ?[GCC 4.0.1 (Apple Inc. build 5943)] on darwin
>> ? ? ? ?Type "help", "copyright", "credits" or "license" for more
>> information.
>> ? ? ? ?>>> print("Hello World")
>> ? ? ? ?Hello World
>>
>> Which is great, but when I try and run the same code in the Terminal by
>> calling a program I've written (print("hello world") again) I get the
>> following:
>>
>> ? ? ? ?matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
>> ? ? ? ?./chapter_2.py: line 4: syntax error near unexpected token `"Hello
>> World"'
>> ? ? ? ?./chapter_2.py: line 4: `print("Hello World")'
>
> Pretty sure it's the parentheses, but I'm not an expert. In python 3 you use
> print(), in 2.6 you either use import from __futur__ or print "string here".

I mean __future__ .
>
>>
>> I'm using a Mac OS X 10.5.8. I had previously downloaded Python 2.6.5 AND
>> 3.1 and had them both on this computer simultaneously but was having trouble
>> with 3.1 crashing. I have since put both in the trash but obviously still
>> have 2.6.5 on my system, I assume that was the version pre-installed on this
>> Mac.
>>
>> Any guidance at all would be much appreciated-- I'm totally lost and have
>> spent hours trying to figure this out.
>>
>> bdb
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>

From marc.tompkins at gmail.com  Mon Sep 27 00:06:04 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 Sep 2010 15:06:04 -0700
Subject: [Tutor] Issues In Terminal
In-Reply-To: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
Message-ID: <AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>

On Sun, Sep 26, 2010 at 2:55 PM, Bill DeBroglie <bill.debroglie at gmail.com>wrote:

> Which is great, but when I try and run the same code in the Terminal by
> calling a program I've written (print("hello world") again) I get the
> following:
>
>        matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
>        ./chapter_2.py: line 4: syntax error near unexpected token `"Hello
> World"'
>        ./chapter_2.py: line 4: `print("Hello World")'
>
> I'm using a Mac OS X 10.5.8. I had previously downloaded Python 2.6.5 AND
> 3.1 and had them both on this computer simultaneously but was having trouble
> with 3.1 crashing. I have since put both in the trash but obviously still
> have 2.6.5 on my system, I assume that was the version pre-installed on this
> Mac.
>


I think that's a shell issue, not specifically a Python issue.  You need to
include a line at the top of the script to tell the OS how to find the
Python interpreter.  Try adding this line at the beginning:

> #!/usr/bin/env python
>
> Your default Python install probably is NOT installed at /usr/bin/python,
but there should be a symbolic link there that points to the actual
location.  If not, you'll need to adjust things a bit.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/eabbcea7/attachment.html>

From steve at pearwood.info  Mon Sep 27 00:12:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 27 Sep 2010 08:12:15 +1000
Subject: [Tutor] a logic problem in an if statement
In-Reply-To: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
References: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
Message-ID: <201009270812.16338.steve@pearwood.info>

On Mon, 27 Sep 2010 06:01:35 am Bill Allen wrote:

> #This captures the coordinates the two mouse clicks, successfully.
> mouse_pos is in the form (x,y), such as (204,102).
> if mouse_pressed == (1,0,0) and first_click == False:
>         first_click = True
>         mouse_pos1 = mouse_pos
> elif mouse_pressed == (1,0,0) and first_click == True:
>         mouse_pos2 = mouse_pos


You don't actually tell us what mouse_pressed is, I presume (1, 0, 0) 
has some significance. But you check its value twice:

if mouse_pressed = (1, 0, 0) and something-else:
    ...
elif mouse_pressed = (1, 0, 0) and the opposite of something-else:
    ...


That is best written as a single test of mouse_pressed, followed by an 
if-else:

if mouse_pressed = (1, 0, 0):
    if something-else:
        ...
    else:
        ...


What should "something-else" be? Your tests are written as:

first_click == False
first_click == True

But both of them return True or False themselves, so you might as well 
write:

(first_click == True) == True
((first_click == True) == True) == True
(((first_click == True) == True) == True) == True
# Help, help, when do I stop???

Of course nobody would bother with the extra tests, because they're 
redundant. But even doing *one* test is likewise redundant -- the place 
to stop is before you even start! Since first_click is already either 
True or False, all you need is to look at it directly:

if mouse_pressed == (1,0,0):
    if first_click:
        mouse_pos2 = mouse_pos
    else:
        first_click = True
        mouse_pos2 = mouse_pos


I'm not entirely sure about the logic with first_click. It seems to me 
that once it becomes True, it will always stay True, and if it becomes 
False, it will immediately be set to True. But perhaps you have some 
other code elsewhere that handles setting it to False.



> #This is the decisional logic based on the mouse click coordinates,
> previously captured.
> #This first case fails although the print statement give me feedback
> on the coordinates,
> #that suggest it should have worked.  It always falls through to the
> final else.
> if mouse_pos[1] < height/2 and mouse_pos2[1] > height/2:
[...]

I'm going to suggest another approach here. Since you only care whether 
the clicks are in the top or bottom half of the screen, let's make that 
explicit:

click_in_bottom_half1 = mouse_pos[1] < height/2
click_in_bottom_half2 = mouse_pos2[1] < height/2

Now your decision logic becomes simple, and obvious. It documents 
itself:

if click_in_bottom_half1 and click_in_bottom_half2:
    print "Both clicks in bottom half of screen"
elif click_in_bottom_half1:
    print "The first click was in the bottom half."
    print "The second click was in the top half."
elif click_in_bottom_half2:
    print "The first click was in the top half."
    print "The second click was in the bottom half."
else:
    print "Both clicks in top half of screen"



-- 
Steven D'Aprano

From marc.tompkins at gmail.com  Mon Sep 27 00:18:30 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 Sep 2010 15:18:30 -0700
Subject: [Tutor] Issues In Terminal
In-Reply-To: <AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>
	<AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>
Message-ID: <AANLkTimh26yyeLLRkoru9Nh=cOQv5eAZ905AsZVFnWVa@mail.gmail.com>

On Sun, Sep 26, 2010 at 3:04 PM, David Hutto <smokefloat at gmail.com> wrote:

> > Pretty sure it's the parentheses, but I'm not an expert. In python 3 you
> use
> > print(), in 2.6 you either use import from __futur__ or print "string
> here".
>
> I mean __future__ .
>

The parentheses are optional in 2.6, mandatory in 3.  In 2.6, print and
print() are alternate ways to invoke the print statement; in 3 the print
statement has been replaced by the print() function.  If you want to use the
function instead of the statement, you must do this:

from __future__ import print_function

 but I'm pretty sure that's not the OP's issue.


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/a78b7471/attachment.html>

From steve at pearwood.info  Mon Sep 27 00:18:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 27 Sep 2010 08:18:56 +1000
Subject: [Tutor] Issues In Terminal
In-Reply-To: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
Message-ID: <201009270818.57208.steve@pearwood.info>

On Mon, 27 Sep 2010 07:55:40 am Bill DeBroglie wrote:
[...]
> Which is great, but when I try and run the same code in the Terminal
> by calling a program I've written (print("hello world") again) I get
> the following:

How do you call the program?

At the shell prompt, if you call:

python name_of_my_program.py

does it work?

Looking at the error you get, it looks like OS-X is treating the program 
as a shell script, not a Python script:

> 	matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
> 	./chapter_2.py: line 4: syntax error near unexpected token `"Hello
> World"'
> 	./chapter_2.py: line 4: `print("Hello World")'

That's not a Python error message, so it's probably a shell error. You 
need to teach the shell how to treat it, either by explicitly calling 
python, as above, or by inserting a "hash-bang" line at the very top of 
the script:

#!/usr/bin/env python


should do it.



-- 
Steven D'Aprano

From bill.debroglie at gmail.com  Mon Sep 27 00:24:07 2010
From: bill.debroglie at gmail.com (Bill DeBroglie)
Date: Sun, 26 Sep 2010 18:24:07 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>
Message-ID: <9DDBC030-A095-4584-9DB8-5F7805010876@gmail.com>


On Sep 26, 2010, at 6:06 PM, Marc Tompkins wrote:

> On Sun, Sep 26, 2010 at 2:55 PM, Bill DeBroglie <bill.debroglie at gmail.com 
> > wrote:
> Which is great, but when I try and run the same code in the Terminal  
> by calling a program I've written (print("hello world") again) I get  
> the following:
>
>        matthews-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
>        ./chapter_2.py: line 4: syntax error near unexpected token  
> `"Hello World"'
>        ./chapter_2.py: line 4: `print("Hello World")'
>
> I'm using a Mac OS X 10.5.8. I had previously downloaded Python  
> 2.6.5 AND 3.1 and had them both on this computer simultaneously but  
> was having trouble with 3.1 crashing. I have since put both in the  
> trash but obviously still have 2.6.5 on my system, I assume that was  
> the version pre-installed on this Mac.
>
>
> I think that's a shell issue, not specifically a Python issue.  You  
> need to include a line at the top of the script to tell the OS how  
> to find the Python interpreter.  Try adding this line at the  
> beginning:
> #!/usr/bin/env python
Is this what you mean?

	matthew-parrillas-macbook:Dawson_Book matthewparrilla$ #!/usr/bin/env  
python
	matthew-parrillas-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
	./chapter_2.py: line 1: syntax error near unexpected token `"Hello  
World"'
	./chapter_2.py: line 1: `print("Hello World")'

If so, obviously still no dice.

> Your default Python install probably is NOT installed at /usr/bin/ 
> python, but there should be a symbolic link there that points to the  
> actual location.  If not, you'll need to adjust things a bit.
>
> -- 
> www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/a2015155/attachment-0001.html>

From bill.debroglie at gmail.com  Mon Sep 27 00:25:11 2010
From: bill.debroglie at gmail.com (Bill DeBroglie)
Date: Sun, 26 Sep 2010 18:25:11 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <AANLkTimh26yyeLLRkoru9Nh=cOQv5eAZ905AsZVFnWVa@mail.gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>
	<AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>
	<AANLkTimh26yyeLLRkoru9Nh=cOQv5eAZ905AsZVFnWVa@mail.gmail.com>
Message-ID: <7A1CC1A9-877D-424C-B199-F341075A8760@gmail.com>


On Sep 26, 2010, at 6:18 PM, Marc Tompkins wrote:

> On Sun, Sep 26, 2010 at 3:04 PM, David Hutto <smokefloat at gmail.com>  
> wrote:
> > Pretty sure it's the parentheses, but I'm not an expert. In python  
> 3 you use
> > print(), in 2.6 you either use import from __futur__ or print  
> "string here".
>
> I mean __future__ .
>
> The parentheses are optional in 2.6, mandatory in 3.  In 2.6, print  
> and print() are alternate ways to invoke the print statement; in 3  
> the print statement has been replaced by the print() function.  If  
> you want to use the function instead of the statement, you must do  
> this:
> from __future__ import print_function
> but I'm pretty sure that's not the OP's issue.
>

Yes, not a parenthesis issue (happens whether I use them or not, I've  
tried both ways).

> -- 
> www.fsrtechnologies.com

By the way guys, thank you so much for the help. I'm sort of learning  
this on my own and don't know where to go when I hit a wall like this...

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/d5ea38b6/attachment.html>

From marc.tompkins at gmail.com  Mon Sep 27 00:29:48 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sun, 26 Sep 2010 15:29:48 -0700
Subject: [Tutor] Issues In Terminal
In-Reply-To: <9DDBC030-A095-4584-9DB8-5F7805010876@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>
	<9DDBC030-A095-4584-9DB8-5F7805010876@gmail.com>
Message-ID: <AANLkTimP9TMWNMcCO4VJKisQH=q-ie4JTyH0vLYvmP7j@mail.gmail.com>

On Sun, Sep 26, 2010 at 3:24 PM, Bill DeBroglie <bill.debroglie at gmail.com>wrote:

>
> Is this what you mean?
>
> matthew-parrillas-macbook:Dawson_Book matthewparrilla$ #!/usr/bin/env
> python
> matthew-parrillas-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
> ./chapter_2.py: line 1: syntax error near unexpected token `"Hello World"'
> ./chapter_2.py: line 1: `print("Hello World")'
>
> If so, obviously still no dice.
>
> No, I meant that you should edit your .py file and add

> #!/usr/bin/env python
>
as the first line, THEN try to run it.

Right now what's happening is that you're handing a line of Python script to
the shell and asking it to run it; the shell is telling you (oh-so-politely)
"what the hell is this?"  You need to give it a clue.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/52c3da02/attachment.html>

From wallenpb at gmail.com  Mon Sep 27 00:30:20 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 26 Sep 2010 17:30:20 -0500
Subject: [Tutor] generating formatted output
In-Reply-To: <AANLkTi=7mNesuMQOA7C9Lbxj0phZLepeTRrm4VmW+U3t@mail.gmail.com>
References: <AANLkTimkQDetvCa9FfXRUfHcesVMBVNeqimHP_p+mmdb@mail.gmail.com>
	<AANLkTi=7mNesuMQOA7C9Lbxj0phZLepeTRrm4VmW+U3t@mail.gmail.com>
Message-ID: <AANLkTi=nQSe_AzuQ7kDNQEO=uMUJ-EtaYowMoG4ehCP_@mail.gmail.com>

On Sun, Sep 26, 2010 at 4:21 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:

> On Sun, Sep 26, 2010 at 10:16 PM, Rance Hall <ranceh at gmail.com> wrote:
> > My app will be printing a series of documents that are the same each
> > time the doc is printed with the exception of the variables.  Sort of
> > a MailMerge if you will.
> >
> >
>
> I would suggest you take a look at string.Template or the str.format
> method. It may be somewhat simpler than doing a whole lot of replaces,
> perhaps faster as well.
>
> http://docs.python.org/library/string.html#template-strings
> http://docs.python.org/library/stdtypes.html#str.format
>
> Hugo
>
> I agree.   I had a great deal of success with using docstrings along with
str.format in a program I wrote at work.

Example, two ways:

"""
Dear Mr. {0},

Thanks for your recent inquiry.

Your current invoice #{1} is overdue by {2} days.

Please make remittance by {3} in order to avoid
overdue fees.

Sincerely,
{4}
Billing Dept.
""".format(client_name, inv_num, num_days, due_date, sender)

or

over_due_notice = """

Dear Mr. {0},

Thanks for your recent inquiry.

Your current invoice #{1} is overdue by {2} days.

Please make remittance by {3} in order to avoid
overdue fees.

Sincerely,
{4}
Billing Dept.
"""

over_due_notice.format(client_name, inv_num, num_days, due_date, sender)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/96e802d3/attachment.html>

From bill.debroglie at gmail.com  Mon Sep 27 00:37:08 2010
From: bill.debroglie at gmail.com (Bill DeBroglie)
Date: Sun, 26 Sep 2010 18:37:08 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <AANLkTimP9TMWNMcCO4VJKisQH=q-ie4JTyH0vLYvmP7j@mail.gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>
	<9DDBC030-A095-4584-9DB8-5F7805010876@gmail.com>
	<AANLkTimP9TMWNMcCO4VJKisQH=q-ie4JTyH0vLYvmP7j@mail.gmail.com>
Message-ID: <A762E1F8-2405-4302-A5F5-570649EB69B9@gmail.com>


On Sep 26, 2010, at 6:29 PM, Marc Tompkins wrote:

> On Sun, Sep 26, 2010 at 3:24 PM, Bill DeBroglie <bill.debroglie at gmail.com 
> > wrote:
>
> Is this what you mean?
>
> 	matthew-parrillas-macbook:Dawson_Book matthewparrilla$ #!/usr/bin/ 
> env python
> 	matthew-parrillas-macbook:Dawson_Book matthewparrilla$ ./chapter_2.py
> 	./chapter_2.py: line 1: syntax error near unexpected token `"Hello  
> World"'
> 	./chapter_2.py: line 1: `print("Hello World")'
>
> If so, obviously still no dice.
>
> No, I meant that you should edit your .py file and add
> #!/usr/bin/env python
> as the first line, THEN try to run it.

BINGO!
>
> Right now what's happening is that you're handing a line of Python  
> script to the shell and asking it to run it; the shell is telling  
> you (oh-so-politely) "what the hell is this?"  You need to give it a  
> clue.

Thank you for the translation. So I need to do this with every .py  
file? My friend who was helping me (he's only been at this a few  
months) doesn't need to do this. Is that possible or is he just  
misleading me?

>
> -- 
> www.fsrtechnologies.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/767bcba4/attachment-0001.html>

From steve at pearwood.info  Mon Sep 27 01:01:16 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 27 Sep 2010 09:01:16 +1000
Subject: [Tutor] Issues In Terminal
In-Reply-To: <A762E1F8-2405-4302-A5F5-570649EB69B9@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTimP9TMWNMcCO4VJKisQH=q-ie4JTyH0vLYvmP7j@mail.gmail.com>
	<A762E1F8-2405-4302-A5F5-570649EB69B9@gmail.com>
Message-ID: <201009270901.17207.steve@pearwood.info>

On Mon, 27 Sep 2010 08:37:08 am Bill DeBroglie wrote:
> > No, I meant that you should edit your .py file and add
> > #!/usr/bin/env python
> > as the first line, THEN try to run it.
>
> BINGO!
>
> > Right now what's happening is that you're handing a line of Python
> > ? script to the shell and asking it to run it; the shell is telling
> > you (oh-so-politely) "what the hell is this?" ?You need to give it
> > a clue.
>
> Thank you for the translation. So I need to do this with every .py ?
> file?

Only if you want to run them without specifying Python on the command 
line.


You can always call python first:

python name-of-my-script.py


instead of just 

name-of-my-script.py



-- 
Steven D'Aprano

From davea at ieee.org  Mon Sep 27 01:16:15 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 26 Sep 2010 19:16:15 -0400
Subject: [Tutor] Issues In Terminal
In-Reply-To: <A762E1F8-2405-4302-A5F5-570649EB69B9@gmail.com>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>	<AANLkTikqTcHy-U4p7jxjPOTQPsNYysv+AiD4z25adOd9@mail.gmail.com>	<9DDBC030-A095-4584-9DB8-5F7805010876@gmail.com>	<AANLkTimP9TMWNMcCO4VJKisQH=q-ie4JTyH0vLYvmP7j@mail.gmail.com>
	<A762E1F8-2405-4302-A5F5-570649EB69B9@gmail.com>
Message-ID: <4C9FD43F.2010900@ieee.org>



On 2:59 PM, Bill DeBroglie wrote:
> <snip>
>> No, I meant that you should edit your .py file and add
>> #!/usr/bin/env python
>> as the first line, THEN try to run it.
>
> BINGO!
>>
>> Right now what's happening is that you're handing a line of Python 
>> script to the shell and asking it to run it; the shell is telling you 
>> (oh-so-politely) "what the hell is this?"  You need to give it a clue.
>
> Thank you for the translation. So I need to do this with every .py 
> file? My friend who was helping me (he's only been at this a few 
> months) doesn't need to do this. Is that possible or is he just 
> misleading me?
>
>
Two times you wouldn't need such a line:

1) in Windows, where file extension determines what the shell will do 
with the file
2) when you explicitly run the script by naming the python executable, 
such as:

    python  chapter_2.py




From jojo.mwebaze at gmail.com  Mon Sep 27 01:45:54 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Mon, 27 Sep 2010 01:45:54 +0200
Subject: [Tutor] super.__init__() arguments
Message-ID: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>

Hey Tutor,

Seems a small issue but this has been playing for a while now, what am i
doing wrong here?

Take an Example

Class Point:
   def __init__(self, x=0, y=0):
     self.x = x
     self.y = y

Class Circle(Point):
    def __init__(self, radius=0, x=0, y=0):
        super().__init__(x, y)
        self.radius = radius


c = Circle(radius =3, x=4, y= 6)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Point.py", line 13, in __init__
    super().__init__(x, y)
TypeError: super() takes at least 1 argument (0 given)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/cf112e36/attachment.html>

From hugo.yoshi at gmail.com  Mon Sep 27 01:55:14 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 27 Sep 2010 01:55:14 +0200
Subject: [Tutor] super.__init__() arguments
In-Reply-To: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
References: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
Message-ID: <AANLkTimFW+5Uc7DtgA3CwvcQrqo5brpoKaWjn1Hm50d-@mail.gmail.com>

On Mon, Sep 27, 2010 at 1:45 AM, Jojo Mwebaze <jojo.mwebaze at gmail.com> wrote:
> Hey Tutor,
> Seems a small issue but this has been playing for a while now, what am i
> doing wrong here?
> Take an Example
> Class Point:
> ?? def __init__(self, x=0, y=0):
> ?? ? self.x = x
> ?? ? self.y = y
> Class Circle(Point):
> ?? ?def __init__(self, radius=0, x=0, y=0):
> ?? ? ? ?super().__init__(x, y)
> ?? ? ? ?self.radius = radius
>
> c = Circle(radius =3, x=4, y= 6)
> Traceback (most recent call last):
> ??File "<stdin>", line 1, in <module>
> ??File "Point.py", line 13, in __init__
> ?? ?super().__init__(x, y)
> TypeError: super() takes at least 1 argument (0 given)
>

Did you read the error you were given? super() takes an argument, and
you're not giving it any. Go read the documentation for super.

http://docs.python.org/library/functions.html#super

Hugo

From wallenpb at gmail.com  Mon Sep 27 02:17:22 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sun, 26 Sep 2010 19:17:22 -0500
Subject: [Tutor] a logic problem in an if statement
In-Reply-To: <201009270812.16338.steve@pearwood.info>
References: <AANLkTimiiov6DhRx5iFQ9uCoZDZKYBJ2tgsnMhjQiCJ1@mail.gmail.com>
	<201009270812.16338.steve@pearwood.info>
Message-ID: <AANLkTimKbFjU6EdZw+rYgdfXGuVT1do+80amTLxDziFq@mail.gmail.com>

On Sun, Sep 26, 2010 at 5:12 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> On Mon, 27 Sep 2010 06:01:35 am Bill Allen wrote:
>
> Now your decision logic becomes simple, and obvious. It documents
> itself:
>
> if click_in_bottom_half1 and click_in_bottom_half2:
>    print "Both clicks in bottom half of screen"
> elif click_in_bottom_half1:
>    print "The first click was in the bottom half."
>    print "The second click was in the top half."
> elif click_in_bottom_half2:
>    print "The first click was in the top half."
>    print "The second click was in the bottom half."
> else:
>    print "Both clicks in top half of screen"
>
>
>
> --
> Steven D'Aprano
>

Steven,

Those are great suggestions and certainly do simplify matters quite a bit.
I had not realized the I was including such redundancies into my code.  I
have some other code I need to now go back through and see what
simplifications I can there also make.

Thanks!

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/c02f85e5/attachment.html>

From lie.1296 at gmail.com  Mon Sep 27 09:11:55 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Mon, 27 Sep 2010 17:11:55 +1000
Subject: [Tutor] super.__init__() arguments
In-Reply-To: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
References: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
Message-ID: <i7pfud$55h$1@dough.gmane.org>

On 09/27/10 09:45, Jojo Mwebaze wrote:
> Hey Tutor,
> 
> Seems a small issue but this has been playing for a while now, what am i
> doing wrong here?
> 

super() without argument only works for Python 3. In Python 2.x, you
have to pass to super your class name and your class instance, i.e.:

Class Circle(Point):
    def __init__(self, radius=0, x=0, y=0):
        super(Point, self).__init__(x, y)
        self.radius = radius


From rwobben at hotmail.com  Mon Sep 27 11:29:43 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 27 Sep 2010 09:29:43 +0000
Subject: [Tutor] class method problem
In-Reply-To: <AANLkTi=K3kSMWBLyyyoevjtJ_j71f_0d8s86p6-uG9cS@mail.gmail.com>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>,
	<201009261116.13948.steve@pearwood.info>,
	<AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>,
	<201009261714.49330.steve@pearwood.info>,
	<AANLkTi=K3kSMWBLyyyoevjtJ_j71f_0d8s86p6-uG9cS@mail.gmail.com>
Message-ID: <SNT118-W3C358B0AB976D63BE32D6AE650@phx.gbl>



Hello, 
 
Fine that you are in a arque
But can we come back to my problem.
 
How can I take care that test2 can be initialized.
 
Roelof

  		 	   		  

From waynejwerner at gmail.com  Mon Sep 27 13:01:06 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Mon, 27 Sep 2010 11:01:06 +0000
Subject: [Tutor] super.__init__() arguments
In-Reply-To: <i7pfud$55h$1@dough.gmane.org>
References: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
	<i7pfud$55h$1@dough.gmane.org>
Message-ID: <AANLkTi=0=cDHQC_PDCY-VqqE3ZRh=rqiFsKjAtiFUV-3@mail.gmail.com>

In addition it only works for new style classes.

-wayne

On 9/27/10, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 09/27/10 09:45, Jojo Mwebaze wrote:
>> Hey Tutor,
>>
>> Seems a small issue but this has been playing for a while now, what am i
>> doing wrong here?
>>
>
> super() without argument only works for Python 3. In Python 2.x, you
> have to pass to super your class name and your class instance, i.e.:
>
> Class Circle(Point):
>     def __init__(self, radius=0, x=0, y=0):
>         super(Point, self).__init__(x, y)
>         self.radius = radius
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

-- 
Sent from my mobile device

From davea at ieee.org  Mon Sep 27 14:33:25 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 27 Sep 2010 08:33:25 -0400
Subject: [Tutor] class method problem
In-Reply-To: <SNT118-W3C358B0AB976D63BE32D6AE650@phx.gbl>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>,
	<201009261116.13948.steve@pearwood.info>,
	<AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>,
	<201009261714.49330.steve@pearwood.info>,
	<AANLkTi=K3kSMWBLyyyoevjtJ_j71f_0d8s86p6-uG9cS@mail.gmail.com>
	<SNT118-W3C358B0AB976D63BE32D6AE650@phx.gbl>
Message-ID: <4CA08F15.9090608@ieee.org>

  On 2:59 PM, Roelof Wobben wrote:
>
> Hello,
>
> Fine that you are in a arque
> But can we come back to my problem.
>
> How can I take care that test2 can be initialized.
>
> Roelof
>
You had this code, and got the following error:

class zoeken() :
     pass
     def __len__(self):
         return 0
     def __str__(self):
         return test2
     def find(self, strng, ch, start, stop):
         index = start
         while index<  len(strng) and index<  stop:
             if strng[index] == ch:
                 return index
             index += 1
             return -1


test = zoeken()
test.woord = "tamara"
test2 = zoeken.find(test, "a", 1,5)
print test(test2)

But now I get this message :

Traceback (most recent call last):
   File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 20, in<module>
     test2 = zoeken.find(test, "a", 1,5)

TypeError: find() takes exactly 5 arguments (4 given)


The immediate answer is that
   1) you are calling the find method with the class as the first 
argument, while it was declared with 'self'.
   2) you never pass a string to be searched, so there's nothing useful 
to be passed to strng.

It's the second problem that causes the error,  but the first one is 
tied with it.  You can fix the immediate syntax error by passing the 
string explicitly.

test2 = test.find("tamara", "a", 1, 5)

The real problem though is one of design, or intent.  You're assigning 
that "tamara" to an attribute of a particular instance of zoeken().  So 
did you mean that find() would look there for it?  If that were the 
case, the find declaration should change to:


     def find(self, ch, start, stop):

and naturally, the reference to strng[index]   should change to  
self.woord[index]

There are several things wrong with the find() method, and with the 
__str__() method, but the first question that needs answering is What 
does a zoeken (please capitalize it, to follow Python conventions) 
object represent?  What are its data attributes going to mean?  Since 
it's not English, I don't get a clue from the name, but normally I'd get 
one from the __init__() method, which you omitted.  My convention is to 
initialize all attributes in the __init__() method, even if they're not 
always used.  But if that's undesirable for some reason, then at least 
comment on them there.

DaveA

From joel.goldstick at gmail.com  Mon Sep 27 16:37:52 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 27 Sep 2010 10:37:52 -0400
Subject: [Tutor] class method problem
In-Reply-To: <4CA08F15.9090608@ieee.org>
References: <SNT118-W371CDA14778B7E68CA0B2BAE630@phx.gbl>
	<201009261116.13948.steve@pearwood.info>
	<AANLkTi=wkKw7qzM--wc+CjMmtZuR-wc2NZz9Yj0F7FQB@mail.gmail.com>
	<201009261714.49330.steve@pearwood.info>
	<AANLkTi=K3kSMWBLyyyoevjtJ_j71f_0d8s86p6-uG9cS@mail.gmail.com>
	<SNT118-W3C358B0AB976D63BE32D6AE650@phx.gbl>
	<4CA08F15.9090608@ieee.org>
Message-ID: <AANLkTi=FjA4n2ogs+VhhD9jVkKS2C-+D=mD-p+ONFwHb@mail.gmail.com>

I looked up the word zoeken -- it means find in English.

I looked up the chapter and exercise in the online text "How to think
like a computer scientist"

Its a good tutorial.

I think the OP seems to get confused on basic concepts.

Here is my stab at the exercise:

#!/usr/bin/env python

"""This exercise is to take the find function, alter it so that it can
specify an end point for the search.  It is problem 2 at the end of this
chapter:
http://openbookproject.net/thinkcs/python/english2e/ch15.html

The author notes that end should default to len(str), but it can't since
default parameters are initialized when the function is defined and not
when it is invoked.
"""

# this is from the author's text
def find(str, ch, start=0):
    index = start
    while index < len(str):
        if str[index] == ch:
            return index
        index = index + 1
    return -1

# this I believe is the concept the author was looking to get the
reader to understand

def find2(str, ch, start=0, end = None):
    if end == None:
        end = len(str)
    index = start
    while index < end:
        if str[index] == ch:
            return index
        index = index + 1
    return -1




-- 
Joel Goldstick

From jojo.mwebaze at gmail.com  Mon Sep 27 16:55:06 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Mon, 27 Sep 2010 16:55:06 +0200
Subject: [Tutor] super.__init__() arguments
In-Reply-To: <AANLkTi=0=cDHQC_PDCY-VqqE3ZRh=rqiFsKjAtiFUV-3@mail.gmail.com>
References: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
	<i7pfud$55h$1@dough.gmane.org>
	<AANLkTi=0=cDHQC_PDCY-VqqE3ZRh=rqiFsKjAtiFUV-3@mail.gmail.com>
Message-ID: <AANLkTi=HExHu+zUcL0fNJWPvoOXmRuSVPJyuoKX8wn8n@mail.gmail.com>

Thanks Guys! Works perfect....

cheers



On Mon, Sep 27, 2010 at 1:01 PM, Wayne Werner <waynejwerner at gmail.com>wrote:

> In addition it only works for new style classes.
>
> -wayne
>
> On 9/27/10, Lie Ryan <lie.1296 at gmail.com> wrote:
> > On 09/27/10 09:45, Jojo Mwebaze wrote:
> >> Hey Tutor,
> >>
> >> Seems a small issue but this has been playing for a while now, what am i
> >> doing wrong here?
> >>
> >
> > super() without argument only works for Python 3. In Python 2.x, you
> > have to pass to super your class name and your class instance, i.e.:
> >
> > Class Circle(Point):
> >     def __init__(self, radius=0, x=0, y=0):
> >         super(Point, self).__init__(x, y)
> >         self.radius = radius
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> --
> Sent from my mobile device
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/33123070/attachment.html>

From jojo.mwebaze at gmail.com  Mon Sep 27 16:56:04 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Mon, 27 Sep 2010 16:56:04 +0200
Subject: [Tutor] super.__init__() arguments
In-Reply-To: <AANLkTi=0=cDHQC_PDCY-VqqE3ZRh=rqiFsKjAtiFUV-3@mail.gmail.com>
References: <AANLkTi=r+bw_33c1e3pg6SYu-F_eZ6H7sFG4d4c-8vTO@mail.gmail.com>
	<i7pfud$55h$1@dough.gmane.org>
	<AANLkTi=0=cDHQC_PDCY-VqqE3ZRh=rqiFsKjAtiFUV-3@mail.gmail.com>
Message-ID: <AANLkTim5GwYDTD_D5YE3H6A6vwZXw0GFVj1wdPahcNK7@mail.gmail.com>

Thanks Guys! Works perfect....

cheers



On Mon, Sep 27, 2010 at 1:01 PM, Wayne Werner <waynejwerner at gmail.com>wrote:

> In addition it only works for new style classes.
>
> -wayne
>
> On 9/27/10, Lie Ryan <lie.1296 at gmail.com> wrote:
> > On 09/27/10 09:45, Jojo Mwebaze wrote:
> >> Hey Tutor,
> >>
> >> Seems a small issue but this has been playing for a while now, what am i
> >> doing wrong here?
> >>
> >
> > super() without argument only works for Python 3. In Python 2.x, you
> > have to pass to super your class name and your class instance, i.e.:
> >
> > Class Circle(Point):
> >     def __init__(self, radius=0, x=0, y=0):
> >         super(Point, self).__init__(x, y)
> >         self.radius = radius
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> --
> Sent from my mobile device
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/856441de/attachment-0001.html>

From tim at lashni.net  Mon Sep 27 17:09:54 2010
From: tim at lashni.net (Tim Miller)
Date: Tue, 28 Sep 2010 01:09:54 +1000
Subject: [Tutor] function with multiple checks
Message-ID: <4CA0B3C2.8020206@lashni.net>

I've got a small function that I'm using to check whether a password is 
of a certain length and contains mixed case, numbers and punctuation.

Originally I was using multiple "if re.search" for the patterns but it 
looked terrible so I've read up on list comprehensions and it's slightly 
improved. I just can't escape the feeling that there's a more elegant 
way to do this that I'm missing.

I've been looking through all the python stuff that I thought might be 
relevant (lambda, map, filter, set, frozenset, etc) but nothing has come 
together. Just wondering if anyone has suggested reading material for 
alternate ways they'd handle this code.

CODE:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation


def complex_password(password):
     """Checks password for sufficient complexity."""
     if len(password) < 12:
         return False
     if len([c for c in password if c in punctuation]) == 0:
         return False
     if len([c for c in password if c in digits]) == 0:
         return False
     if len([c for c in password if c in ascii_uppercase]) == 0:
         return False
     if len([c for c in password if c in ascii_lowercase]) == 0:
         return False
     return True

From mehgcap at gmail.com  Mon Sep 27 17:32:32 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 11:32:32 -0400
Subject: [Tutor] dynamic arrays?
Message-ID: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>

Hi all,
One thing I have never much liked about Python is its need for
specifically sized arrays and lack of a dynamic, array-like data
structure. For example, the following fails with a "list assignment
index out of range" error:

a=[]
i=0
for l in open("file.txt", "r"):
  a[i]=l
   i+=1

Is there something in Python I am missing that would let the above
work? I am hoping that my annoyance at the apparent lack of such a
thing is unfounded. BTW, I know why the above throws that exception.
TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From bkjones at gmail.com  Mon Sep 27 17:35:09 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 27 Sep 2010 11:35:09 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
Message-ID: <AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>

On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure. For example, the following fails with a "list assignment
> index out of range" error:
>
> a=[]
> i=0
> for l in open("file.txt", "r"):
>  a[i]=l
>   i+=1
>

Is there some reason to use this construct rather than the list object's
'append' method?

for i in open('file.txt', 'r'):
    a.append(l)

brian

>
> Is there something in Python I am missing that would let the above
> work? I am hoping that my annoyance at the apparent lack of such a
> thing is unfounded. BTW, I know why the above throws that exception.
> TIA.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/7d294458/attachment.html>

From evert.rol at gmail.com  Mon Sep 27 17:36:36 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 27 Sep 2010 17:36:36 +0200
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
Message-ID: <A2E61FC7-983A-4965-8478-E46D97CC4249@gmail.com>

> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure. For example, the following fails with a "list assignment
> index out of range" error:
> 
> a=[]
> i=0
> for l in open("file.txt", "r"):
>  a[i]=l
>   i+=1

Hmm, what's wrong with append()?

a = []
for l in open("file.txt"):
  a.append(l)

Can't answer on the why, ie, why use append instead of a[i]. 
Then again, if you want that option, use a dictionary (probably bad idea here, but it works):

a = {}
i = 0
for l in open("file.txt"):
  a[i] = l
  i += 1

Cheers,

  Evert


> Is there something in Python I am missing that would let the above
> work? I am hoping that my annoyance at the apparent lack of such a
> thing is unfounded. BTW, I know why the above throws that exception.
> TIA.


From mehgcap at gmail.com  Mon Sep 27 17:39:48 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 11:39:48 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
Message-ID: <AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>

On 9/27/10, Brian Jones <bkjones at gmail.com> wrote:
> On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall <mehgcap at gmail.com> wrote:
>
>> Hi all,
>> One thing I have never much liked about Python is its need for
>> specifically sized arrays and lack of a dynamic, array-like data
>> structure. For example, the following fails with a "list assignment
>> index out of range" error:
>>
>> a=[]
>> i=0
>> for l in open("file.txt", "r"):
>>  a[i]=l
>>   i+=1
>>
>
> Is there some reason to use this construct rather than the list object's
> 'append' method?
>
> for i in open('file.txt', 'r'):
>     a.append(l)

Ah, good thought. So exactly what are the functional differences
between a list and an array in Python, or are they so close that it
makes no difference which you use? It seems like you can index into
both with the bracket notation. Are lists limited in any way that
makes them not as desirable as arrays?
>
> brian
>
>>
>> Is there something in Python I am missing that would let the above
>> work? I am hoping that my annoyance at the apparent lack of such a
>> thing is unfounded. BTW, I know why the above throws that exception.
>> TIA.
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Brian K. Jones
> My Blog          http://www.protocolostomy.com
> Follow me      http://twitter.com/bkjones
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From bkjones at gmail.com  Mon Sep 27 17:43:10 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 27 Sep 2010 11:43:10 -0400
Subject: [Tutor] function with multiple checks
In-Reply-To: <4CA0B3C2.8020206@lashni.net>
References: <4CA0B3C2.8020206@lashni.net>
Message-ID: <AANLkTim0BFuxZAx5yFGd04ru_eR5ZN2WuyU6j-bkZVmt@mail.gmail.com>

On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller <tim at lashni.net> wrote:

> I've got a small function that I'm using to check whether a password is of
> a certain length and contains mixed case, numbers and punctuation.
>
> Originally I was using multiple "if re.search" for the patterns but it
> looked terrible so I've read up on list comprehensions and it's slightly
> improved. I just can't escape the feeling that there's a more elegant way to
> do this that I'm missing.
>
> I've been looking through all the python stuff that I thought might be
> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come
> together. Just wondering if anyone has suggested reading material for
> alternate ways they'd handle this code.
>
> CODE:
>
> from string import ascii_lowercase, ascii_uppercase, digits, punctuation
>
>
> def complex_password(password):
>    """Checks password for sufficient complexity."""
>    if len(password) < 12:
>        return False
>    if len([c for c in password if c in punctuation]) == 0:
>        return False
>    if len([c for c in password if c in digits]) == 0:
>        return False
>    if len([c for c in password if c in ascii_uppercase]) == 0:
>        return False
>    if len([c for c in password if c in ascii_lowercase]) == 0:
>        return False
>    return True
>


You can probably make other optimizations, but just to start, you can get
rid of 'len' and '== 0':

if not [c for c in password if c in ascii_lowercase]:
   return False

will return False if there are no lowercase characters. An empty list
evaluates to False. With that in mind, you could just 'return [c for c in
password if c in ascii_lowercase]' if the calling code is written to handle
it.




> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/f45894dc/attachment-0001.html>

From vince at vinces.ca  Mon Sep 27 17:41:41 2010
From: vince at vinces.ca (Vince Spicer)
Date: Mon, 27 Sep 2010 09:41:41 -0600
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
Message-ID: <AANLkTimFnbHOEHFyDHvn9STJJYAzb_9QJUnCW=XKAUcg@mail.gmail.com>

On Mon, Sep 27, 2010 at 9:32 AM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all,
> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure. For example, the following fails with a "list assignment
> index out of range" error:
>
> a=[]
> i=0
> for l in open("file.txt", "r"):
>  a[i]=l
>   i+=1
>
> Is there something in Python I am missing that would let the above
> work? I am hoping that my annoyance at the apparent lack of such a
> thing is unfounded. BTW, I know why the above throws that exception.
> TIA.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


Your method works ok for dictionaries but when working with lists
you can append data.

#method 1: works with any iterator
data=[]
for line in open("file.txt", "r"):
    data.append(line)

#method 2: this will convert a file into an array
data = open("file.txt", "r").readlines()

#method 3: if you had to know the line number
a = []
for i, line in enumerate(open('flie.txt')):
    print i, line
    a.append(line)

Hope this helps
-- 
Vince Spicer
Lead Developer - MCE Computing

-- 
Sent from Ubuntu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/3231130f/attachment.html>

From malaclypse2 at gmail.com  Mon Sep 27 17:46:17 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Mon, 27 Sep 2010 11:46:17 -0400
Subject: [Tutor] function with multiple checks
In-Reply-To: <4CA0B3C2.8020206@lashni.net>
References: <4CA0B3C2.8020206@lashni.net>
Message-ID: <AANLkTina2KcA8Y=_VAPg_6=42n4rrEiq=-z5QF3nocBX@mail.gmail.com>

On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller <tim at lashni.net> wrote:
> I've got a small function that I'm using to check whether a password is of a
> certain length and contains mixed case, numbers and punctuation.
>
> Originally I was using multiple "if re.search" for the patterns but it
> looked terrible so I've read up on list comprehensions and it's slightly
> improved. I just can't escape the feeling that there's a more elegant way to
> do this that I'm missing.
>
> I've been looking through all the python stuff that I thought might be
> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come
> together. Just wondering if anyone has suggested reading material for
> alternate ways they'd handle this code.

The way you've written it obviously works fine.  That being said, I'd
probably do something like this:

from string import ascii_lowercase, ascii_uppercase, digits, punctuation

def complex_password(password):
    '''Checks to make sure a password is complex'''
    checks = [
        lambda p: len(p) > 12,
        lambda p: any(c in punctuation for c in p),
        lambda p: any(c in digits for c in p),
        lambda p: any(c in ascii_uppercase for c in p),
        lambda p: any(c in ascii_lowercase for c in p),
        ]

    return all(check(password) for check in checks)

if __name__ == '__main__':
    passwords = ['password', 'Password1234567', 'Password1.234567']
    for password in passwords:
        print password, complex_password(password)


In the complex_password function, I create a list of tests, each of
which is a function that returns either true or false.  In this case I
used lambdas to create the function objects, since all the tests
easily fit on a single line, but it would be fine to define a function
elsewhere and use it in the list if you had more complicated checks to
do.

all() is a built in function that returns True if all of the elements
in an iterable are true (or the iterable is empty), and otherwise
returns False.  That seems like an ideal way to execute a bunch of
tests and return True if all of them pass, and otherwise return false.
 In this case, the iterable is a generator expression that evaluates
each of the rules with the supplied password.

any() is similar, but it returns True if any member of the iterable is True.

Looking back at it, I probably should have used longer variable names
in my rules, which would have made them a bit easier to read.  When I
was writing them, I was worried about the lines getting too long with
longer names.  It didn't turn out to be a problem though.

-- 
Jerry

From bkjones at gmail.com  Mon Sep 27 17:45:56 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 27 Sep 2010 11:45:56 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
	<AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
Message-ID: <AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>

On Mon, Sep 27, 2010 at 11:39 AM, Alex Hall <mehgcap at gmail.com> wrote:

> On 9/27/10, Brian Jones <bkjones at gmail.com> wrote:
> > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall <mehgcap at gmail.com> wrote:
> >
> >> Hi all,
> >> One thing I have never much liked about Python is its need for
> >> specifically sized arrays and lack of a dynamic, array-like data
> >> structure. For example, the following fails with a "list assignment
> >> index out of range" error:
> >>
> >> a=[]
> >> i=0
> >> for l in open("file.txt", "r"):
> >>  a[i]=l
> >>   i+=1
> >>
> >
> > Is there some reason to use this construct rather than the list object's
> > 'append' method?
> >
> > for i in open('file.txt', 'r'):
> >     a.append(l)
>
> Ah, good thought. So exactly what are the functional differences
> between a list and an array in Python, or are they so close that it
> makes no difference which you use? It seems like you can index into
> both with the bracket notation. Are lists limited in any way that
> makes them not as desirable as arrays?
>

A python list and a python array are one and the same to my knowledge. Do
you mean a list and a dict? A dict is an unordered collection of key-value
pairs, and the keys are more or less arbitrary values of your own creation
(I believe the single limitation is the key must be a hashable type). A list
is a 'flat' array, although you can use enumerate(l) to get index->value
pairs from a list 'l'.

hth.



> >
> > brian
> >
> >>
> >> Is there something in Python I am missing that would let the above
> >> work? I am hoping that my annoyance at the apparent lack of such a
> >> thing is unfounded. BTW, I know why the above throws that exception.
> >> TIA.
> >>
> >> --
> >> Have a great day,
> >> Alex (msg sent from GMail website)
> >> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> >> _______________________________________________
> >> Tutor maillist  -  Tutor at python.org
> >> To unsubscribe or change subscription options:
> >> http://mail.python.org/mailman/listinfo/tutor
> >>
> >
> >
> >
> > --
> > Brian K. Jones
> > My Blog          http://www.protocolostomy.com
> > Follow me      http://twitter.com/bkjones
> >
>
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/e1f1cec3/attachment.html>

From bkjones at gmail.com  Mon Sep 27 17:50:56 2010
From: bkjones at gmail.com (Brian Jones)
Date: Mon, 27 Sep 2010 11:50:56 -0400
Subject: [Tutor] function with multiple checks
In-Reply-To: <AANLkTim0BFuxZAx5yFGd04ru_eR5ZN2WuyU6j-bkZVmt@mail.gmail.com>
References: <4CA0B3C2.8020206@lashni.net>
	<AANLkTim0BFuxZAx5yFGd04ru_eR5ZN2WuyU6j-bkZVmt@mail.gmail.com>
Message-ID: <AANLkTinL9QY+rQ9Lf7OVNd-AZTW+8pM6ydnprrikLf3s@mail.gmail.com>

On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones <bkjones at gmail.com> wrote:

>
>
> On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller <tim at lashni.net> wrote:
>
>> I've got a small function that I'm using to check whether a password is of
>> a certain length and contains mixed case, numbers and punctuation.
>>
>> Originally I was using multiple "if re.search" for the patterns but it
>> looked terrible so I've read up on list comprehensions and it's slightly
>> improved. I just can't escape the feeling that there's a more elegant way to
>> do this that I'm missing.
>>
>> I've been looking through all the python stuff that I thought might be
>> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come
>> together. Just wondering if anyone has suggested reading material for
>> alternate ways they'd handle this code.
>>
>> CODE:
>>
>> from string import ascii_lowercase, ascii_uppercase, digits, punctuation
>>
>>
>> def complex_password(password):
>>    """Checks password for sufficient complexity."""
>>    if len(password) < 12:
>>        return False
>>    if len([c for c in password if c in punctuation]) == 0:
>>        return False
>>    if len([c for c in password if c in digits]) == 0:
>>        return False
>>    if len([c for c in password if c in ascii_uppercase]) == 0:
>>        return False
>>    if len([c for c in password if c in ascii_lowercase]) == 0:
>>        return False
>>    return True
>>
>
How about this:

d = [digits, punctuation, ascii_uppercase, ascii_lowercase]
s = 'asdf1234A'
for c in d:
   if not [x for x in s if x in c]:
       print x, ' not in ', c

Just a quick hack, but you get the idea. It breaks when you want different
numbers of characters from the different lists in the password.



>
>
> You can probably make other optimizations, but just to start, you can get
> rid of 'len' and '== 0':
>
> if not [c for c in password if c in ascii_lowercase]:
>    return False
>
> will return False if there are no lowercase characters. An empty list
> evaluates to False. With that in mind, you could just 'return [c for c in
> password if c in ascii_lowercase]' if the calling code is written to handle
> it.
>
>
>
>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Brian K. Jones
> My Blog          http://www.protocolostomy.com
> Follow me      http://twitter.com/bkjones
>



-- 
Brian K. Jones
My Blog          http://www.protocolostomy.com
Follow me      http://twitter.com/bkjones
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/470a3341/attachment-0001.html>

From evert.rol at gmail.com  Mon Sep 27 17:51:24 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 27 Sep 2010 17:51:24 +0200
Subject: [Tutor] function with multiple checks
In-Reply-To: <4CA0B3C2.8020206@lashni.net>
References: <4CA0B3C2.8020206@lashni.net>
Message-ID: <472D17C9-15C2-412E-8153-A3C3662487F5@gmail.com>

> I've got a small function that I'm using to check whether a password is of a certain length and contains mixed case, numbers and punctuation.
> 
> Originally I was using multiple "if re.search" for the patterns but it looked terrible so I've read up on list comprehensions and it's slightly improved. I just can't escape the feeling that there's a more elegant way to do this that I'm missing.
> 
> I've been looking through all the python stuff that I thought might be relevant (lambda, map, filter, set, frozenset, etc) but nothing has come together. Just wondering if anyone has suggested reading material for alternate ways they'd handle this code.

set does seem to have what you want: isdisjoint() could do the trick.
Eg:

    if set(punctuation).isdisjoint(password) or set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) or set(ascii_lowercase).isdisjoint(password):
         return False
    return True


You could even confuse yourself and put it all on one line:

      return not any(set(chars).isdisjoint(password) for chars in [punctuation, digits, ascii_uppercase, ascii_lowercase])

but I wouldn't recomended it. I guess this can even shortened further.
(note: the 'not' operator is needed, because isdisjoint returns True for what you probably prefer as False.)


  Evert


> CODE:
> 
> from string import ascii_lowercase, ascii_uppercase, digits, punctuation
> 
> 
> def complex_password(password):
>    """Checks password for sufficient complexity."""
>    if len(password) < 12:
>        return False
>    if len([c for c in password if c in punctuation]) == 0:
>        return False
>    if len([c for c in password if c in digits]) == 0:
>        return False
>    if len([c for c in password if c in ascii_uppercase]) == 0:
>        return False
>    if len([c for c in password if c in ascii_lowercase]) == 0:
>        return False
>    return True
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From mehgcap at gmail.com  Mon Sep 27 17:54:47 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 11:54:47 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
	<AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
	<AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
Message-ID: <AANLkTikdMiS8ueppjyZySFLbtEc8LYgr=_v8nv3sfY5O@mail.gmail.com>

On 9/27/10, Brian Jones <bkjones at gmail.com> wrote:
> On Mon, Sep 27, 2010 at 11:39 AM, Alex Hall <mehgcap at gmail.com> wrote:
>
>> On 9/27/10, Brian Jones <bkjones at gmail.com> wrote:
>> > On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall <mehgcap at gmail.com> wrote:
>> >
>> >> Hi all,
>> >> One thing I have never much liked about Python is its need for
>> >> specifically sized arrays and lack of a dynamic, array-like data
>> >> structure. For example, the following fails with a "list assignment
>> >> index out of range" error:
>> >>
>> >> a=[]
>> >> i=0
>> >> for l in open("file.txt", "r"):
>> >>  a[i]=l
>> >>   i+=1
>> >>
>> >
>> > Is there some reason to use this construct rather than the list object's
>> > 'append' method?
>> >
>> > for i in open('file.txt', 'r'):
>> >     a.append(l)
>>
>> Ah, good thought. So exactly what are the functional differences
>> between a list and an array in Python, or are they so close that it
>> makes no difference which you use? It seems like you can index into
>> both with the bracket notation. Are lists limited in any way that
>> makes them not as desirable as arrays?
>>
>
> A python list and a python array are one and the same to my knowledge. Do
> you mean a list and a dict? A dict is an unordered collection of key-value
> pairs, and the keys are more or less arbitrary values of your own creation
> (I believe the single limitation is the key must be a hashable type). A list
> is a 'flat' array, although you can use enumerate(l) to get index->value
> pairs from a list 'l'.
Oh. Somehow I never made the connection that arrays and lists are the
same. :) No, I was not thinking of a dictionary in this case, though I
will have to look into that enumerate function. Thanks for clearing
this up.
>
> hth.
>
>
>
>> >
>> > brian
>> >
>> >>
>> >> Is there something in Python I am missing that would let the above
>> >> work? I am hoping that my annoyance at the apparent lack of such a
>> >> thing is unfounded. BTW, I know why the above throws that exception.
>> >> TIA.
>> >>
>> >> --
>> >> Have a great day,
>> >> Alex (msg sent from GMail website)
>> >> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>> >> _______________________________________________
>> >> Tutor maillist  -  Tutor at python.org
>> >> To unsubscribe or change subscription options:
>> >> http://mail.python.org/mailman/listinfo/tutor
>> >>
>> >
>> >
>> >
>> > --
>> > Brian K. Jones
>> > My Blog          http://www.protocolostomy.com
>> > Follow me      http://twitter.com/bkjones
>> >
>>
>>
>> --
>> Have a great day,
>> Alex (msg sent from GMail website)
>> mehgcap at gmail.com; http://www.facebook.com/mehgcap
>>
>
>
>
> --
> Brian K. Jones
> My Blog          http://www.protocolostomy.com
> Follow me      http://twitter.com/bkjones
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From davea at ieee.org  Mon Sep 27 18:12:10 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 27 Sep 2010 12:12:10 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>	<AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
	<AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
Message-ID: <4CA0C25A.4090709@ieee.org>



On 2:59 PM, Alex Hall wrote:
> On 9/27/10, Brian Jones<bkjones at gmail.com>  wrote:
>> On Mon, Sep 27, 2010 at 11:32 AM, Alex Hall<mehgcap at gmail.com>  wrote:
>>
>>> Hi all,
>>> One thing I have never much liked about Python is its need for
>>> specifically sized arrays and lack of a dynamic, array-like data
>>> structure. For example, the following fails with a "list assignment
>>> index out of range" error:
>>>
>>> a=[]
>>> i=0
>>> for l in open("file.txt", "r"):
>>>   a[i]=l
>>>    i+=1
>>>
>> Is there some reason to use this construct rather than the list object's
>> 'append' method?
>>
>> for i in open('file.txt', 'r'):
>>      a.append(l)
> Ah, good thought. So exactly what are the functional differences
> between a list and an array in Python, or are they so close that it
> makes no difference which you use? It seems like you can index into
> both with the bracket notation. Are lists limited in any way that
> makes them not as desirable as arrays?
> <snip>

an array is of homogeneous type, so it takes much less space.  On the 
other hand, if you ever want to have some elements different from 
others, you need to use list.,  Similarly, if the type of data isn't one 
of the dozen or so defined array types, you need to use list.

DaveA


From joel.goldstick at gmail.com  Mon Sep 27 18:12:55 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 27 Sep 2010 12:12:55 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTimP4hv_RLfw=1GvqwRQ-+_RDqC33UdEC_Djs8Kh@mail.gmail.com>
	<AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
	<AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
Message-ID: <AANLkTikE9ONt=XdACZTRAGd4pJbL7MnE-UgKRj5xyZAZ@mail.gmail.com>

> Hi all,
>> >> One thing I have never much liked about Python is its need for
>> >> specifically sized arrays and lack of a dynamic, array-like data
>> >> structure. For example, the following fails with a "list assignment
>> >> index out of range" error:
a=[]
i=0
for l in open("file.txt", "r"):
 a[i]=l
  i+=1

>> >>

> A python list and a python array are one and the same to my knowledge.

Actually I looked it up, there is an array module.  I've never used
it.  Lists are built in data type that act like what people mean when
they say arrays -- an ordered list of values accessible by a
positional index.

The reason you get the exception is that you are trying to put
something in a[0], and you defined a as empty, so it has no a[0] yet.
len(a) == 0 initially. When you append a value
to a, your first value is stored, in a[0], etc.  Read about slices.
They're fun, and informative to understand indexing concepts in python


-- 
Joel Goldstick

From tim at lashni.net  Mon Sep 27 18:52:43 2010
From: tim at lashni.net (Tim Miller)
Date: Tue, 28 Sep 2010 02:52:43 +1000
Subject: [Tutor] function with multiple checks
In-Reply-To: <472D17C9-15C2-412E-8153-A3C3662487F5@gmail.com>
References: <4CA0B3C2.8020206@lashni.net>
	<472D17C9-15C2-412E-8153-A3C3662487F5@gmail.com>
Message-ID: <4CA0CBDB.60704@lashni.net>

> set does seem to have what you want: isdisjoint() could do the trick.
> Eg:
>
>      if set(punctuation).isdisjoint(password) or set(digits).isdisjoint(password) or set(ascii_uppercase).isdisjoint(password) or set(ascii_lowercase).isdisjoint(password):
>           return False
>      return True
>
>
> You could even confuse yourself and put it all on one line:
>
>        return not any(set(chars).isdisjoint(password) for chars in [punctuation, digits, ascii_uppercase, ascii_lowercase])
>
> but I wouldn't recomended it. I guess this can even shortened further.
> (note: the 'not' operator is needed, because isdisjoint returns True for what you probably prefer as False.)

Here I was thinking I'd read through set types thoroughly and now that 
you've pointed out isdisjoint it really jumps out describing exactly the 
usage I was looking for.

isdisjoint(other)?

     Return True if the set has no elements in common with other. Sets 
are disjoint if and only if their intersection is the empty set.

From tim at lashni.net  Mon Sep 27 18:57:54 2010
From: tim at lashni.net (Tim Miller)
Date: Tue, 28 Sep 2010 02:57:54 +1000
Subject: [Tutor] function with multiple checks
In-Reply-To: <AANLkTina2KcA8Y=_VAPg_6=42n4rrEiq=-z5QF3nocBX@mail.gmail.com>
References: <4CA0B3C2.8020206@lashni.net>
	<AANLkTina2KcA8Y=_VAPg_6=42n4rrEiq=-z5QF3nocBX@mail.gmail.com>
Message-ID: <4CA0CD12.10007@lashni.net>

On 28/09/10 01:46, Jerry Hill wrote:
> The way you've written it obviously works fine.  That being said, I'd
> probably do something like this:
>
> from string import ascii_lowercase, ascii_uppercase, digits, punctuation
>
> def complex_password(password):
>      '''Checks to make sure a password is complex'''
>      checks = [
>          lambda p: len(p)>  12,
>          lambda p: any(c in punctuation for c in p),
>          lambda p: any(c in digits for c in p),
>          lambda p: any(c in ascii_uppercase for c in p),
>          lambda p: any(c in ascii_lowercase for c in p),
>          ]
>
>      return all(check(password) for check in checks)
>
> if __name__ == '__main__':
>      passwords = ['password', 'Password1234567', 'Password1.234567']
>      for password in passwords:
>          print password, complex_password(password)
>
>
> In the complex_password function, I create a list of tests, each of
> which is a function that returns either true or false.  In this case I
> used lambdas to create the function objects, since all the tests
> easily fit on a single line, but it would be fine to define a function
> elsewhere and use it in the list if you had more complicated checks to
> do.
>
> all() is a built in function that returns True if all of the elements
> in an iterable are true (or the iterable is empty), and otherwise
> returns False.  That seems like an ideal way to execute a bunch of
> tests and return True if all of them pass, and otherwise return false.
>   In this case, the iterable is a generator expression that evaluates
> each of the rules with the supplied password.
>
> any() is similar, but it returns True if any member of the iterable is True.
>
> Looking back at it, I probably should have used longer variable names
> in my rules, which would have made them a bit easier to read.  When I
> was writing them, I was worried about the lines getting too long with
> longer names.  It didn't turn out to be a problem though.
>

After doing a bit more reading and trying out some of the very useful 
suggestions people have made in this thread, I've decided to rework that 
section based on your example.

I was trying to use lambdas to solve this earlier but it's new territory 
for me and I couldn't figure out how to string them together as you've 
done above. The explanation is especially invaluable, thanks.

From tim at lashni.net  Mon Sep 27 19:06:13 2010
From: tim at lashni.net (Tim Miller)
Date: Tue, 28 Sep 2010 03:06:13 +1000
Subject: [Tutor] function with multiple checks
In-Reply-To: <AANLkTinL9QY+rQ9Lf7OVNd-AZTW+8pM6ydnprrikLf3s@mail.gmail.com>
References: <4CA0B3C2.8020206@lashni.net>
	<AANLkTim0BFuxZAx5yFGd04ru_eR5ZN2WuyU6j-bkZVmt@mail.gmail.com>
	<AANLkTinL9QY+rQ9Lf7OVNd-AZTW+8pM6ydnprrikLf3s@mail.gmail.com>
Message-ID: <4CA0CF05.4000800@lashni.net>

On 28/09/10 01:50, Brian Jones wrote:
>
>
> On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones <bkjones at gmail.com
> <mailto:bkjones at gmail.com>> wrote:
>
> How about this:
>
> d = [digits, punctuation, ascii_uppercase, ascii_lowercase]
> s = 'asdf1234A'
> for c in d:
>     if not [x for x in s if x in c]:
>         print x, ' not in ', c
>
> Just a quick hack, but you get the idea. It breaks when you want
> different numbers of characters from the different lists in the password.
>
>     You can probably make other optimizations, but just to start, you
>     can get rid of 'len' and '== 0':
>
>     if not [c for c in password if c in ascii_lowercase]:
>         return False
>
>     will return False if there are no lowercase characters. An empty
>     list evaluates to False. With that in mind, you could just 'return
>     [c for c in password if c in ascii_lowercase]' if the calling code
>     is written to handle it.

I've rewritten that section of code using the lambda example from this 
thread since to me it just looks very clean. Thanks for the pointers on 
list comprehensions though, I've managed to go through and simplify 
quite a few bits of code based on that. I'm a little embarrased about 
all the len() now. :)

From steve at pearwood.info  Mon Sep 27 19:34:35 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 03:34:35 +1000
Subject: [Tutor] function with multiple checks
In-Reply-To: <4CA0B3C2.8020206@lashni.net>
References: <4CA0B3C2.8020206@lashni.net>
Message-ID: <201009280334.36318.steve@pearwood.info>

On Tue, 28 Sep 2010 01:09:54 am Tim Miller wrote:

> def complex_password(password):
>      """Checks password for sufficient complexity."""
>      if len(password) < 12:
>          return False
>      if len([c for c in password if c in punctuation]) == 0:
>          return False
>      if len([c for c in password if c in digits]) == 0:
>          return False
>      if len([c for c in password if c in ascii_uppercase]) == 0:
>          return False
>      if len([c for c in password if c in ascii_lowercase]) == 0:
>          return False
>      return True

def complex_password(password):
    return ( 
    len(password) >= 12 and
    any(c in punctuation for c in password) and
    any(c in digits for c in password) and
    any(c in ascii_uppercase for c in password) and
    any(c in ascii_lowercase for c in password)
    )



-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 27 19:49:50 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 03:49:50 +1000
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTi=1qSX+NRqUWtFDAVDE0ukGhGrsK1MvO9RyCLEP@mail.gmail.com>
	<AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
Message-ID: <201009280349.50462.steve@pearwood.info>

On Tue, 28 Sep 2010 01:45:56 am Brian Jones wrote:

> A python list and a python array are one and the same to my
> knowledge.

Close, but not quite.

Python has an array type. It is almost identical to lists, except the 
type of data it will hold is constrained to a specific type:

>>> import array
>>> a = array.array('i')
>>> a.append(42)
>>> a
array('i', [42])
>>> a.append("spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required



-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 27 19:52:23 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 03:52:23 +1000
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTikE9ONt=XdACZTRAGd4pJbL7MnE-UgKRj5xyZAZ@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
	<AANLkTikE9ONt=XdACZTRAGd4pJbL7MnE-UgKRj5xyZAZ@mail.gmail.com>
Message-ID: <201009280352.24063.steve@pearwood.info>

On Tue, 28 Sep 2010 02:12:55 am Joel Goldstick wrote:

> a=[]
> i=0
> for l in open("file.txt", "r"):
>  a[i]=l
>   i+=1

Did you try it before posting?



-- 
Steven D'Aprano

From mehgcap at gmail.com  Mon Sep 27 19:54:55 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 13:54:55 -0400
Subject: [Tutor] filling 2d array with zeros
Message-ID: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>

Hi again everyone,
I have a 2d array (I guess it is technically a list) which I want to
fill with zeros. Later I will change some values, but any I do not
change have to be zeros. I have two complex for loops, but I tried to
scale things down to a couple list comprehensions and I broke things.
What is wrong with the following line?
self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
range(len(self.lines)) b=0]

self.lines is another array that tells self.am how big to get, but no
matter the size, all created cells of the self.am 2d array should end
up with a value of 0. I barely understand list comprehensions as it is
so am not sure what I did wrong here. I adapted this from a working
example that fills a 2d array with numbers.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From steve at pearwood.info  Mon Sep 27 19:55:25 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 03:55:25 +1000
Subject: [Tutor] dynamic arrays?
In-Reply-To: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
Message-ID: <201009280355.26193.steve@pearwood.info>

On Tue, 28 Sep 2010 01:32:32 am Alex Hall wrote:
> Hi all,
> One thing I have never much liked about Python is its need for
> specifically sized arrays and lack of a dynamic, array-like data
> structure.

Python lists are dynamically sized. If you compare Python to languages 
with fixed-size arrays, like Pascal, you will see the difference: fixed 
arrays are, well, fixed. You declare their size, and then they can 
never change, either increase or decrease. Python lists can do both.

You can increase their size using:

* the append method
* the extend method
* the insert method
* slice assignment

or you can decrease their size using:

* the del statement
* slice assignment



-- 
Steven D'Aprano

From roberto03 at gmail.com  Mon Sep 27 20:02:28 2010
From: roberto03 at gmail.com (roberto)
Date: Mon, 27 Sep 2010 20:02:28 +0200
Subject: [Tutor] function error
Message-ID: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>

hello,
i have the following error when i call this function:
   20 def outOfBounds():
---> 21         if abs(turtle.position()[0]) >
turtle.window_height()/2 or abs(turtle.position()[1]) >
turtle.window_width()/2:
     22                 return "true"
     23         else:

TypeError: 'function' object is unsubscriptable

but i can't really figure out where is the problem with this function
'unsubscriptable';
i know it may be something regarding turtle.position returning a list

can you help me with some hint ?

thank you
-- 
roberto

From modulok at gmail.com  Mon Sep 27 20:03:17 2010
From: modulok at gmail.com (Modulok)
Date: Mon, 27 Sep 2010 12:03:17 -0600
Subject: [Tutor] unittest testing order...
Message-ID: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>

List,

When using the unittest module, tests are run in alphanumeric order.
What's the suggested way of specifying a test order? Any code examples
would be great!

Thanks
-Modulok-

From joel.goldstick at gmail.com  Mon Sep 27 20:03:30 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 27 Sep 2010 14:03:30 -0400
Subject: [Tutor] dynamic arrays?
In-Reply-To: <201009280352.24063.steve@pearwood.info>
References: <AANLkTik125yby=0V+whxwsFpSyLMArVb4PfRYFit3kQ3@mail.gmail.com>
	<AANLkTi=U4+SuVM5P7ddTesEeTr8sT7DoQmHpgT2ff_2s@mail.gmail.com>
	<AANLkTikE9ONt=XdACZTRAGd4pJbL7MnE-UgKRj5xyZAZ@mail.gmail.com>
	<201009280352.24063.steve@pearwood.info>
Message-ID: <AANLkTi=HZXQa-WKQejVAmpW4TjSszCaF5GEEkLeVdNNe@mail.gmail.com>

On Mon, Sep 27, 2010 at 1:52 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 02:12:55 am Joel Goldstick wrote:
>
>> a=[]
>> i=0
>> for l in open("file.txt", "r"):
>> ?a[i]=l
>> ? i+=1
>
> Did you try it before posting?
>
That is a copy of the OP post.  and it shows what didn't work

I deleted in my post, then realized I needed it for example, so cut
and pasted.  But, to answer your question, that code gives and
exception

Joel Goldstick
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick

From joel.goldstick at gmail.com  Mon Sep 27 20:08:39 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 27 Sep 2010 14:08:39 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
Message-ID: <AANLkTik0uxO1D9cTcdMr=eeUCMUYKcr_qRgXv5zCXQ9f@mail.gmail.com>

On Mon, Sep 27, 2010 at 1:54 PM, Alex Hall <mehgcap at gmail.com> wrote:
> Hi again everyone,
> I have a 2d array (I guess it is technically a list) which I want to
> fill with zeros. Later I will change some values, but any I do not
> change have to be zeros. I have two complex for loops, but I tried to
> scale things down to a couple list comprehensions and I broke things.
> What is wrong with the following line?
> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
> range(len(self.lines)) b=0]
>
> self.lines is another array that tells self.am how big to get, but no
> matter the size, all created cells of the self.am 2d array should end
> up with a value of 0. I barely understand list comprehensions as it is
> so am not sure what I did wrong here. I adapted this from a working
> example that fills a 2d array with numbers.
>
> --
> Have a great day,
> Alex (msg sent from GMail website)
> mehgcap at gmail.com; http://www.facebook.com/mehgcap
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

I don't know how you are figuring out your size, but if you note
below, you can create a list with one element value 0, then multiply
it by length you need and result is than length of array filled with
0s


 x = [0] * 4
>>> x
[0, 0, 0, 0]

-- 
Joel Goldstick

From steve at pearwood.info  Mon Sep 27 20:29:49 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 04:29:49 +1000
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
Message-ID: <201009280429.50252.steve@pearwood.info>

On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote:
> Hi again everyone,
> I have a 2d array (I guess it is technically a list) which I want to
> fill with zeros. Later I will change some values, but any I do not
> change have to be zeros. I have two complex for loops, but I tried to
> scale things down to a couple list comprehensions and I broke things.
> What is wrong with the following line?
> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
> range(len(self.lines)) b=0]


Start with a single row, of n columns:

[0 for i in range(n)]  # the loop variable i is not used

Now all you need is to set n appropriately:

n = len(self.lines)
[0 for i in range(n)]


Is there an easier way? Yes, you don't even need a list comp:

[0]*n

Now make m rows of the same:

[ [0]*n for i in range(m) ]

And you are done.


You might be tempted to take a short-cut:

[ [0]*n ]*m

but this doesn't work as you expect. This is one of the rare Python 
gotchas -- it looks like it should work, but it doesn't behave like you 
might expect. Try it and see:

>>> a = [[0]*3]*4
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][1] = 2
>>> a
[[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]

What's going on here? It's a little complicated, so let's start with a 
simpler situation:

>>> b = [0, 0, 0]
>>> c = b  # c is an alias to the same list as b
>>> d = b  # so is d
>>> e = c  # and e
>>> b[0] = 3
>>> e
[3, 0, 0]

Because both b and e refer to the same list (not copies!) any change to 
b *must* also change e. It's like if Barack Obama gets a haircut, so 
does the current President of the USA, because they're the same person.

Now stick them in a list:

>>> a = [b, c, d, e]
>>> a
[[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]]
>>> a[0][1] = 4
>>> a
[[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]]

Modify one, modify them all, because in fact they are actually all the 
same list.

[ [0]*3 ]*4 behaves the same way. There's no problem in the inner list, 
but the outer list doesn't make four copies of [0,0,0], it has *one* 
list repeated four times. Modify one, modify them all.


-- 
Steven D'Aprano

From steve at pearwood.info  Mon Sep 27 20:33:34 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 04:33:34 +1000
Subject: [Tutor] unittest testing order...
In-Reply-To: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>
References: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>
Message-ID: <201009280433.35742.steve@pearwood.info>

On Tue, 28 Sep 2010 04:03:17 am Modulok wrote:
> List,
>
> When using the unittest module, tests are run in alphanumeric order.
> What's the suggested way of specifying a test order? 

There isn't one. It shouldn't matter what order the tests run, no test 
should *rely* on another test. 

(Although of course, if one test fails, any tests which assume the 
missing functionality will also fail.)



-- 
Steven D'Aprano

From Joel.Levine at Dartmouth.EDU  Mon Sep 27 20:34:05 2010
From: Joel.Levine at Dartmouth.EDU (Joel Levine)
Date: 27 Sep 2010 14:34:05 -0400
Subject: [Tutor] dynamic arrays?
Message-ID: <150950550@newdancer.Dartmouth.EDU>

I'm guessing you are also using numpy and that you want arrays (or matrices) for  
the sake of either (a) matrix and array functions or (b) much greater processing  
speed.

Add
from numpy import *

Then hat you can do is go back and forth:  Build what you intend to be an array,  
but build it as a list using append.

then ar=array(list)

converts it.

If you want to change its size again, convert it back to a list, change it, convert  
it back to an array.

The functions you need are list(), array(), and possibly matrix()


>>>  from numpy import *
>>>  a=[1,2,3]
>>>  type(a)
<type 'list'>
>>>  ar=array(a)
>>>  ar
array([1, 2, 3])
>>>  matrix(ar)
matrix([[1, 2, 3]])
>>>  type(ar)
<type 'numpy.ndarray'>
>>>  

From emile at fenx.com  Mon Sep 27 21:12:34 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 27 Sep 2010 12:12:34 -0700
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
Message-ID: <i7qqau$g9k$1@dough.gmane.org>

On 9/27/2010 10:54 AM Alex Hall said...
> What is wrong with the following line?
> self.am=[[(a,b)
>   for a in range(len(self.lines)) a=0]
>   for b in range(len(self.lines)) b=0]

The a=0 and b=0 -- what do you think they're doing?

Emile





From evert.rol at gmail.com  Mon Sep 27 21:16:37 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 27 Sep 2010 21:16:37 +0200
Subject: [Tutor] unittest testing order...
In-Reply-To: <201009280433.35742.steve@pearwood.info>
References: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>
	<201009280433.35742.steve@pearwood.info>
Message-ID: <5F841C79-C78D-4EC1-86BA-B57565FBCCD6@gmail.com>

>> List,
>> 
>> When using the unittest module, tests are run in alphanumeric order.
>> What's the suggested way of specifying a test order? 
> 
> There isn't one. It shouldn't matter what order the tests run, no test 
> should *rely* on another test. 
> 
> (Although of course, if one test fails, any tests which assume the 
> missing functionality will also fail.)

Steven is right that unittests should be independent. 

I did once, however, come across an option to order the tests. Scanning through the unittest docs, I found "sortTestMethodsUsing":

"Function to be used to compare method names when sorting them in getTestCaseNames() and all the loadTestsFrom*() methods. The default value is the built-in cmp() function; the attribute can also be set to None to disable the sort."

Perhaps that does what you want. But I would indeed not recommend it.

  Evert


From knacktus at googlemail.com  Mon Sep 27 21:19:34 2010
From: knacktus at googlemail.com (Knacktus)
Date: Mon, 27 Sep 2010 21:19:34 +0200
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <201009280429.50252.steve@pearwood.info>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
Message-ID: <4CA0EE46.7030303@googlemail.com>

Am 27.09.2010 20:29, schrieb Steven D'Aprano:
> On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote:
>> Hi again everyone,
>> I have a 2d array (I guess it is technically a list) which I want to
>> fill with zeros. Later I will change some values, but any I do not
>> change have to be zeros. I have two complex for loops, but I tried to
>> scale things down to a couple list comprehensions and I broke things.
>> What is wrong with the following line?
>> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
>> range(len(self.lines)) b=0]
>
>
> Start with a single row, of n columns:
>
> [0 for i in range(n)]  # the loop variable i is not used
>
> Now all you need is to set n appropriately:
>
> n = len(self.lines)
> [0 for i in range(n)]
>
>
> Is there an easier way? Yes, you don't even need a list comp:
>
> [0]*n
>
> Now make m rows of the same:
>
> [ [0]*n for i in range(m) ]
>
> And you are done.
>
>
> You might be tempted to take a short-cut:
>
> [ [0]*n ]*m
>
> but this doesn't work as you expect. This is one of the rare Python
> gotchas -- it looks like it should work, but it doesn't behave like you
> might expect. Try it and see:
>
>>>> a = [[0]*3]*4
>>>> a
> [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>> a[0][1] = 2
>>>> a
> [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
>
> What's going on here? It's a little complicated, so let's start with a
> simpler situation:
>
>>>> b = [0, 0, 0]
>>>> c = b  # c is an alias to the same list as b
>>>> d = b  # so is d
>>>> e = c  # and e
>>>> b[0] = 3
>>>> e
> [3, 0, 0]
>
> Because both b and e refer to the same list (not copies!) any change to
> b *must* also change e. It's like if Barack Obama gets a haircut, so
> does the current President of the USA, because they're the same person.
>
> Now stick them in a list:
>
>>>> a = [b, c, d, e]
>>>> a
> [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]]
>>>> a[0][1] = 4
>>>> a
> [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]]
>
> Modify one, modify them all, because in fact they are actually all the
> same list.
>
> [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list,
> but the outer list doesn't make four copies of [0,0,0], it has *one*
> list repeated four times. Modify one, modify them all.
>
>
Another extremly helpful explanation for every learner watching the 
mailing list. Steven, you really deserve the golden tutor medal of honor!

Cheers,

Jan

P.S.: You other guys are awesome as well. Amazing mailing list...

From mehgcap at gmail.com  Mon Sep 27 22:00:41 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 16:00:41 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <201009280429.50252.steve@pearwood.info>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
Message-ID: <AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>

On 9/27/10, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote:
>> Hi again everyone,
>> I have a 2d array (I guess it is technically a list) which I want to
>> fill with zeros. Later I will change some values, but any I do not
>> change have to be zeros. I have two complex for loops, but I tried to
>> scale things down to a couple list comprehensions and I broke things.
>> What is wrong with the following line?
>> self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
>> range(len(self.lines)) b=0]
>
>
> Start with a single row, of n columns:
>
> [0 for i in range(n)]  # the loop variable i is not used
>
> Now all you need is to set n appropriately:
>
> n = len(self.lines)
> [0 for i in range(n)]
>
>
> Is there an easier way? Yes, you don't even need a list comp:
>
> [0]*n
>
> Now make m rows of the same:
>
> [ [0]*n for i in range(m) ]
That worked, and I think I see what is going on.
>
> And you are done.
>
>
> You might be tempted to take a short-cut:
>
> [ [0]*n ]*m
>
> but this doesn't work as you expect. This is one of the rare Python
> gotchas -- it looks like it should work, but it doesn't behave like you
> might expect. Try it and see:
>
>>>> a = [[0]*3]*4
>>>> a
> [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>> a[0][1] = 2
>>>> a
> [[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]
>
> What's going on here? It's a little complicated, so let's start with a
> simpler situation:
>
>>>> b = [0, 0, 0]
>>>> c = b  # c is an alias to the same list as b
>>>> d = b  # so is d
>>>> e = c  # and e
>>>> b[0] = 3
>>>> e
> [3, 0, 0]
>
> Because both b and e refer to the same list (not copies!) any change to
> b *must* also change e. It's like if Barack Obama gets a haircut, so
> does the current President of the USA, because they're the same person.
>
> Now stick them in a list:
>
>>>> a = [b, c, d, e]
>>>> a
> [[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]]
>>>> a[0][1] = 4
>>>> a
> [[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]]
>
> Modify one, modify them all, because in fact they are actually all the
> same list.
>
> [ [0]*3 ]*4 behaves the same way. There's no problem in the inner list,
> but the outer list doesn't make four copies of [0,0,0], it has *one*
> list repeated four times. Modify one, modify them all.
That makes sense. Basically, the * operator in this case acts as a
copying command. For simple data types this is fine, but throw in a
complex type, in this case a list (though I expect that any object
would do this) and you are just doing what Python does to copy
objects: copying the memory location, not making a deep copy and
getting a duplicate object. I never would have thought of that. Thanks
again for the great explanation!
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From norman at khine.net  Mon Sep 27 22:22:52 2010
From: norman at khine.net (Norman Khine)
Date: Mon, 27 Sep 2010 22:22:52 +0200
Subject: [Tutor] if value in list of dictionaries
Message-ID: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>

hello, i have a list which is generated from a csv file:

options = [
	{'industry': 'travel', 'name': 'owner-director','value':
MSG(u"Owner/Director")},
	{'industry': 'travel', 'name': 'manager','value': MSG(u"Manager")},
	{'industry': 'travel', 'name': 'assistant-manager','value':
MSG(u"Assistant Manager")},
	{'industry': 'travel', 'name': 'travel-consultant','value':
MSG(u"Travel Consultant")},
	{'industry': 'travel', 'name': 'managing-director','value':
MSG(u"Managing Director")},
	{'industry': 'travel', 'name': 'sales-director','value': MSG(u"Sales
Director")},
	{'industry': 'travel', 'name': 'marketing-director','value':
MSG(u"Marketing Director")},
	{'industry': 'travel', 'name': 'marketing-manager','value':
MSG(u"Marketing Manager")},
	{'industry': 'travel', 'name': 'marketing-assistant','value':
MSG(u"Marketing Assistant")},
	{'industry': 'travel', 'name': 'product-manager','value':
MSG(u"Product Manager")},
	{'industry': 'travel', 'name': 'reservation-staff','value':
MSG(u"Reservation Staff")},
	{'industry': 'travel', 'name': 'student','value': MSG(u"Student")},
	{'industry': 'travel', 'name': 'other','value': MSG(u"Other")}]

what is the correct way to ensure that {'industry': 'travel', 'name':
'other','value': MSG(u"Other")} is always added to the end of this
list after all the items have been sorted?

here is the code which returns this list:

http://pastie.org/1185024

thanks

-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From sander.sweers at gmail.com  Mon Sep 27 23:15:20 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 27 Sep 2010 23:15:20 +0200
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
	<AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
Message-ID: <AANLkTikaCW8pkbFNb5=mL9RpkLRkh+pZ0FCtL4e-G0Ca@mail.gmail.com>

On 27 September 2010 22:00, Alex Hall <mehgcap at gmail.com> wrote:
> That makes sense. Basically, the * operator in this case acts as a
> copying command. For simple data types this is fine, but throw in a
> complex type, in this case a list (though I expect that any object
> would do this) and you are just doing what Python does to copy
> objects: copying the memory location, not making a deep copy and
> getting a duplicate object.

It does not copy the object it makes multiple _references_ to the *same* object.

So let's say you have a list [1,2,3] with variable a which is a list
object containing 3 integer objects. Following Steven?s example you
basically create a new list with 3 references to the first list with
variable a. You could just as well have written it as [a,a,a] which is
the same as [a] * 3.

>>> a = [1,2,3]
>>> b = [a,a,a]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[10, 2, 3], [10, 2, 3], [10, 2, 3]]

The next step is how do we create a real copy of the object instead of
a new reference to the same object. There are multiple methods to
create a copy.

The easiest is using a slice. A slice returns (in this example) a
*new* list with all the values.
>>> b = [a[:],a[:],a[:]]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[0][0] = 10
>>> b
[[10, 2, 3], [1, 2, 3], [1, 2, 3]]

Or use the copy modules to do the same, see help(copy) for more info.
>>> import copy
>>> a = [1,2,3]
>>> b = [copy.copy(a), copy.copy(a), copy.copy(a)]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> a[0] = 10
>>> a
[10, 2, 3]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[0][0] = 10
>>> b
[[10, 2, 3], [1, 2, 3], [1, 2, 3]]

copy.copy(a) is what we call a shallow copy. It only make a copy of
the list object a. But what if list object a again contained 3 list
objects? You then run into the same problem as before.

>>> a = [[1,2],[3,4],[5,6]]
>>> b = [copy.copy(a), copy.copy(a), copy.copy(a)]
>>> b
[[[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]], [[1, 2], [3, 4], [5, 6]]]
>>> a[0][0] = 10
>>> b
[[[10, 2], [3, 4], [5, 6]], [[10, 2], [3, 4], [5, 6]], [[10, 2], [3,
4], [5, 6]]]

For this you can use copy.deepcopy() which make sure you create a copy
of each object (in this case lists).

I found this was one of the most weird things I needed to understand
about python.

Hope this helps.

Greets
Sander

From sander.sweers at gmail.com  Mon Sep 27 23:38:59 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 27 Sep 2010 23:38:59 +0200
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTikaCW8pkbFNb5=mL9RpkLRkh+pZ0FCtL4e-G0Ca@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
	<AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
	<AANLkTikaCW8pkbFNb5=mL9RpkLRkh+pZ0FCtL4e-G0Ca@mail.gmail.com>
Message-ID: <AANLkTik-a-+f2waMoQaryLaYV0zTX8NuCyQHdK4wa3Cv@mail.gmail.com>

On 27 September 2010 23:15, Sander Sweers <sander.sweers at gmail.com> wrote:
>> objects: copying the memory location, not making a deep copy and
>> getting a duplicate object.
>
> It does not copy the object it makes multiple _references_ to the *same* object.

Oops, You already got the idea and I should have read better. Ow well,
maybe the copy module was of interest to you.

Greets
Sander

From emile at fenx.com  Mon Sep 27 23:39:52 2010
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 27 Sep 2010 14:39:52 -0700
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
Message-ID: <i7r2v6$bg2$1@dough.gmane.org>

On 9/27/2010 1:22 PM Norman Khine said...

> what is the correct way to ensure that {'industry': 'travel', 'name':
> 'other','value': MSG(u"Other")} is always added to the end of this
> list after all the items have been sorted?
>
> here is the code which returns this list:

    options.sort(key=itemgetter('name'))
    return options

So, to answer the question you ask above, you can do:

    options.sort(key=itemgetter('name'))
    options.append({'industry':'travel',
       'name':'other','value':MSG(u"Other")}
    return options

But I don't think that's the question you're looking to get answered.

I think you want "other" to be found only at the end and not elsewhere.

Then you might try excluding other from options allowing the above to 
append it to the end:

for index, row in enumerate(topics.get_rows()):
     if row[0] != 'other':
         options.append({'name': row[0], 'value': MSG(row[1])})

HTH,

Emile

		


From modulok at gmail.com  Tue Sep 28 00:07:30 2010
From: modulok at gmail.com (Modulok)
Date: Mon, 27 Sep 2010 16:07:30 -0600
Subject: [Tutor] unittest testing order...
In-Reply-To: <201009280433.35742.steve@pearwood.info>
References: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>
	<201009280433.35742.steve@pearwood.info>
Message-ID: <AANLkTik_+htfZXSz8K9M8Lm0V_Qysd+cdQqH58P2NYdE@mail.gmail.com>

On 9/27/10, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 04:03:17 am Modulok wrote:
>> List,
>>
>> When using the unittest module, tests are run in alphanumeric order.
>> What's the suggested way of specifying a test order?
>
> There isn't one. It shouldn't matter what order the tests run, no test
> should *rely* on another test.
>
> (Although of course, if one test fails, any tests which assume the
> missing functionality will also fail.)

In an ideal world, I agree. This is possible for pure functional
programming where state is avoided. However, when dealing with object
oriented, imperative programming, state changes cannot be avoided.
Thus if a method requires an object be passed to it, I'd like to
verify that object is being constructed correctly by the object
factory, before verifying that the method which uses said object, is
correct.

Or is there some other way of doing this? I'm new to unittesting.

Thanks!
-Modulok-

From steve at alchemy.com  Tue Sep 28 00:20:41 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 27 Sep 2010 15:20:41 -0700
Subject: [Tutor] unittest testing order...
In-Reply-To: <AANLkTik_+htfZXSz8K9M8Lm0V_Qysd+cdQqH58P2NYdE@mail.gmail.com>
References: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>	<201009280433.35742.steve@pearwood.info>
	<AANLkTik_+htfZXSz8K9M8Lm0V_Qysd+cdQqH58P2NYdE@mail.gmail.com>
Message-ID: <4CA118B9.30705@alchemy.com>

On 27-Sep-10 15:07, Modulok wrote:
> In an ideal world, I agree. This is possible for pure functional
> programming where state is avoided. However, when dealing with object
> oriented, imperative programming, state changes cannot be avoided.

Generally, a unit test should test a single aspect of a single unit of 
your program.  This is used all the time in object oriented programming. 
  You set up an object (or collection of them), set up an initial state, 
test the behavior, and tear it down again.  The state should not affect 
the assumptions of any other unit test.

> Thus if a method requires an object be passed to it, I'd like to
> verify that object is being constructed correctly by the object
> factory, before verifying that the method which uses said object, is
> correct.

No problem.  The object's constructor will have a number of unit tests 
of its own to ensure objects are constructed correctly, and the method 
has unit tests for them which test various cases about their behavior, etc.

I suggest picking up a good book or two about unit testing so you get 
off to the right foot about how this is usually done.  I'm not sure 
you're seeing the complete point of this.


From carter.danforth at gmail.com  Tue Sep 28 00:55:36 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Mon, 27 Sep 2010 18:55:36 -0400
Subject: [Tutor] generating independent random numbers
Message-ID: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>

Hi, I'm writing a program that's testing speed calculation of calendar dates
from any date spanning 1600-3000. I want it to generate a random date and
then prompt the user to indicate the correct day of the week using Zeller's
formula.

Included below is just some of the code to show what I'm having trouble
with. The variables that need to be randomly called each time (in this case,
5 times) are c, y, month, and k (I use these inputs to get the value and
assign the date with Zeller's formula, not included below).

Problem I'm having is that on each while loop, those variables stay
constant. I'm not sure how to make the class independently random. How can I
change this with random so that on each while loop c, y, month, and k also
have different values?

Thanks

-----------------------------------------------------------------------------------

import random, calendar

class Date:
    c = random.randint(16,30)
    y = random.randint(0,99)
    month = random.randint(1,12)

    apr = [4,6,9,11]
    feb = [2]

    if month in feb:
        if y%4 == 0:
            k = random.randint(1,29)
        else:
            k = random.randint(1,28)
    elif month in apr:
        k = random.randint(1,30)
    else:
        k = random.randint(1,31)

n = 0
while n < 5:
    Date()
    year = Date.c*100 + Date.y

    print '\n',calendar.month_name[Date.month], Date.k,',', year,'=',
    answer = raw_input()
    n+=1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/c1f18a55/attachment.html>

From mehgcap at gmail.com  Tue Sep 28 01:38:23 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 19:38:23 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTik-a-+f2waMoQaryLaYV0zTX8NuCyQHdK4wa3Cv@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
	<AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
	<AANLkTikaCW8pkbFNb5=mL9RpkLRkh+pZ0FCtL4e-G0Ca@mail.gmail.com>
	<AANLkTik-a-+f2waMoQaryLaYV0zTX8NuCyQHdK4wa3Cv@mail.gmail.com>
Message-ID: <AANLkTi=VOdf0_vtcaxpNL2VvB21AgSWZkeSub__ivyJ=@mail.gmail.com>

On 9/27/10, Sander Sweers <sander.sweers at gmail.com> wrote:
> On 27 September 2010 23:15, Sander Sweers <sander.sweers at gmail.com> wrote:
>>> objects: copying the memory location, not making a deep copy and
>>> getting a duplicate object.
>>
>> It does not copy the object it makes multiple _references_ to the *same*
>> object.
>
> Oops, You already got the idea and I should have read better. Ow well,
> maybe the copy module was of interest to you.
Yes, very much. I never even knew such a module existed, and I had
wondered, through all of this, what would happen when a deep copy was
required. Now I know. :)
>
> Greets
> Sander
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From rdmoores at gmail.com  Tue Sep 28 02:26:02 2010
From: rdmoores at gmail.com (Richard D. Moores)
Date: Mon, 27 Sep 2010 17:26:02 -0700
Subject: [Tutor] IPython: trouble setting an editor
Message-ID: <AANLkTik6egu0mgHzmNmc0KoxzVeA4aDXTji7HqYq8dyX@mail.gmail.com>

64-bit Vista
Python 2.6 for IPython 0.10
I also have Python 2.7 and 3.1

I'd like to use the version of IDLE that comes with Python 2.6.
However, if I have the line

ipy_editors.idle()

in my ipy_user_conf.py,

And enter   edit,

What opens is the IDLE for Python 3.1.

So, in imitation of this line in ipy_user_conf.py:

#ipy_editors.scite('c:/opt/scite/scite.exe') ,

I swapped out the above line for

ipy_editors.idle("c:/Python26/Lib/idlelib/idle.pyw")

and now when I enter

ed fact.py,  or  just   ed ,? ? (fact.py is a script of mine that I
copied to C:Python26/Scripts)

the IDLE for Python 3.1 opens, all set to edit the SCRIPT
c:/Python26/Lib/idlelib/idle.pyw !

What's going on here? What do I have to do to use the Python 2.6
version of IDLE with IPython?

BTW entering   run fact.py    at the IPython prompt runs fact.py just fine.

Thanks,

Dick Moores

From steve at pearwood.info  Tue Sep 28 02:27:07 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 10:27:07 +1000
Subject: [Tutor] generating independent random numbers
In-Reply-To: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
Message-ID: <201009281027.08146.steve@pearwood.info>

On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote:

> class Date:
>     c = random.randint(16,30)
>     y = random.randint(0,99)
>     month = random.randint(1,12)

Here's your problem: you are creating a class where all the attributes 
(called "members" in some other languages) belong to the class and are 
shared by all instances.

Python classes are themselves objects, and the code inside the class 
body gets executed *once*, when the class is created. So in this case, 
the Date class chooses a single random month, *once*, and all instances 
share this attribute Date.month.

To get the behaviour you are after, you need to use instance attributes, 
which means referring to self. The usual place to do this is in the 
__init__ method, which is called when the instance is being 
initialised:

class Date:
    def __init__(self):
        self.month = random.randint(1,12)
        # etc.



By the way, why do you calculate a century and year separately, then add 
c+y to get the year? It would be easier to just say:

year = random.randint(1600, 3099)



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 02:46:20 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 10:46:20 +1000
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
	<AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
Message-ID: <201009281046.20681.steve@pearwood.info>

On Tue, 28 Sep 2010 06:00:41 am Alex Hall wrote:
> > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner
> > list, but the outer list doesn't make four copies of [0,0,0], it
> > has *one* list repeated four times. Modify one, modify them all.
>
> That makes sense. Basically, the * operator in this case acts as a
> copying command. For simple data types this is fine, but throw in a
> complex type, in this case a list (though I expect that any object
> would do this) and you are just doing what Python does to copy
> objects: copying the memory location, not making a deep copy and
> getting a duplicate object. I never would have thought of that.
> Thanks again for the great explanation!

No, be careful about your terminology. I get that you understand what is 
going on, but you're saying it wrong. The * operator doesn't make 
copies. I know it's tempting to say it does, sometimes I catch myself 
saying so myself, but what Python is doing is making multiple 
references to the same object. The object is not copied.

It may be easier if you think about the underlying C implementation 
(under the hood, in the engine) rather than the Python level. At the 
Python level, objects can be in multiple places at once. Objects like 
lists can even be inside themselves:

>>> L = []
>>> L.append(L)

If you've watched Doctor Who as a child, and seen his TARDIS (which of 
course is bigger on the inside than the outside) land inside itself, 
such strange loops won't hold any fear for you at all :)

But at the C level, Python doesn't make copies of any object unless 
necessary. The *name* L is a pointer to the list object. When you 
execute:

L = []

Python creates a name L which then points ("refers to") to a list 
object. When you next do this:

L.append(L)

Python doesn't move the list object into itself -- that would be a good 
trick. Besides, objects are big, complex chunks of memory and moving 
them around would be slow, so Python leaves the list where it is and 
simply places a pointer to L into the appropriate list position.

(But don't forget that Python is not necessarily written in C. There's 
Jython, written in Java, and CLPython written in Lisp, and many others. 
How they implement objects may be different. What happens under the 
hood isn't important, so long as the behaviour at the Python level 
remains the same.)

So at the Python level, there is never any copying of objects unless you 
specifically ask for it, and the * operator doesn't make any copies at 
all. It repeats the one object multiple times.


-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 02:47:39 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 10:47:39 +1000
Subject: [Tutor] unittest testing order...
In-Reply-To: <AANLkTik_+htfZXSz8K9M8Lm0V_Qysd+cdQqH58P2NYdE@mail.gmail.com>
References: <AANLkTik8nfRn3gc8H91XgkhHpQkkDWeTywPM4qiri32T@mail.gmail.com>
	<201009280433.35742.steve@pearwood.info>
	<AANLkTik_+htfZXSz8K9M8Lm0V_Qysd+cdQqH58P2NYdE@mail.gmail.com>
Message-ID: <201009281047.39567.steve@pearwood.info>

On Tue, 28 Sep 2010 08:07:30 am Modulok wrote:
> On 9/27/10, Steven D'Aprano <steve at pearwood.info> wrote:
> > On Tue, 28 Sep 2010 04:03:17 am Modulok wrote:
> >> List,
> >>
> >> When using the unittest module, tests are run in alphanumeric
> >> order. What's the suggested way of specifying a test order?
> >
> > There isn't one. It shouldn't matter what order the tests run, no
> > test should *rely* on another test.
> >
> > (Although of course, if one test fails, any tests which assume the
> > missing functionality will also fail.)
>
> In an ideal world, I agree. This is possible for pure functional
> programming where state is avoided. However, when dealing with object
> oriented, imperative programming, state changes cannot be avoided.
> Thus if a method requires an object be passed to it, I'd like to
> verify that object is being constructed correctly by the object
> factory, before verifying that the method which uses said object, is
> correct.

It is reasonable to write two tests:

test_construction # verify object is constructed correctly
test_method  # verify object is used correctly

But you shouldn't rely on the tests being *executed* in any specific 
order, just as you shouldn't rely on them being *written* in any 
specific order. You should be able to go back at any time and add an 
extra test:

test_special_construction

even though test_method already exists. Likewise because every test is 
independent, it doesn't matter whether test_construction executes 
before or after test_method, or even simultaneously! (An advanced 
testing infrastructure might execute each test in its own thread.)

Tests can have their own setup and teardown code. You should not put the 
setup code to test_method in test_construction -- they should be 
independent.


-- 
Steven D'Aprano

From Joel.Levine at Dartmouth.EDU  Tue Sep 28 02:33:33 2010
From: Joel.Levine at Dartmouth.EDU (Joel Levine)
Date: 27 Sep 2010 20:33:33 -0400
Subject: [Tutor] generating independent random numbers
Message-ID: <150970234@newdancer.Dartmouth.EDU>

You might try fixing up the following.  I did not match the scale to what you  
are looking for.  But the trick is to take advantage of the time module's association  
of numbers with dates:

import time
import random

""" Sample output

Wed Apr 29 14:35:58 1992
Thu Jun 24 12:04:15 1971
Fri Oct  7 01:29:28 1994
Wed Mar 23 10:33:14 1994
Sun Apr 12 12:17:56 1998
Wed May 12 06:41:33 1971
Mon Jun 15 09:15:31 1998
Fri Sep 14 18:26:22 1979
Fri Apr 28 00:55:57 1972
Fri Mar 26 00:43:12 2010
"""

def re_scale():


     now=float(time.time())
     early=1000000.
     rang=(now-early)
     return time.ctime((random.random())*rang+early)



for i in range(10):
     print re_scale()


From mehgcap at gmail.com  Tue Sep 28 03:56:33 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Mon, 27 Sep 2010 21:56:33 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <201009281046.20681.steve@pearwood.info>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009280429.50252.steve@pearwood.info>
	<AANLkTinOvUM8y68WRjVZ69wPoG5=unmNpqnzZ6w9D8LK@mail.gmail.com>
	<201009281046.20681.steve@pearwood.info>
Message-ID: <AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>

On 9/27/10, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 06:00:41 am Alex Hall wrote:
>> > [ [0]*3 ]*4 behaves the same way. There's no problem in the inner
>> > list, but the outer list doesn't make four copies of [0,0,0], it
>> > has *one* list repeated four times. Modify one, modify them all.
>>
>> That makes sense. Basically, the * operator in this case acts as a
>> copying command. For simple data types this is fine, but throw in a
>> complex type, in this case a list (though I expect that any object
>> would do this) and you are just doing what Python does to copy
>> objects: copying the memory location, not making a deep copy and
>> getting a duplicate object. I never would have thought of that.
>> Thanks again for the great explanation!
>
> No, be careful about your terminology. I get that you understand what is
> going on, but you're saying it wrong. The * operator doesn't make
> copies. I know it's tempting to say it does, sometimes I catch myself
> saying so myself, but what Python is doing is making multiple
> references to the same object. The object is not copied.
Yes; the object stays put, the object's memory location (pointer) is
copied. I have just enough c++ and theory to get this, and enough to
be scared of it and very thankful that Python deals with it for me
instead of me needing all those ampersand and star operators in front
of variables... That was a nightmare, and I came running back to my
high-level languages in a hurry. :)
>
> It may be easier if you think about the underlying C implementation
> (under the hood, in the engine) rather than the Python level. At the
> Python level, objects can be in multiple places at once. Objects like
> lists can even be inside themselves:
>
>>>> L = []
>>>> L.append(L)
>
> If you've watched Doctor Who as a child, and seen his TARDIS (which of
> course is bigger on the inside than the outside) land inside itself,
> such strange loops won't hold any fear for you at all :)
>
> But at the C level, Python doesn't make copies of any object unless
> necessary. The *name* L is a pointer to the list object. When you
> execute:
>
> L = []
>
> Python creates a name L which then points ("refers to") to a list
> object. When you next do this:
>
> L.append(L)
>
> Python doesn't move the list object into itself -- that would be a good
> trick. Besides, objects are big, complex chunks of memory and moving
> them around would be slow, so Python leaves the list where it is and
> simply places a pointer to L into the appropriate list position.
Makes sense, but I never thought of this as being possible, let alone
legal. Still, though I cannot imagine a situation where it would be
necessary, I am sure someone has used it somewhere. A very interesting
thing to think about; a single-element list holding... itself. Yep,
very interesting! Now I wish I were more of a sci fi buff. :)
>
> (But don't forget that Python is not necessarily written in C. There's
> Jython, written in Java, and CLPython written in Lisp, and many others.
> How they implement objects may be different. What happens under the
> hood isn't important, so long as the behaviour at the Python level
> remains the same.)
Really? Neat! I wonder what the advantage of doing that is, since the
end result, as you say, should be the same once you start writing
Python code?
>
> So at the Python level, there is never any copying of objects unless you
> specifically ask for it, and the * operator doesn't make any copies at
> all. It repeats the one object multiple times.
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From davea at ieee.org  Tue Sep 28 04:21:41 2010
From: davea at ieee.org (Dave Angel)
Date: Mon, 27 Sep 2010 22:21:41 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <201009281027.08146.steve@pearwood.info>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
Message-ID: <4CA15135.3050506@ieee.org>



On 2:59 PM, Steven D'Aprano wrote:
> On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote:
>
>> class Date:
>>      c = random.randint(16,30)
>>      y = random.randint(0,99)
>>      month = random.randint(1,12)
> Here's your problem: you are creating a class where all the attributes
> (called "members" in some other languages) belong to the class and are
> shared by all instances.
>
> Python classes are themselves objects, and the code inside the class
> body gets executed *once*, when the class is created. So in this case,
> the Date class chooses a single random month, *once*, and all instances
> share this attribute Date.month.
>
> To get the behaviour you are after, you need to use instance attributes,
> which means referring to self. The usual place to do this is in the
> __init__ method, which is called when the instance is being
> initialised:
>
> class Date:
>      def __init__(self):
>          self.month = random.randint(1,12)
>          # etc.
>
>
>
> By the way, why do you calculate a century and year separately, then add
> c+y to get the year? It would be easier to just say:
>
> year = random.randint(1600, 3099)
>
>
>
That's the big problem, although it's also worth pointing out that 
you'll need a new instance each time through the loop.  It's not enough 
to call Date(), you also have to bind it to a name, and use that name 
for attribute lookup.    So something like
     mydate = Date()
     year = mydate.y + ....

But there are at least a few subtle problems left.  One is that many of 
the years are divisible by four but do not have 29 days in February.  
For example, 1800, 1900, 2100 are not leap years.

Next problem is that the dates are not evenly distributed over the 
entire range of years.  The 14th of February will be more likely to be 
chosen than the sixth of July.  You can decide that this is deliberate, 
but it is a consideration.

Third, the program doesn't do anything to check the user's answer.  For 
that matter, there's no timing going on either.

Depending on the learning goals of this project, I'd consider using the 
datetime module, and method:

mydate = date.fromordinal(/ordinal/)

Now you can make a single randint() call, once you precalculate the 
starting and ending dates desired.   And this module also gives you 
other things you need, such as the weekday() method.

DaveA

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/db9177ef/attachment-0001.html>

From wallenpb at gmail.com  Tue Sep 28 05:57:23 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Mon, 27 Sep 2010 22:57:23 -0500
Subject: [Tutor] list comprehension, efficiency?
Message-ID: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>

I have seen list comprehensions used, but have not quite got the hang of it
yet.
So, I was writing a bit of code to do some work with file directories and
decided
to give it a try as follows:

list_c = os.listdir("c:")

#first code written in the way I usually would.
dirs = []
for x in list_c:
    if os.path.isdir(x):
        dirs.append(x)

#replaced the above code with the following list comprehension, it worked as
expected:
dirs = [x for x in list_c if os.path.isdir(x)]

I can now see that quite a bit of the code I write dealing with lists can be
done with list
comprehensions.   My question is this, is the list comprehension styled code
generally
more efficient at runtime?  If so, why?

--Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/11ec90c0/attachment.html>

From mass02gh at yahoo.ca  Tue Sep 28 06:15:52 2010
From: mass02gh at yahoo.ca (masawudu bature)
Date: Mon, 27 Sep 2010 21:15:52 -0700 (PDT)
Subject: [Tutor] Python Help
Message-ID: <765790.84633.qm@web58508.mail.re3.yahoo.com>

I'm having a hard time finding the count of divisors that are even. Help 
anybody?

Here's my code.

The output is suppose to count the number of even divisors the range has.

def evenCount(b) :
    for n in range(x, y+1) :
        count = 0
        if n % 2 == 0 :
            count += n/3
            count % n == 1
        return n


### main ####

x = input("Enter a starting value: ")
y = input("Enter a stopping value: ")

count = evenCount(x)

for n in range(x, y+1) :
    count = 0
    if n % 2 == 0 :
        count += n/3
        print "%2d: " %n, "has%2d" %count, "even divisors",
    else :
        print "%2d: " %n, "has 0 even divisors",
    print


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/28274bb3/attachment.html>

From smokefloat at gmail.com  Tue Sep 28 06:36:05 2010
From: smokefloat at gmail.com (David Hutto)
Date: Tue, 28 Sep 2010 00:36:05 -0400
Subject: [Tutor] Python Help
In-Reply-To: <765790.84633.qm@web58508.mail.re3.yahoo.com>
References: <765790.84633.qm@web58508.mail.re3.yahoo.com>
Message-ID: <AANLkTi==109eCXfJ6t090FvDJsug1kbCdNtTKZnzwCqC@mail.gmail.com>

On Tue, Sep 28, 2010 at 12:15 AM, masawudu bature <mass02gh at yahoo.ca> wrote:
> I'm having a hard time finding the count of divisors that are even. Help
> anybody?
>
> Here's my code.
>
> The output is suppose to count the number of even divisors the range has.
>
> def evenCount(b) :
> ??? for n in range(x, y+1) :
> ??????? count = 0
> ??????? if n % 2 == 0 :
> ??????????? count += n/3
> ??????????? count % n == 1
> ??????? return n
>
>
> ### main ####
>
> x = input("Enter a starting value: ")
> y = input("Enter a stopping value: ")
>
> count = evenCount(x)
>
> for n in range(x, y+1) :
> ??? count = 0
> ??? if n % 2 == 0 :
> ??????? count += n/3
> ??????? print "%2d: " %n, "has%2d" %count, "even divisors",
> ??? else :
> ??????? print "%2d: " %n, "has 0 even divisors",
> ??? print
>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

#You start with your range variables
x = input("Enter a starting value: ")
y = input("Enter a stopping value: ")

#You set a for loop for range
for num in range(x, y):
#If that number divided by 2 has a remainder of 0, it's of course even.
	if num % 2 == 0:
	#print the number
            print num

And various other ways as well.

David

From lie.1296 at gmail.com  Tue Sep 28 08:06:56 2010
From: lie.1296 at gmail.com (Lie Ryan)
Date: Tue, 28 Sep 2010 16:06:56 +1000
Subject: [Tutor] list comprehension, efficiency?
In-Reply-To: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>
References: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>
Message-ID: <i7s0gg$ct0$1@dough.gmane.org>

On 09/28/10 13:57, Bill Allen wrote:
> I can now see that quite a bit of the code I write dealing with lists
> can be done with list
> comprehensions.   My question is this, is the list comprehension styled
> code generally
> more efficient at runtime?  If so, why?

Yes, because the looping in list comprehension is done in C instead of a
python construct. However, they are the type of efficiency that you
shouldn't bother yourself with unless you're microoptimizing.


From mass02gh at yahoo.ca  Tue Sep 28 08:07:57 2010
From: mass02gh at yahoo.ca (masawudu bature)
Date: Mon, 27 Sep 2010 23:07:57 -0700 (PDT)
Subject: [Tutor] Python Help
In-Reply-To: <AANLkTi==109eCXfJ6t090FvDJsug1kbCdNtTKZnzwCqC@mail.gmail.com>
References: <765790.84633.qm@web58508.mail.re3.yahoo.com>
	<AANLkTi==109eCXfJ6t090FvDJsug1kbCdNtTKZnzwCqC@mail.gmail.com>
Message-ID: <72753.54815.qm@web58508.mail.re3.yahoo.com>

Thanks David, But the loop was suppose to produce the count of even divisors an 
integer has.
Like, 6 has 2 "even" divisors, which is 2 and 6, itself.
8 = 3 even divisors, which is 2, 4 ,and 8
10 = 2 even divisors, which is 2, and 10
12 = 4 even divisors, which is 2, 4, 6, and 12

sorry, I just don't know how to write a code to count the number of divisors




________________________________
From: David Hutto <smokefloat at gmail.com>
To: masawudu bature <mass02gh at yahoo.ca>
Cc: tutor at python.org
Sent: Mon, September 27, 2010 11:36:05 PM
Subject: Re: [Tutor] Python Help

On Tue, Sep 28, 2010 at 12:15 AM, masawudu bature <mass02gh at yahoo.ca> wrote:
> I'm having a hard time finding the count of divisors that are even. Help
> anybody?
>
> Here's my code.
>
> The output is suppose to count the number of even divisors the range has.
>
> def evenCount(b) :
>     for n in range(x, y+1) :
>         count = 0
>         if n % 2 == 0 :
>             count += n/3
>             count % n == 1
>         return n
>
>
> ### main ####
>
> x = input("Enter a starting value: ")
> y = input("Enter a stopping value: ")
>
> count = evenCount(x)
>
> for n in range(x, y+1) :
>     count = 0
>     if n % 2 == 0 :
>         count += n/3
>         print "%2d: " %n, "has%2d" %count, "even divisors",
>     else :
>         print "%2d: " %n, "has 0 even divisors",
>     print
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

#You start with your range variables
x = input("Enter a starting value: ")
y = input("Enter a stopping value: ")

#You set a for loop for range
for num in range(x, y):
#If that number divided by 2 has a remainder of 0, it's of course even.
    if num % 2 == 0:
    #print the number
            print num

And various other ways as well.

David



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/fb989b49/attachment.html>

From ajarncolin at gmail.com  Tue Sep 28 08:15:26 2010
From: ajarncolin at gmail.com (col speed)
Date: Tue, 28 Sep 2010 13:15:26 +0700
Subject: [Tutor] Pythonic nested lists
Message-ID: <AANLkTimdykbKzxAacbAAGpQ_fAZ50Ruy=bcr81dQXk0P@mail.gmail.com>

Hi all,
I've been trying to write a programme that solves sudoku problems for a
while now. I'm getting close, but would like to ask a few questions about
the most pythonic way of doing some things.
I've decided to create nested lists (row order, column order and square
order) which correspond with dictionary keys - the values of which are the
numbers given in the puzzle - so I can loop through the dict in different
orders.
I think the first two are OK, but the square order list seems extremely
messy and I would love some pointers. What I have is as follows:

roworder = [[str(j)+str(i) for i in range(9)] for j in range(9)]
colorder = zip(*roworder)
#here comes the problem!
start, index = 0,0
sqorder = []
for i in range(9):
    sqorder.append([])
    for j in range(start, start+3):
        sqorder[i].extend(roworder[j][index:index+3])
    if index == 6:
        index = 0
    else:
        index += 3
    if i == 2 or i == 5:
        start += 3

Any comments at all would be gratefully received.
Thanks in advance
Colin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/884126f3/attachment-0001.html>

From norman at khine.net  Tue Sep 28 09:56:14 2010
From: norman at khine.net (Norman Khine)
Date: Tue, 28 Sep 2010 09:56:14 +0200
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <i7r2v6$bg2$1@dough.gmane.org>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<i7r2v6$bg2$1@dough.gmane.org>
Message-ID: <AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>

thanks for the reply. i should have been more specific in my question ;)

the order in which 'other' is listed is not always the last item of
the list as it is dependent on where in the CSV file it is included.

what i was trying to do is to take create the list of dictionary items
and then find the item which has name=='other' and then put this as
the last item in the list.

so from this list http://pastie.org/1185974 how do i select the item
name == 'other' and put it at the end of the list?

On Mon, Sep 27, 2010 at 11:39 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 9/27/2010 1:22 PM Norman Khine said...
>
>> what is the correct way to ensure that {'industry': 'travel', 'name':
>> 'other','value': MSG(u"Other")} is always added to the end of this
>> list after all the items have been sorted?
>>
>> here is the code which returns this list:
>
> ? options.sort(key=itemgetter('name'))
> ? return options
>
> So, to answer the question you ask above, you can do:
>
> ? options.sort(key=itemgetter('name'))
> ? options.append({'industry':'travel',
> ? ? ?'name':'other','value':MSG(u"Other")}
> ? return options
>
> But I don't think that's the question you're looking to get answered.
>
> I think you want "other" to be found only at the end and not elsewhere.
>
> Then you might try excluding other from options allowing the above to append
> it to the end:
>
> for index, row in enumerate(topics.get_rows()):
> ? ?if row[0] != 'other':
> ? ? ? ?options.append({'name': row[0], 'value': MSG(row[1])})
>
> HTH,
>
> Emile
>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From cmacleod170 at gmail.com  Mon Sep 27 17:53:05 2010
From: cmacleod170 at gmail.com (Cameron Macleod)
Date: Mon, 27 Sep 2010 16:53:05 +0100
Subject: [Tutor] Basics
Message-ID: <AANLkTikUEMvDGuJOquJoM5P+biocxL6W9YOqr0aqhX-B@mail.gmail.com>

Hi,

I'm relatively new to this mailing list (and python!) and I would greatly
appreciate some exercises to try or something to get me familiar with the
system.

Thanks,

Cameron Macleod
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/89088acf/attachment.html>

From double.hh at live.com  Mon Sep 27 03:31:58 2010
From: double.hh at live.com (Ralph  Pat Hall)
Date: Sun, 26 Sep 2010 21:31:58 -0400
Subject: [Tutor] help with python 3.1
Message-ID: <BAY152-ds9B29E0AABC6242F6501B098650@phx.gbl>

Dear Tutor:

I would like to install a program that was written with python 3.1, the computer that I would like to put in on has Win 98SE. I tried Python 3.1.2 MSI and 2.61 but got a message that a DLL was not there and would not install. I then tried them on a Win 7 computer and got to the 5 files that you had to say where they should go. They were register ext.; TCI/TK; documentation; utility scripts; test suite---go on the HD, local drive, not at all. My guess is HD ??? Do I need all 5 files ?

The writer of the program also said that you needed to download sq-3_6_23_1.zip and if you had XP or Vista and you wanted to print you also needed pywin.32-214.win32py3.1.exe. Would I need that with 98SE? He also said that any python before 3.1 would not be useable.

I don't know anything about python so I need any help possible

thank you 
Ralph
duoble.hh at live.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100926/898abd0d/attachment.html>

From dr8086 at bristol.ac.uk  Sat Sep 25 20:44:49 2010
From: dr8086 at bristol.ac.uk (D Ryan (2))
Date: Sat, 25 Sep 2010 19:44:49 +0100 (BST)
Subject: [Tutor] trouble with list.remove() loop
Message-ID: <49645.172.21.98.221.1285440289.squirrel@webmail.bris.ac.uk>

Hello all,
I am currently trying to write a program which can find the solution to a
game of hangman.
In a part of the program, a user inputs a letter, a tester tells him if
the word contains that letter, and then if the answer is no, all words
containing that letter are removed from the list of remaining candidates.
However, the code I've written seems to remove some, but not all the words
containing the letter. Strangely though, if i run it a few more times it
gets some of the ones it missed the 1st time round, untill after enough
iterations it gets all of them. I cant understand why it doesnt remove all
of them the first time round. I have cut the offending code and formatted
it to work on its own, and also to fit into a relatively short email.

# A sample list of words, one of which is the answer.
candidates = ["abacus","amazing",
              "ozimandias",
              "a","alphanumeric",
              "functioning"]

# In the following code, the user has guessed the letter 'a',
# and the tester has told him that the letter 'a' is not in the word.

user_guess="a"
tester_response="no"

# The following code should eliminate all words which contain the letter
# 'a', leaving only the word 'functioning' in the list

if tester_response in ("No","no","n","N","NO"):
    for word in candidates:
        if user_guess in word:
            print word, "removed.."
            candidates.remove(word)
print candidates

Running once gives this output

abacus removed..
ozimandias removed..
alphanumeric removed..
['amazing', 'a', 'functioning']

But if i run it again it successfully removes 'amazing, and the next time
it removes 'a', leaving the correct answer. I'm perplexed by this strange
behaviour and would be most appreciative of any help. I'm very new to
python so apologies for any formatting/style errors, and also for the
simplicity of the problem.

Best regards
Dave


From la.foma at gmail.com  Tue Sep 28 07:05:25 2010
From: la.foma at gmail.com (Juli)
Date: Tue, 28 Sep 2010 05:05:25 -0000
Subject: [Tutor] pyMVPA and OSError
Message-ID: <F1856E0D-B139-4C8C-B355-702CF4058C40@gmail.com>

I am very much new to python, and thus I am likely to feel stupid  
about asking. But I need to get past this to continue with my work.
I need pyMVPA module to run some analysis on fMRI data, but as a start  
I want to at first play around with the sample data provided on pyMVPA  
website. I have downloaded Python2.6, my operating system is Mac  
Leopard (i get a depracation warning when I try to >>> import mvpa,  
which is not the problem, however, when I attempt to use the following  
line
 >>> import mvpa.suite as mvpa
which i assume to mean the same thing, I dont get deprecation warning,  
but I do get a bunch of errors as follows:
 >>> import mvpa.suite as mvpa

Traceback (most recent call last):
   File "<pyshell#14>", line 1, in <module>
     import mvpa.suite as mvpa
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/suite.py", line 38, in <module>
     from mvpa.algorithms.cvtranserror import *
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py", line 15,  
in <module>
     from mvpa.measures.base import DatasetMeasure
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/measures/base.py", line 31, in <module>
     from mvpa.clfs.stats import autoNullDist
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/clfs/stats.py", line 772, in <module>
     if externals.exists('pylab'):
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/base/externals.py", line 432, in exists
     exec _KNOWN[dep]
   File "<string>", line 1, in <module>
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/mvpa/base/externals.py", line 249, in  
__check_pylab
     import pylab as P
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/pylab.py", line 1, in <module>
     from matplotlib.pylab import *
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/pylab.py", line 206, in <module>
     from matplotlib import mpl  # pulls in most modules
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/mpl.py", line 2, in <module>
     from matplotlib import axis
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/axis.py", line 10, in <module>
     import matplotlib.font_manager as font_manager
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/font_manager.py", line 1297, in  
<module>
     _rebuild()
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/font_manager.py", line 1288, in  
_rebuild
     fontManager = FontManager()
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/font_manager.py", line 980, in  
__init__
     self.ttffiles = findSystemFonts(paths) + findSystemFonts()
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/font_manager.py", line 337, in  
findSystemFonts
     for f in get_fontconfig_fonts(fontext):
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/site-packages/matplotlib/font_manager.py", line 298, in  
get_fontconfig_fonts
     pipe = subprocess.Popen(['fc-list', '', 'file'],  
stdout=subprocess.PIPE)
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/subprocess.py", line 621, in __init__
     errread, errwrite)
   File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/ 
lib/python2.6/subprocess.py", line 1126, in _execute_child
     raise child_exception
OSError: [Errno 2] No such file or directory

-----

I am not sure why OSError is popping and I am sure I am doing  
something wrong, I just do not know enough to pinpoint what exactly.

Any feedback is appreciated. And I do once more apologize for asking  
very stupid questions.



From putjatt at yahoo.com  Sun Sep 26 05:50:25 2010
From: putjatt at yahoo.com (Preetinder Singh)
Date: Sat, 25 Sep 2010 20:50:25 -0700 (PDT)
Subject: [Tutor] I am looking for a book on Beginners who never programmed
	before or have no experience in programming
Message-ID: <333453.11381.qm@web53602.mail.re2.yahoo.com>

Hi I am trying to learn how to program, I want to become a software developer so 
I can develop a software and also understand how to write my own software not 
copying someone else. So if there any book or online tutorials for complete 
beginners. I went to the python website and on wiki python and there are so many 
books to choose from, please help me choose one.


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100925/06af9998/attachment-0001.html>

From thierry338 at yahoo.com  Mon Sep 27 18:11:07 2010
From: thierry338 at yahoo.com (Thierry Tung)
Date: Mon, 27 Sep 2010 09:11:07 -0700 (PDT)
Subject: [Tutor] console output that is same in Python 2 and 3
Message-ID: <926033.58480.qm@web38901.mail.mud.yahoo.com>

Hello tutor at python.org.

How can I write strings to the console in a way that will give the same result in Python 3 and Python 2?

I tried sys.stdout.write('hello') on Microsoft vista.

with python 3.1.2 
>>>sys.stdout.write('hello')
hello5
>>>

with python 2.7 
>>>sys.stdout.write('hello')
hello>>>

Why is the string length appended to the output with python 3.1.2?

Thanks,
Thierry



      

From oldmantaggie at gmail.com  Sat Sep 25 15:33:06 2010
From: oldmantaggie at gmail.com (John Chandler)
Date: Sat, 25 Sep 2010 08:33:06 -0500
Subject: [Tutor] input and raw input
In-Reply-To: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
References: <BAY127-DS17FF3895B7176C9B1CEDADCE610@phx.gbl>
Message-ID: <AANLkTinGz3Gb00ZOSKOAeJPwUkpXC8YBHA=72fdaBGVa@mail.gmail.com>

you can use an re split...

import re
a=raw_input("Enter the number of your class in the school:")
regex = re.compile("[ ,]") #sets the delimeters to a single space or comma
m = regex.split(a)

if you want to use any white space character than you can use "[\s,]"

2010/9/23 Ahmed AL-Masri <ahmedn82 at hotmail.com>

>  Hi,
> any one have an idea about how we can input many number in the one time and
> change it to list.
> for example:
>
> a=input("Enter the number of your class in the school:")     # the number
> can be enter as: 12,13,14 or 12 13 14 with a space in between.
>
> now how I can put these numbers into list like b=[12,13,14] with len( a )
> =3
>
> I tried with that but it's working only for a numbers less than 10 ex.
> 1,2,3 or 1 2 3 but it's not when I go for numbers higher than 10 like in
> example above.
>
> a=raw_input("Enter the number of your class in the school:")
> m=[]
>  for I range (len( a)):
>     if a[I]==',':
>         pass
>     elif a[I]==' ':
>         pass
>     else:
>         m.append(a[I])
> m=map(float,m)
> print m;print len( m )
> >> [1,2,3]
> >> 3
>
> looking forward to seeing your help,
> regards,
> Ahmed
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
-John Chandler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100925/fa23b62b/attachment.html>

From dextrous85 at gmail.com  Tue Sep 28 10:37:39 2010
From: dextrous85 at gmail.com (vishwajeet singh)
Date: Tue, 28 Sep 2010 14:07:39 +0530
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <333453.11381.qm@web53602.mail.re2.yahoo.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
Message-ID: <AANLkTi=a5QO_EDQizP2NiHpNFBVCYoUcHK=h=rD88F7C@mail.gmail.com>

On Sun, Sep 26, 2010 at 9:20 AM, Preetinder Singh <putjatt at yahoo.com> wrote:

> Hi I am trying to learn how to program, I want to become a software
> developer so I can develop a software and also understand how to write my
> own software not copying someone else. So if there any book or online
> tutorials for complete beginners. I went to the python website and on wiki
> python and there are so many books to choose from, please help me choose
> one.
>

 I would recommend Python for Absolute Beginners.


>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Vishwajeet Singh
+91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com
Twitter: http://twitter.com/vishwajeets | LinkedIn:
http://www.linkedin.com/in/singhvishwajeet
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/79108881/attachment.html>

From mail at timgolden.me.uk  Tue Sep 28 10:56:14 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 28 Sep 2010 09:56:14 +0100
Subject: [Tutor] console output that is same in Python 2 and 3
In-Reply-To: <926033.58480.qm@web38901.mail.mud.yahoo.com>
References: <926033.58480.qm@web38901.mail.mud.yahoo.com>
Message-ID: <4CA1ADAE.6040007@timgolden.me.uk>

On 27/09/2010 17:11, Thierry Tung wrote:
> Hello tutor at python.org.
>
> How can I write strings to the console in a way that will give the same result in Python 3 and Python 2?

> I tried sys.stdout.write('hello') on Microsoft vista.
>
> with python 3.1.2
>>>> sys.stdout.write('hello')
> hello5
>>>>
>
> with python 2.7
>>>> sys.stdout.write('hello')
> hello>>>
>
> Why is the string length appended to the output with python 3.1.2?

Because in Py 3.x the .write method returns the length written.
The interpreter echoes the non-None return value of any function
to stdout. This won't happen when you run the program -- you won't
get a stream of numbers. To avoid it happening in the interpreter,
simply assign the return value:

   n = sys.stdout.write("hello")

In Python 2.x n will be None; in Python 3.x it will be 5

TJG

From cwitts at compuscan.co.za  Tue Sep 28 10:55:15 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Tue, 28 Sep 2010 10:55:15 +0200
Subject: [Tutor] trouble with list.remove() loop
In-Reply-To: <49645.172.21.98.221.1285440289.squirrel@webmail.bris.ac.uk>
References: <49645.172.21.98.221.1285440289.squirrel@webmail.bris.ac.uk>
Message-ID: <4CA1AD73.5000005@compuscan.co.za>

On 25/09/2010 20:44, D Ryan (2) wrote:
> Hello all,
> I am currently trying to write a program which can find the solution to a
> game of hangman.
> In a part of the program, a user inputs a letter, a tester tells him if
> the word contains that letter, and then if the answer is no, all words
> containing that letter are removed from the list of remaining candidates.
> However, the code I've written seems to remove some, but not all the words
> containing the letter. Strangely though, if i run it a few more times it
> gets some of the ones it missed the 1st time round, untill after enough
> iterations it gets all of them. I cant understand why it doesnt remove all
> of them the first time round. I have cut the offending code and formatted
> it to work on its own, and also to fit into a relatively short email.
>
> # A sample list of words, one of which is the answer.
> candidates = ["abacus","amazing",
>                "ozimandias",
>                "a","alphanumeric",
>                "functioning"]
>
> # In the following code, the user has guessed the letter 'a',
> # and the tester has told him that the letter 'a' is not in the word.
>
> user_guess="a"
> tester_response="no"
>
> # The following code should eliminate all words which contain the letter
> # 'a', leaving only the word 'functioning' in the list
>
> if tester_response in ("No","no","n","N","NO"):
>      for word in candidates:
>          if user_guess in word:
>              print word, "removed.."
>              candidates.remove(word)
> print candidates
>
> Running once gives this output
>
> abacus removed..
> ozimandias removed..
> alphanumeric removed..
> ['amazing', 'a', 'functioning']
>
> But if i run it again it successfully removes 'amazing, and the next time
> it removes 'a', leaving the correct answer. I'm perplexed by this strange
> behaviour and would be most appreciative of any help. I'm very new to
> python so apologies for any formatting/style errors, and also for the
> simplicity of the problem.
>
> Best regards
> Dave
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>    

You are mutating the list that you are iterating over so in essence you 
are looking at the word in list index 0, testing it, and removing it, 
then moving onto list index 1 but now your list has 'amazing' in index 0 
so that does not get checked.

The simplest way is to iterate through a new list with this
     for word in candidates[:]:

That will create a new list that you will iterate over while you mutate 
the original list.

-- 
Kind Regards,
Christian Witts



From alan.gauld at btinternet.com  Tue Sep 28 11:33:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 10:33:40 +0100
Subject: [Tutor] pure function problem
References: <SNT118-W3393FF86ED910F45E4102AAE610@phx.gbl>
Message-ID: <i7scpp$uig$1@dough.gmane.org>

Just home from vacation so jumping in late...

"Roelof Wobben" <rwobben at hotmail.com> wrote

> class tijd :
>    pass

Others have solved this for you but you don't appear to have picked
up on the point made by Jeremy that you are not initialising your
class's attributes.

By only creating the attributes within the function - and worse, by
creating different attributes depending on the logic flow - you are 
creating
a huge layer of complexity for yourself. That is why you will nearly
always see a class definition have an __init__ method. It ensures that
the minimum set of attributes are there and valid (at least with 
default
values)

If you carrry on defining classes as you are doing you will continue
to have these errors because the code that uses the object will not 
know
whether attributes exist or not. You will have to check the existence
of each atribute before you use it. That is hard work, much harder
than creating an __init__ method.

> def increment(time, seconds):
>    sum = tijd()
>    sum.seconds = time.seconds + seconds
>
>    if sum.seconds> 60 :
>        minutes, seconds = divmod(sum.seconds, 60)
>        sum.seconds = seconds
>        sum.minutes = time.minutes + minutes
>    return sum

> Traceback (most recent call last):
>  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 22, 
> in <module>
>    print uitkomst.minutes, uitkomst.seconds
> AttributeError: tijd instance has no attribute 'minutes'
>
> So it looks like uitkomst has no attribute minutes but uitkomst
> is a instance of tijd which has a attribute minutes.

No it doesn't if seconds <= 60.

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



From jemejones at gmail.com  Tue Sep 28 11:37:12 2010
From: jemejones at gmail.com (Jeremy Jones)
Date: Tue, 28 Sep 2010 05:37:12 -0400
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <333453.11381.qm@web53602.mail.re2.yahoo.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
Message-ID: <AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>

On Sat, Sep 25, 2010 at 11:50 PM, Preetinder Singh <putjatt at yahoo.com> wrote:
> Hi I am trying to learn how to program, I want to become a software
> developer so I can develop a software and also understand how to write my
> own software not copying someone else. So if there any book or online
> tutorials for complete beginners. I went to the python website and on wiki
> python and there are so many books to choose from, please help me choose
> one.
>

"Beginning Python" by Magnus lie Hetland is good.  I have the first
edition, but not the second.  I can only imagine that it got better.
"Head First Programming: A Learner's Guide to Programming Using the
Python Language" by David Griffiths and Paul Barry was a great read.
It's unconventional (by their nature, all Head First books are), but
excellent.  It's about programming in general, but uses Python to
demonstrate.
There's also a new book coming out shortly that will probably benefit
you: "Head First Python".  Again, it's unconventional, but thoroughly
enjoyable and informative.

Disclaimer:  I tech reviewed all 3 of these books.  I don't get any
more $ for you buying them, though.

Another great read is the Python Cookbook.  You can find the recipes
online, also, but sometimes it's good to just sit with a hard copy of
the book.  The cookbook will walk you through tons of code examples,
which is really helpful when you're learning a new language (or any
language for the first time).

HTH,

- jmj


>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From alan.gauld at btinternet.com  Tue Sep 28 11:50:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 10:50:31 +0100
Subject: [Tutor] I am looking for a book on Beginners who never
	programmedbefore or have no experience in programming
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
Message-ID: <i7sdpd$304$1@dough.gmane.org>


"Preetinder Singh" <putjatt at yahoo.com> wrote

> copying someone else. So if there any book or online tutorials for 
> complete
> beginners. I went to the python website and on wiki python and there 
> are so many
> books to choose from, please help me choose one.

There are many because people learn in different ways.
My tutor, for example, focuses on general programming principles and 
uses 3
languages to illustrate the points. It also assumes a fair degree of 
computer
skills although no previous programming experience. Others take an 
example
based approach. Others focus on a feature by feature, in depth 
coverage of a
single language. It just depends on how you like to be taught.

My advice would be to pick two or three tutorials from the Non 
Programmers
section of the web site, follow a few of the sections in each and see 
which seems
most effecftive to you. Stick with that tutor but when you get stuck 
refer to the
second best to see how it covers the same topic. If you still can't 
understand
ask questions here.

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



From alan.gauld at btinternet.com  Tue Sep 28 12:02:56 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 11:02:56 +0100
Subject: [Tutor] Issues In Terminal
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com><AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com><AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>
	<AANLkTimh26yyeLLRkoru9Nh=cOQv5eAZ905AsZVFnWVa@mail.gmail.com>
Message-ID: <i7segm$64l$1@dough.gmane.org>


"Marc Tompkins" <marc.tompkins at gmail.com> wrote


> The parentheses are optional in 2.6, mandatory in 3.  In 2.6, print 
> and
> print() are alternate ways to invoke the print statement

Not strictly true. They often give the same results but not always,
see a recent thread on this. In particular

>>> print ('a','b')

is quite different to

>>> print 'a','b'

But that shouldn't be an issue for 'hello world'

Alan G.



From alan.gauld at btinternet.com  Tue Sep 28 12:09:12 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 11:09:12 +0100
Subject: [Tutor] function error
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
Message-ID: <i7sesd$7rc$1@dough.gmane.org>


"roberto" <roberto03 at gmail.com> wrote

> i have the following error when i call this function:
>   20 def outOfBounds():
> ---> 21         if abs(turtle.position()[0]) >
> turtle.window_height()/2 or abs(turtle.position()[1]) >
> turtle.window_width()/2:
>     22                 return "true"
>     23         else:
>
> TypeError: 'function' object is unsubscriptable
>
> but i can't really figure out where is the problem with this 
> function
> 'unsubscriptable';

This means you are trying to use [] on a function.
eg you might be doing turtle.position[1] instead of 
turtle.position()[1]

I can't see it in your code sample but I'd check carefully that your
parens() all balance correctly and are in the right place...

HTH,


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



From alan.gauld at btinternet.com  Tue Sep 28 12:05:02 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 11:05:02 +0100
Subject: [Tutor] Basics
References: <AANLkTikUEMvDGuJOquJoM5P+biocxL6W9YOqr0aqhX-B@mail.gmail.com>
Message-ID: <i7sekj$6lh$1@dough.gmane.org>


"Cameron Macleod" <cmacleod170 at gmail.com> wrote

> I'm relatively new to this mailing list (and python!) and I would 
> greatly
> appreciate some exercises to try or something to get me familiar 
> with the
> system.

Are you new to programming? Or just new to Python?

In erither case there are a wealth of tutorials suited to your needs
on the Python web site. They nearly all have exercises in one form or 
other.

If you are already fairly experienced you might find the Python 
Challenge
web site a fun way to learn too.

HTH,


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



From delegbede at dudupay.com  Tue Sep 28 12:13:27 2010
From: delegbede at dudupay.com (Dipo Elegbede)
Date: Tue, 28 Sep 2010 11:13:27 +0100
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
Message-ID: <AANLkTikHbbhsbhNSRUh_1JPSZKOpJCTPHUdKAXDLBwOe@mail.gmail.com>

I go with Alan.
If you however arrive at a choice book or books, send me a list of the
books, I will check if I have any of them. I have plenty books on
python now.
You may not need to send a personal mail, just send it here on the
forum and i would send you a download link.
I hope by that everyone who wishes can have a look and I would not
have violated any copyright law.
Welcome to the world of python programming.

You sure would get a great deal of help in here.
Regards,

On 9/28/10, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Preetinder Singh" <putjatt at yahoo.com> wrote
>
>> copying someone else. So if there any book or online tutorials for
>> complete
>> beginners. I went to the python website and on wiki python and there
>> are so many
>> books to choose from, please help me choose one.
>
> There are many because people learn in different ways.
> My tutor, for example, focuses on general programming principles and
> uses 3
> languages to illustrate the points. It also assumes a fair degree of
> computer
> skills although no previous programming experience. Others take an
> example
> based approach. Others focus on a feature by feature, in depth
> coverage of a
> single language. It just depends on how you like to be taught.
>
> My advice would be to pick two or three tutorials from the Non
> Programmers
> section of the web site, follow a few of the sections in each and see
> which seems
> most effecftive to you. Stick with that tutor but when you get stuck
> refer to the
> second best to see how it covers the same topic. If you still can't
> understand
> ask questions here.
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

-- 
Sent from my mobile device

Elegbede Muhammed Oladipupo
OCA
+2348077682428
+2347042171716
www.dudupay.com
Mobile Banking Solutions | Transaction Processing | Enterprise
Application Development

From alan.gauld at btinternet.com  Tue Sep 28 12:18:28 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 28 Sep 2010 11:18:28 +0100
Subject: [Tutor] Python Help
References: <765790.84633.qm@web58508.mail.re3.yahoo.com>
Message-ID: <i7sfdp$a6v$1@dough.gmane.org>


"masawudu bature" <mass02gh at yahoo.ca> wrote

> The output is suppose to count the number of even divisors the range 
> has.

You need to work this through again in your head:

> def evenCount(b) :

This function takes a parameter b but you never use b in the 
function...

>    for n in range(x, y+1) :

What are x and y supposed to be? They must be defined
outside the function? Don;t you really want your loop to check
the values for b? So it would be range(0,b+1)?

>        count = 0

You reset count to zero for each time through the loop - do
you really want to do that?

>        if n % 2 == 0 :
>            count += n/3

Why do you add n/3?

>            count % n == 1

This is a boolean expression that will evaluate to TRue or False
and which you then ignore. It does nothing useful.

>        return n

And this will always return the first value of your loop, x.

Try working through it on paper, writing down the values of each 
variable
in the function  for each time through the loop. Are they what you 
expect?

HTH,


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



From nitin.162 at gmail.com  Tue Sep 28 12:35:27 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Tue, 28 Sep 2010 16:05:27 +0530
Subject: [Tutor] function error
In-Reply-To: <i7sesd$7rc$1@dough.gmane.org>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
Message-ID: <AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>

It seems that ur turtle.position doesn't return a list because of this when
indexing is done on that u get this kind of error.

--nitin

On Tue, Sep 28, 2010 at 3:39 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> "roberto" <roberto03 at gmail.com> wrote
>
>
>  i have the following error when i call this function:
>>  20 def outOfBounds():
>> ---> 21         if abs(turtle.position()[0]) >
>> turtle.window_height()/2 or abs(turtle.position()[1]) >
>> turtle.window_width()/2:
>>    22                 return "true"
>>    23         else:
>>
>> TypeError: 'function' object is unsubscriptable
>>
>> but i can't really figure out where is the problem with this function
>> 'unsubscriptable';
>>
>
> This means you are trying to use [] on a function.
> eg you might be doing turtle.position[1] instead of turtle.position()[1]
>
> I can't see it in your code sample but I'd check carefully that your
> parens() all balance correctly and are in the right place...
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/87080ca9/attachment-0001.html>

From steve at pearwood.info  Tue Sep 28 13:16:00 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 21:16:00 +1000
Subject: [Tutor] Python Help
In-Reply-To: <765790.84633.qm@web58508.mail.re3.yahoo.com>
References: <765790.84633.qm@web58508.mail.re3.yahoo.com>
Message-ID: <201009282116.00917.steve@pearwood.info>

On Tue, 28 Sep 2010 02:15:52 pm masawudu bature wrote:
> I'm having a hard time finding the count of divisors that are even.
> Help anybody?
>
> Here's my code.
>
> The output is suppose to count the number of even divisors the range
> has.

I don't understand the question. What do you mean by "divisors the range 
has"? Perhaps you should show an example, and give the answer you 
expect.



This function is troublesome:

> def evenCount(b) :
>     for n in range(x, y+1) :
>         count = 0
>         if n % 2 == 0 :
>             count += n/3
>             count % n == 1
>         return n

What's b? It is never used.

Every time through the loop, you start the count at zero again.

This function will always return y, the stopping value.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 13:22:36 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 21:22:36 +1000
Subject: [Tutor] trouble with list.remove() loop
In-Reply-To: <4CA1AD73.5000005@compuscan.co.za>
References: <49645.172.21.98.221.1285440289.squirrel@webmail.bris.ac.uk>
	<4CA1AD73.5000005@compuscan.co.za>
Message-ID: <201009282122.36638.steve@pearwood.info>

On Tue, 28 Sep 2010 06:55:15 pm Christian Witts wrote:

> You are mutating the list that you are iterating over so in essence
> you are looking at the word in list index 0, testing it, and removing
> it, then moving onto list index 1 but now your list has 'amazing' in
> index 0 so that does not get checked.
>
> The simplest way is to iterate through a new list with this
>      for word in candidates[:]:
>
> That will create a new list that you will iterate over while you
> mutate the original list.



Another technique is to iterate over the list backwards, so you are only 
ever deleting words you've already seen:

for i in range(len(candidates)-1, -1, -1)):
    word = candidates[i]
    if some_test():
        del candidates[i]


I know the series of -1, -1, -1 is ugly, but that's what it takes.


-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 13:25:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 21:25:28 +1000
Subject: [Tutor] list comprehension, efficiency?
In-Reply-To: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>
References: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>
Message-ID: <201009282125.28338.steve@pearwood.info>

On Tue, 28 Sep 2010 01:57:23 pm Bill Allen wrote:

> I can now see that quite a bit of the code I write dealing with lists
> can be done with list
> comprehensions.   My question is this, is the list comprehension
> styled code generally
> more efficient at runtime?  If so, why?


List comprehensions *are* lists, or rather, they produce lists.

A list comprehension 

result = [expr for x in seq] 

is just syntactic sugar for a for-loop:

result = []
for x in seq:
    result.append(x)

except that in Python 3, the "x" variable is hidden. (In Python 2 it is 
not, but that was an accident.) The end result is exactly the same 
whether you use a list comp or a for-loop.

The advantage of for-loops is that you can do much more complex code. 
That complexity comes at a cost, and consequently for-loops tend to be 
a little bit slower than list comprehensions: some of the work can be 
done under the hood, faster than regular Python code. But for most 
cases, this difference is relatively small and won't make any real 
difference. What does it matter if your program runs in 24 milliseconds 
instead of 22 milliseconds? Or five hours and seventeen minutes instead 
of five hours and sixteen minutes? Who cares? Write the code that is 
most natural and easy to read and understand, and only worry about such 
tiny savings when you absolutely have to.

But there is one case where for-loops are potentially MUCH faster than 
list comps. List comps always run all the way to the end, but for-loops 
can break out early. If your problem lets you break out of the loop 
early, this is a good thing. So this for-loop:


for x in xrange(10000000):
    result.append(x+1)
    if x > 5: break


will beat the pants off this list comp:

[x+1 for x in xrange(10000000) if x <= 5]

There's no way to break out of the list comp early -- it has to keep 
going past 5 all the way to the end.


-- 
Steven D'Aprano

From alifshirali at hotmail.com  Tue Sep 28 13:39:16 2010
From: alifshirali at hotmail.com (Alif Shirali)
Date: Tue, 28 Sep 2010 07:39:16 -0400
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <333453.11381.qm@web53602.mail.re2.yahoo.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
Message-ID: <SNT127-W39A164786317F06521DF27A9660@phx.gbl>


You might also consider the following free resources that are meant for new programmers. They can easily be found on the internet:

How to Think Like a (Python) Programmer
by Allen Downey

Dive Into Python
20 May 2004
Copyright ? 2000, 2001, 2002, 2003, 2004 Mark Pilgrim 
(mailto:mark at diveintopython.org)
This book lives at http://diveintopython.org/. If you're reading it somewhere else, you may not have the latest version.

and the intro python short courses at ocw.mit.edu and www.berkeley.edu
MIT is generaly open free to the public, and last I checked Berkeley was too. The MIT course was designed for non computer science students.

Good luck, and I agree with every comment posted in this forum about this.

Date: Sat, 25 Sep 2010 20:50:25 -0700
From: putjatt at yahoo.com
To: tutor at python.org
Subject: [Tutor] I am looking for a book on Beginners who never programmed	before or have no experience in programming



Hi I am trying to learn how to program, I want to become a software developer so I can develop a software and also understand how to write my own software not copying someone else. So if there any book or online tutorials for complete beginners. I went to the python website and on wiki python and there are so many books to choose from, please help me choose one.
 


      
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/b3964e51/attachment.html>

From steve at pearwood.info  Tue Sep 28 13:47:41 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 21:47:41 +1000
Subject: [Tutor] I am looking for a book on Beginners who never
	programmed before or have no experience in programming
In-Reply-To: <AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
	<AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>
Message-ID: <201009282147.42408.steve@pearwood.info>

On Tue, 28 Sep 2010 07:37:12 pm Jeremy Jones wrote:

> "Head First Programming: A Learner's Guide to Programming Using the
> Python Language" by David Griffiths and Paul Barry was a great read.
> It's unconventional (by their nature, all Head First books are),


I've never heard of "Head First Programming" -- how are they 
unconventional?



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 13:49:53 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 28 Sep 2010 21:49:53 +1000
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009281046.20681.steve@pearwood.info>
	<AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>
Message-ID: <201009282149.54175.steve@pearwood.info>

On Tue, 28 Sep 2010 11:56:33 am Alex Hall wrote:
> > (But don't forget that Python is not necessarily written in C.
> > There's Jython, written in Java, and CLPython written in Lisp, and
> > many others. How they implement objects may be different. What
> > happens under the hood isn't important, so long as the behaviour at
> > the Python level remains the same.)
>
> Really? Neat! I wonder what the advantage of doing that is, since the
> end result, as you say, should be the same once you start writing
> Python code?

Different implementations can make different choices, to suit different 
needs. So long as the end result is the same, they can choose different 
mechanisms, different techniques, radically different strategies, or 
simply choose a different implementation language because they can.

CPython is a conservative implementation written in ordinary C so that 
it is available on almost any platform that has a C compiler. 
Efficiency is not its primary goal, clarity of code and simplicity of 
design is considered just as important. This is almost certainly the 
version you are using.

Unladen Swallow is a version of CPython written by Google that aims to 
speed up certain time-critical parts. If it works, it may end up being 
merged with the regular CPython. Unfortunately, after a flash of 
publicity and some promising early results, Unladen Swallow seems to 
have gone quiet.

PyPy is a version of Python written in Python. It has an incredible 
mission: to eventually produce versions of Python which are faster than 
pure C, despite being written in Python itself. Although they have a 
long, long way to go, they are making good progress, and PyPy can now 
run Python code faster than CPython. PyPy is becoming a generalised 
Just-In-Time compiler for high-level languages like Python.

IronPython and Jython are designed to integrate with Dot-Net and Java. 
IronPython is probably written in C#, like most Dot-Net software, and 
Jython is written in Java.

Stackless Python is similar to CPython except it doesn't have a function 
call stack, which is good for certain specialist applications.

Pynie is an experimental version of Python written for the Parrot 
virtual machine used by Perl 6.

CapPython is a restricted version of Python which aims to be much more 
secure, allowing you to safely run untrusted code without it eating 
your computer. 

And there are many more... I count at least 41 current or past Python 
implementations, add-ons and related projects. My favourite (apart from 
PyPy, which makes me feel all warm and tingly in that special place) is 
LikePython:

http://www.staringispolite.com/likepython/


#!usr/bin/python
# My first Like, Python script!
yo just print like "hello world" bro


I can't wait to put that on my resume :)




-- 
Steven D'Aprano

From rwobben at hotmail.com  Tue Sep 28 14:02:16 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 28 Sep 2010 12:02:16 +0000
Subject: [Tutor] question
Message-ID: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>


Hello,


Im now studying this page :
http://openbookproject.net/thinkcs/python/english2e/ch16.html

But I don't get it why aces are now lower then deuces in the  cmp function.


Roelof

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/2bb7b46c/attachment.html>

From mehgcap at gmail.com  Tue Sep 28 14:08:59 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Tue, 28 Sep 2010 08:08:59 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <201009282149.54175.steve@pearwood.info>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009281046.20681.steve@pearwood.info>
	<AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>
	<201009282149.54175.steve@pearwood.info>
Message-ID: <AANLkTi=wGBGhMHpicsxG-OZsZEwghp8mrru9UbGRR882@mail.gmail.com>

On 9/28/10, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 11:56:33 am Alex Hall wrote:
>> > (But don't forget that Python is not necessarily written in C.
>> > There's Jython, written in Java, and CLPython written in Lisp, and
>> > many others. How they implement objects may be different. What
>> > happens under the hood isn't important, so long as the behaviour at
>> > the Python level remains the same.)
>>
>> Really? Neat! I wonder what the advantage of doing that is, since the
>> end result, as you say, should be the same once you start writing
>> Python code?
>
> Different implementations can make different choices, to suit different
> needs. So long as the end result is the same, they can choose different
> mechanisms, different techniques, radically different strategies, or
> simply choose a different implementation language because they can.
>
> CPython is a conservative implementation written in ordinary C so that
> it is available on almost any platform that has a C compiler.
> Efficiency is not its primary goal, clarity of code and simplicity of
> design is considered just as important. This is almost certainly the
> version you are using.
Probably, I just got 2.6 from python.org.
>
> Unladen Swallow is a version of CPython written by Google that aims to
> speed up certain time-critical parts. If it works, it may end up being
> merged with the regular CPython. Unfortunately, after a flash of
> publicity and some promising early results, Unladen Swallow seems to
> have gone quiet.
>
> PyPy is a version of Python written in Python. It has an incredible
> mission: to eventually produce versions of Python which are faster than
> pure C, despite being written in Python itself. Although they have a
> long, long way to go, they are making good progress, and PyPy can now
> run Python code faster than CPython. PyPy is becoming a generalised
> Just-In-Time compiler for high-level languages like Python.
Okay, I now have to go investigate this and see how it is even
possible; somewhere, the Python code has to get down to machine
code...
>
> IronPython and Jython are designed to integrate with Dot-Net and Java.
> IronPython is probably written in C#, like most Dot-Net software, and
> Jython is written in Java.
>
> Stackless Python is similar to CPython except it doesn't have a function
> call stack, which is good for certain specialist applications.
I'll take your word for it, but it seems like you could then not use
OO since a function's return would have no idea where to go. I was
once forced to try LISP, MIPS machine language, and a functionless
Basic, and I hated them.
>
> Pynie is an experimental version of Python written for the Parrot
> virtual machine used by Perl 6.
>
> CapPython is a restricted version of Python which aims to be much more
> secure, allowing you to safely run untrusted code without it eating
> your computer.
>
> And there are many more... I count at least 41 current or past Python
> implementations, add-ons and related projects. My favourite (apart from
> PyPy, which makes me feel all warm and tingly in that special place) is
> LikePython:
>
> http://www.staringispolite.com/likepython/
>
>
> #!usr/bin/python
> # My first Like, Python script!
> yo just print like "hello world" bro

...interesting. This, too, will have to be looked at, if only because
it is so different. Thanks for all the info!
>
>
> I can't wait to put that on my resume :)
>
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at 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)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From emile at fenx.com  Tue Sep 28 15:12:46 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 28 Sep 2010 06:12:46 -0700
Subject: [Tutor] pyMVPA and OSError
In-Reply-To: <F1856E0D-B139-4C8C-B355-702CF4058C40@gmail.com>
References: <F1856E0D-B139-4C8C-B355-702CF4058C40@gmail.com>
Message-ID: <i7spk9$i3q$1@dough.gmane.org>

On 2/18/2010 8:10 AM Juli said...
> I am very much new to python, and thus I am likely to feel stupid about
> asking. But I need to get past this to continue with my work.
> I need pyMVPA module to run some analysis on fMRI data, but as a start I
> want to at first play around with the sample data provided on pyMVPA
> website. I have downloaded Python2.6,

Just a guess, but the pyMVPA site specifically mentions using version 
2.5, and whenever I have issues with a new package, I go back to the 
installation documentation and follow it closely as it's typically 
written by an experienced user while installing and yields a functioning 
implementation.  I'd reinstall and pay close attention to the version 
numbers and dependencies.

http://www.pymvpa.org/installation.html#macos-x

Then, always check if there's a user group for the package.  Diagnosing 
installation problems of specific packages and related dependencies are 
rarely an area of expertise outside the users of the package.  Join the 
mailing list.

See http://lists.alioth.debian.org/mailman/listinfo/pkg-exppsy-pymvpa

HTH,

Emile


> my operating system is Mac Leopard
> (i get a depracation warning when I try to >>> import mvpa, which is not
> the problem, however, when I attempt to use the following line
>  >>> import mvpa.suite as mvpa
> which i assume to mean the same thing, I dont get deprecation warning,
> but I do get a bunch of errors as follows:
>  >>> import mvpa.suite as mvpa
>
> Traceback (most recent call last):
> File "<pyshell#14>", line 1, in <module>
> import mvpa.suite as mvpa
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/suite.py",
> line 38, in <module>
> from mvpa.algorithms.cvtranserror import *
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py",
> line 15, in <module>
> from mvpa.measures.base import DatasetMeasure
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.py",
> line 31, in <module>
> from mvpa.clfs.stats import autoNullDist
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/stats.py",
> line 772, in <module>
> if externals.exists('pylab'):
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
> line 432, in exists
> exec _KNOWN[dep]
> File "<string>", line 1, in <module>
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py",
> line 249, in __check_pylab
> import pylab as P
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylab.py",
> line 1, in <module>
> from matplotlib.pylab import *
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pylab.py",
> line 206, in <module>
> from matplotlib import mpl # pulls in most modules
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/mpl.py",
> line 2, in <module>
> from matplotlib import axis
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py",
> line 10, in <module>
> import matplotlib.font_manager as font_manager
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
> line 1297, in <module>
> _rebuild()
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
> line 1288, in _rebuild
> fontManager = FontManager()
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
> line 980, in __init__
> self.ttffiles = findSystemFonts(paths) + findSystemFonts()
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
> line 337, in findSystemFonts
> for f in get_fontconfig_fonts(fontext):
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py",
> line 298, in get_fontconfig_fonts
> pipe = subprocess.Popen(['fc-list', '', 'file'], stdout=subprocess.PIPE)
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
> line 621, in __init__
> errread, errwrite)
> File
> "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
> line 1126, in _execute_child
> raise child_exception
> OSError: [Errno 2] No such file or directory
>
> -----
>
> I am not sure why OSError is popping and I am sure I am doing something
> wrong, I just do not know enough to pinpoint what exactly.
>
> Any feedback is appreciated. And I do once more apologize for asking
> very stupid questions.
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



From evert.rol at gmail.com  Tue Sep 28 15:16:47 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 28 Sep 2010 15:16:47 +0200
Subject: [Tutor] pyMVPA and OSError
In-Reply-To: <F1856E0D-B139-4C8C-B355-702CF4058C40@gmail.com>
References: <F1856E0D-B139-4C8C-B355-702CF4058C40@gmail.com>
Message-ID: <157C206C-E7DF-4A98-9945-9CE00F1A66AA@gmail.com>

  Hi,

> I am very much new to python, and thus I am likely to feel stupid about asking. But I need to get past this to continue with my work.
> I need pyMVPA module to run some analysis on fMRI data, but as a start I want to at first play around with the sample data provided on pyMVPA website. I have downloaded Python2.6, my operating system is Mac Leopard (i get a depracation warning when I try to >>> import mvpa,

What depracation warning?


> which is not the problem, however, when I attempt to use the following line
> >>> import mvpa.suite as mvpa

I wouldn't do that; just seems prone to lead to confusion. Perhaps:
  >>> import mvpa.suite as mvpas
or
  >>> from mvpa import suite


> which i assume to mean the same thing,

It normally doesn't mean the same thing. mvpa and mvpa.suite would normally be quite different things. But perhaps this is how the package is setup; that would be in the manual.


More after the traceback.


> I dont get deprecation warning, but I do get a bunch of errors as follows:
> >>> import mvpa.suite as mvpa
> 
> Traceback (most recent call last):
>  File "<pyshell#14>", line 1, in <module>
>    import mvpa.suite as mvpa
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/suite.py", line 38, in <module>
>    from mvpa.algorithms.cvtranserror import *
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/algorithms/cvtranserror.py", line 15, in <module>
>    from mvpa.measures.base import DatasetMeasure
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/measures/base.py", line 31, in <module>
>    from mvpa.clfs.stats import autoNullDist
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/clfs/stats.py", line 772, in <module>
>    if externals.exists('pylab'):
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py", line 432, in exists
>    exec _KNOWN[dep]
>  File "<string>", line 1, in <module>
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/mvpa/base/externals.py", line 249, in __check_pylab
>    import pylab as P
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylab.py", line 1, in <module>
>    from matplotlib.pylab import *
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/pylab.py", line 206, in <module>
>    from matplotlib import mpl  # pulls in most modules
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/mpl.py", line 2, in <module>
>    from matplotlib import axis
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/axis.py", line 10, in <module>
>    import matplotlib.font_manager as font_manager
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 1297, in <module>
>    _rebuild()
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 1288, in _rebuild
>    fontManager = FontManager()
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 980, in __init__
>    self.ttffiles = findSystemFonts(paths) + findSystemFonts()
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 337, in findSystemFonts
>    for f in get_fontconfig_fonts(fontext):
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/matplotlib/font_manager.py", line 298, in get_fontconfig_fonts
>    pipe = subprocess.Popen(['fc-list', '', 'file'], stdout=subprocess.PIPE)


At first read, it looks like mvpa is checking for external dependencies, including checking for fonts to be used by matplotlib (or actually, matplotlib does this).
Matplotlib then tries to run an external process called 'fc-list', which presumably list the font-config fonts.
It looks like your system does not have this installed.

Since this is all installed through matplotlib, that would mean that somewhere there is a dependency check missing. 
For a start, you could try and reinstall matplotlib yourself, hoping this solves it. But I won't guarantee that.

Since this all done through macports, I wonder what your python is: did you install that through matplotlib as well, or are you using a different (system) python?
You mention you downloaded Python 2.6, which would suggest you're not using macports python, which may cause these errors as well.
In addition, if you are on Snow Leopard (not plain Leopard), you should have Python 2.6 as the system python, which would be a different python again (and a bit out of date).

So, check which python you're using and see if that's macports python.

Good luck,

  Evert



>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 621, in __init__
>    errread, errwrite)
>  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1126, in _execute_child
>    raise child_exception
> OSError: [Errno 2] No such file or directory
> 
> -----
> 
> I am not sure why OSError is popping and I am sure I am doing something wrong, I just do not know enough to pinpoint what exactly.
> 
> Any feedback is appreciated. And I do once more apologize for asking very stupid questions.


From davea at ieee.org  Tue Sep 28 16:02:27 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 28 Sep 2010 10:02:27 -0400
Subject: [Tutor] question
In-Reply-To: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>
References: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>
Message-ID: <4CA1F573.6090506@ieee.org>



On 2:59 PM, Roelof Wobben wrote:
> Hello,
>
>
> Im now studying this page :
> http://openbookproject.net/thinkcs/python/english2e/ch16.html
>
> But I don't get it why aces are now lower then deuces in the  cmp function.
>
>
> Roelof
>
>   
Why would you be surprised that aces are lower than deuces?  If aces are 
represented by 1, and deuces by 2, then 1 is less than 2.

Notice that because self.suit is compared first, an ace of spades is 
higher than a deuce of hearts.  It's only within the same suit that an 
ace is "less than" a deuce.

DaveA

		 	   		



From waynejwerner at gmail.com  Tue Sep 28 16:04:07 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 28 Sep 2010 09:04:07 -0500
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <SNT127-W39A164786317F06521DF27A9660@phx.gbl>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
	<SNT127-W39A164786317F06521DF27A9660@phx.gbl>
Message-ID: <AANLkTinLRerqjFE0Y2RV0obWTyVLJKGMjTw7CNsCPpfF@mail.gmail.com>

On Tue, Sep 28, 2010 at 6:39 AM, Alif Shirali <alifshirali at hotmail.com>wrote:

>  You might also consider the following free resources that are meant for
> new programmers. They can easily be found on the internet:
>

I'll toss another recommendation into the ring:

Snake Wrangling for Kids.

It may be geared towards younger people, but I found it entertaining (maybe
my sense of humour is a little immature at times ;) and it also explained
topics fairly well. Explained so well that even adults can understand :)

my 2.5?, adjusted for inflation
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/f2f9721d/attachment.html>

From waynejwerner at gmail.com  Tue Sep 28 16:08:56 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 28 Sep 2010 09:08:56 -0500
Subject: [Tutor] Issues In Terminal
In-Reply-To: <i7segm$64l$1@dough.gmane.org>
References: <00FD001F-F923-4F62-8C6F-FF22B61D6899@gmail.com>
	<AANLkTikWUyTVk4mw+wwD53+HMewuG4Sw127+sX87YP=_@mail.gmail.com>
	<AANLkTi=3WCU6AzcjPK_AB0f4K7rPWvjMX0CjrDKfzgG8@mail.gmail.com>
	<AANLkTimh26yyeLLRkoru9Nh=cOQv5eAZ905AsZVFnWVa@mail.gmail.com>
	<i7segm$64l$1@dough.gmane.org>
Message-ID: <AANLkTikjP5rW5HaFos1-bvPtjZt96M63tCbPxdeaorK=@mail.gmail.com>

On Tue, Sep 28, 2010 at 5:02 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:

>
> "Marc Tompkins" <marc.tompkins at gmail.com> wrote
>
>
>
>  The parentheses are optional in 2.6, mandatory in 3.  In 2.6, print and
>> print() are alternate ways to invoke the print statement
>>
>
> Not strictly true. They often give the same results but not always,
> see a recent thread on this. In particular
>
>  print ('a','b')
>>>>
>>>
> is quite different to
>
>  print 'a','b'
>>>>
>>>
> But that shouldn't be an issue for 'hello world'
>

And of course if you're on 2.6+ you can always add

from __future__ import print_function

and that will help prepare you for the eventual migration to 3+

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/61d5611d/attachment.html>

From norman at khine.net  Tue Sep 28 16:12:50 2010
From: norman at khine.net (Norman Khine)
Date: Tue, 28 Sep 2010 16:12:50 +0200
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <4CA1E617.8090604@fenx.com>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<i7r2v6$bg2$1@dough.gmane.org>
	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>
	<4CA1E617.8090604@fenx.com>
Message-ID: <AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>

thanks for the reply, i think i have it now, perhaps it could be done better

http://pastie.org/1186545

On Tue, Sep 28, 2010 at 2:56 PM, Emile van Sebille <emile at fenx.com> wrote:
> ?Hi Norman,
>
> Read my reply again -- that's the second question I answered.
>
> Emile
>
>
> On 9/28/2010 12:56 AM Norman Khine said...
>>
>> thanks for the reply. i should have been more specific in my question ;)
>>
>> the order in which 'other' is listed is not always the last item of
>> the list as it is dependent on where in the CSV file it is included.
>>
>> what i was trying to do is to take create the list of dictionary items
>> and then find the item which has name=='other' and then put this as
>> the last item in the list.
>>
>> so from this list http://pastie.org/1185974 how do i select the item
>> name == 'other' and put it at the end of the list?
>>
>> On Mon, Sep 27, 2010 at 11:39 PM, Emile van Sebille<emile at fenx.com>
>> ?wrote:
>>>
>>> On 9/27/2010 1:22 PM Norman Khine said...
>>>
>>>> what is the correct way to ensure that {'industry': 'travel', 'name':
>>>> 'other','value': MSG(u"Other")} is always added to the end of this
>>>> list after all the items have been sorted?
>>>>
>>>> here is the code which returns this list:
>>>
>>> ? options.sort(key=itemgetter('name'))
>>> ? return options
>>>
>>> So, to answer the question you ask above, you can do:
>>>
>>> ? options.sort(key=itemgetter('name'))
>>> ? options.append({'industry':'travel',
>>> ? ? ?'name':'other','value':MSG(u"Other")}
>>> ? return options
>>>
>>> But I don't think that's the question you're looking to get answered.
>>>
>>> I think you want "other" to be found only at the end and not elsewhere.
>>>
>>> Then you might try excluding other from options allowing the above to
>>> append
>>> it to the end:
>>>
>>> for index, row in enumerate(topics.get_rows()):
>>> ? ?if row[0] != 'other':
>>> ? ? ? ?options.append({'name': row[0], 'value': MSG(row[1])})
>>>
>>> HTH,
>>>
>>> Emile
>>>
>>>
>>>
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From davea at ieee.org  Tue Sep 28 16:14:15 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 28 Sep 2010 10:14:15 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <AANLkTi=wGBGhMHpicsxG-OZsZEwghp8mrru9UbGRR882@mail.gmail.com>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>	<201009281046.20681.steve@pearwood.info>	<AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>	<201009282149.54175.steve@pearwood.info>
	<AANLkTi=wGBGhMHpicsxG-OZsZEwghp8mrru9UbGRR882@mail.gmail.com>
Message-ID: <4CA1F837.9000309@ieee.org>



On 2:59 PM, Alex Hall wrote:
> On 9/28/10, Steven D'Aprano<steve at pearwood.info>  wrote:
>> <snip>
>>
>> PyPy is a version of Python written in Python. It has an incredible
>> mission: to eventually produce versions of Python which are faster than
>> pure C, despite being written in Python itself. Although they have a
>> long, long way to go, they are making good progress, and PyPy can now
>> run Python code faster than CPython. PyPy is becoming a generalised
>> Just-In-Time compiler for high-level languages like Python.
> Okay, I now have to go investigate this and see how it is even
> possible; somewhere, the Python code has to get down to machine
> code...
>
Just-in-time compiling  (JIT) is taking some high-level construct, such 
as python byte code or a java class file, and compiling it into machine 
code, at the time of first execution.  Java uses it heavily, to achieve 
its performance level.  The standard CPython does not, but simply 
interprets those byte codes.

One advantage of just-in-time is that the translation can be specific to 
a particular processor, or even to a particular operating system and 
operating environment.  Conventional compiling is done by the developer, 
and he has to release multiple versions for multiple platforms.  And 
even then, he seldom takes advantage of the newer instructions of a 
given processor, which are changing quite frequently.  I'm sure there 
are at least a dozen different instruction supersets of the original 
Pentium processor, though most of the recent ones are relatively 
specialized (eg. for hashing, searching, encryption), and likely to 
affect libraries more than your main program.

DaveA


From flebber.crue at gmail.com  Tue Sep 28 16:22:38 2010
From: flebber.crue at gmail.com (Sayth Renshaw)
Date: Wed, 29 Sep 2010 00:22:38 +1000
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
Message-ID: <AANLkTikdfq5MVvDPgob-w05nRhF0Np7V0kYrA2mS9L1u@mail.gmail.com>

I read python from novice to professinal. I also read a lot of online guides
sometimes more beneficial than the books.

These links should help you

http://wiki.python.org/moin/BeginnersGuide

http://www.awaretek.com/tutorials.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/197665b9/attachment-0001.html>

From rwobben at hotmail.com  Tue Sep 28 16:22:48 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 28 Sep 2010 14:22:48 +0000
Subject: [Tutor] question
In-Reply-To: <SNT118-W573AE8023170002E4B97DCAE660@phx.gbl>
References: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>,
	<4CA1F573.6090506@ieee.org>,
	<SNT118-W573AE8023170002E4B97DCAE660@phx.gbl>
Message-ID: <SNT118-W470BECB65CBBC4338D65BAE660@phx.gbl>



 


From: rwobben at hotmail.com
To: davea at ieee.org
Subject: RE: [Tutor] question
Date: Tue, 28 Sep 2010 14:22:17 +0000





 
> Date: Tue, 28 Sep 2010 10:02:27 -0400
> From: davea at ieee.org
> To: rwobben at hotmail.com
> CC: tutor at python.org
> Subject: Re: [Tutor] question
> 
> 
> 
> On 2:59 PM, Roelof Wobben wrote:
> > Hello,
> >
> >
> > Im now studying this page :
> > http://openbookproject.net/thinkcs/python/english2e/ch16.html
> >
> > But I don't get it why aces are now lower then deuces in the cmp function.
> >
> >
> > Roelof
> >
> > 
> Why would you be surprised that aces are lower than deuces? If aces are 
> represented by 1, and deuces by 2, then 1 is less than 2.
> 
> Notice that because self.suit is compared first, an ace of spades is 
> higher than a deuce of hearts. It's only within the same suit that an 
> ace is "less than" a deuce.
> 
> DaveA
> 
> 
> 
> 

Hello Dave, 
 
In some games in the Netherlands Aces can have a value of 11 or 1 .
So if Aces are 11 then Deuces is lesser then Aces.
 
Can I say that the position of the list is a representation of the value.
 
Roelof
 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/06899fa1/attachment.html>

From jemejones at gmail.com  Tue Sep 28 16:39:21 2010
From: jemejones at gmail.com (Jeremy Jones)
Date: Tue, 28 Sep 2010 10:39:21 -0400
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <201009282147.42408.steve@pearwood.info>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
	<AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>
	<201009282147.42408.steve@pearwood.info>
Message-ID: <AANLkTikJxsvN+u4-g=n1N5hRa0rPM_YX7poPBGoeuEwu@mail.gmail.com>

On Tue, Sep 28, 2010 at 7:47 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Tue, 28 Sep 2010 07:37:12 pm Jeremy Jones wrote:
>
>> "Head First Programming: A Learner's Guide to Programming Using the
>> Python Language" by David Griffiths and Paul Barry was a great read.
>> It's unconventional (by their nature, all Head First books are),
>
>
> I've never heard of "Head First Programming" -- how are they
> unconventional?
>

Both HF Programming (currently out) and HF Python (currently being
written) are very example-driven and in the course of each example,
introduce a number of concepts.  So, rather than having a chapter on
lists, the books introduce lists as a part of an evolving example.
The "conventional" approach (in my view) is splitting a book into
chapters of such topics as variables, operators, lists, dicts, OO,
etc.  So, I hope that I conveyed the "unconventional" as a good thing,
because I definitely see it as such.  I love these books.  Honestly,
it's enjoyable to me just to see the craft these folks use to evolve a
problem and weave in new concepts all along the way.

>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From davea at ieee.org  Tue Sep 28 16:49:28 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 28 Sep 2010 10:49:28 -0400
Subject: [Tutor] question
In-Reply-To: <SNT118-W573AE8023170002E4B97DCAE660@phx.gbl>
References: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>,
	<4CA1F573.6090506@ieee.org>
	<SNT118-W573AE8023170002E4B97DCAE660@phx.gbl>
Message-ID: <4CA20078.5080203@ieee.org>

  On 9/28/2010 10:22 AM, Roelof Wobben wrote:
>
>
>
>> Date: Tue, 28 Sep 2010 10:02:27 -0400
>> From: davea at ieee.org
>> To: rwobben at hotmail.com
>> CC: tutor at python.org
>> Subject: Re: [Tutor] question
>>
>>
>>
>> On 2:59 PM, Roelof Wobben wrote:
>>> Hello,
>>>
>>>
>>> Im now studying this page :
>>> http://openbookproject.net/thinkcs/python/english2e/ch16.html
>>>
>>> But I don't get it why aces are now lower then deuces in the cmp function.
>>>
>>>
>>> Roelof
>>>
>>>
>> Why would you be surprised that aces are lower than deuces? If aces are
>> represented by 1, and deuces by 2, then 1 is less than 2.
>>
>> Notice that because self.suit is compared first, an ace of spades is
>> higher than a deuce of hearts. It's only within the same suit that an
>> ace is "less than" a deuce.
>>
>> DaveA
>>
>>
>>
>>
>
> Hello Dave,
>
>
>
> In some games in the Netherlands Aces can have a value of 11 or 1 .
>
> So if Aces are 11 then Deuces is lesser then Aces.
>
>
>
> Can I say that the position of the list is a representation of the value.
>
>
>
> Roelof
>
>
>   
The class attribute was assigned as follows:

  ranks  =  ["narf",  "Ace",  "2",  "3",  "4",  "5",  "6",  "7",
              "8",  "9",  "10",  "Jack",  "Queen",  "King"]


So "Ace" is at position 1.  And if you want an Ace, you'd have to supply a 1 to the constructor.

I would certainly agree that in many games this wouldn't be the desired case.  Some games specify aces higher than kings, some have no ordering among face cards, some let the player choose.

If the Card class needed to cover all cases, then one might need to make the __cmp__() method parameterizable, so that at different times, the cards might sort differently.

But this is one implementation of the Card class, and hopefully it's self-consistent in the course.



DaveA



> 		 	   		


From __peter__ at web.de  Tue Sep 28 17:41:22 2010
From: __peter__ at web.de (Peter Otten)
Date: Tue, 28 Sep 2010 17:41:22 +0200
Subject: [Tutor] if value in list of dictionaries
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<i7r2v6$bg2$1@dough.gmane.org>
	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>
	<4CA1E617.8090604@fenx.com>
	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
Message-ID: <i7t2ag$3du$1@dough.gmane.org>

Norman Khine wrote:

> thanks for the reply, i think i have it now, perhaps it could be done
> better

> >>> topics.sort(key=itemgetter('name'))
> >>> for i, t in enumerate(topics):
> ...     for (k, v) in t.iteritems():
> ...             if v == 'other':
> ...                     topics.append(topics.pop(i))
> ... 
 
You should never iterate over a list or dictionary and add or remove items 
to it at the same time. That is a recipe for disaster even if it doesn't 
fail explicitly*

As Christian Witts explains in the "trouble with list.remove() loop" thread 
you will not see all items.

I suggest that you use a better sort key instead:

>>> def sort_key(topic):
...     name = topic["name"]
...     return name == "other", name
...
>>> topics.sort(key=sort_key)

>>> pprint(topics)
[{'industry': 'travel',
  'name': 'assistant-manager',
  'value': 'Assistant Manager'},

<snip>

 {'industry': 'travel', 'name': 'university', 'value': 'University'},
 {'industry': 'travel', 'name': 'other', 'value': 'Other'}]

The above sort_key() checks only the "name" key for an "other" value. It 
will return a (True, name) tuple if the name is "other" and (False, name) 
else. As 

False < True 

it ensures that topics with topic["name"] == "other" are placed after all 
others. If (like your attempt suggests) you want to check all values instead 
of just the one associated with the "name" key use

def sort_key(topic):
    return "other" in topic.itervalues(), topic["name"]

Remember that both functions are case-sensitive.

Peter

(*) I'll leave it to Steven D'Aprano to add the fine print ;)


From emile at fenx.com  Tue Sep 28 17:50:51 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 28 Sep 2010 08:50:51 -0700
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>	<i7r2v6$bg2$1@dough.gmane.org>	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>	<4CA1E617.8090604@fenx.com>
	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
Message-ID: <i7t2sq$6pv$1@dough.gmane.org>

On 9/28/2010 7:12 AM Norman Khine said...
> thanks for the reply, i think i have it now, perhaps it could be done better
>

I think I'd use a helper function to sort:

def sortOtherToEnd(val):
   if val['name'] == 'other:
     return 'zzzz'
   return val['name']

#then sort it

topics.sort(key=sortOtherToEnd)

But, generally, I'd stop once I got it going without worrying too much 
about 'better' ways -- that's a subjective measure.  There is often one 
obvious way to do it, but unless you've seen that way before, there'll 
often be many alternatives that work as well.

HTH,

Emile


From __peter__ at web.de  Tue Sep 28 18:03:34 2010
From: __peter__ at web.de (Peter Otten)
Date: Tue, 28 Sep 2010 18:03:34 +0200
Subject: [Tutor] trouble with list.remove() loop
References: <49645.172.21.98.221.1285440289.squirrel@webmail.bris.ac.uk>
Message-ID: <i7t3k3$9vd$1@dough.gmane.org>

D Ryan (2) wrote:

> Hello all,
> I am currently trying to write a program which can find the solution to a
> game of hangman.
> In a part of the program, a user inputs a letter, a tester tells him if
> the word contains that letter, and then if the answer is no, all words
> containing that letter are removed from the list of remaining candidates.
> However, the code I've written seems to remove some, but not all the words
> containing the letter. Strangely though, if i run it a few more times it
> gets some of the ones it missed the 1st time round, untill after enough
> iterations it gets all of them. I cant understand why it doesnt remove all
> of them the first time round. I have cut the offending code and formatted
> it to work on its own, and also to fit into a relatively short email.
> 
> # A sample list of words, one of which is the answer.
> candidates = ["abacus","amazing",
>               "ozimandias",
>               "a","alphanumeric",
>               "functioning"]
> 
> # In the following code, the user has guessed the letter 'a',
> # and the tester has told him that the letter 'a' is not in the word.
> 
> user_guess="a"
> tester_response="no"
> 
> # The following code should eliminate all words which contain the letter
> # 'a', leaving only the word 'functioning' in the list
> 
> if tester_response in ("No","no","n","N","NO"):
>     for word in candidates:
>         if user_guess in word:
>             print word, "removed.."
>             candidates.remove(word)
> print candidates
> 
> Running once gives this output
> 
> abacus removed..
> ozimandias removed..
> alphanumeric removed..
> ['amazing', 'a', 'functioning']
> 
> But if i run it again it successfully removes 'amazing, and the next time
> it removes 'a', leaving the correct answer. I'm perplexed by this strange
> behaviour and would be most appreciative of any help. I'm very new to
> python so apologies for any formatting/style errors, and also for the
> simplicity of the problem.

I'd like to point out a robust method to avoid such pitfalls: create a new 
list instead of modifying the old one:

old_candidates = candidates
candidates = []
for word in old_candidates:
    if user_guess in word:
        print word, "removed"
    else:
        candidates.append(word)
print candidates

Often you can simplify that to a list comprehension like

candidates = [word for word in candidates if user_guess not in word]

Peter


From norman at khine.net  Tue Sep 28 18:37:09 2010
From: norman at khine.net (Norman Khine)
Date: Tue, 28 Sep 2010 18:37:09 +0200
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <i7t2sq$6pv$1@dough.gmane.org>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<i7r2v6$bg2$1@dough.gmane.org>
	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>
	<4CA1E617.8090604@fenx.com>
	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
	<i7t2sq$6pv$1@dough.gmane.org>
Message-ID: <AANLkTikVMaqDUE7Ev37sO8WbqNYwQ4q0gXNrN62+n4Xb@mail.gmail.com>

thank you, here is the updated version:

http://pastie.org/1186860

On Tue, Sep 28, 2010 at 5:50 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 9/28/2010 7:12 AM Norman Khine said...
>>
>> thanks for the reply, i think i have it now, perhaps it could be done
>> better
>>
>
> I think I'd use a helper function to sort:
>
> def sortOtherToEnd(val):
> ?if val['name'] == 'other:
> ? ?return 'zzzz'
> ?return val['name']
>
> #then sort it
>
> topics.sort(key=sortOtherToEnd)
>
> But, generally, I'd stop once I got it going without worrying too much about
> 'better' ways -- that's a subjective measure. ?There is often one obvious
> way to do it, but unless you've seen that way before, there'll often be many
> alternatives that work as well.
>
> HTH,
>
> Emile
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From emile at fenx.com  Tue Sep 28 18:53:01 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 28 Sep 2010 09:53:01 -0700
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <AANLkTikVMaqDUE7Ev37sO8WbqNYwQ4q0gXNrN62+n4Xb@mail.gmail.com>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>	<i7r2v6$bg2$1@dough.gmane.org>	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>	<4CA1E617.8090604@fenx.com>	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>	<i7t2sq$6pv$1@dough.gmane.org>
	<AANLkTikVMaqDUE7Ev37sO8WbqNYwQ4q0gXNrN62+n4Xb@mail.gmail.com>
Message-ID: <i7t6h7$o2s$1@dough.gmane.org>

On 9/28/2010 9:37 AM Norman Khine said...
> thank you, here is the updated version:
>
> http://pastie.org/1186860
>


The only obvious redundancy is the duplicated sort of options just 
before the return.  You only need the newer sort_key based one.

Emile


From bill at celestial.net  Tue Sep 28 19:12:19 2010
From: bill at celestial.net (Bill Campbell)
Date: Tue, 28 Sep 2010 10:12:19 -0700
Subject: [Tutor] list comprehension, efficiency?
In-Reply-To: <i7s0gg$ct0$1@dough.gmane.org>
References: <AANLkTik21ZNCoD3565e-DsVMBxZpSPK+3Reg_QtUc1C_@mail.gmail.com>
	<i7s0gg$ct0$1@dough.gmane.org>
Message-ID: <20100928171219.GB31353@ayn.mi.celestial.com>

On Tue, Sep 28, 2010, Lie Ryan wrote:
>On 09/28/10 13:57, Bill Allen wrote:
>> I can now see that quite a bit of the code I write dealing with lists
>> can be done with list
>> comprehensions.   My question is this, is the list comprehension styled
>> code generally
>> more efficient at runtime?  If so, why?
>
>Yes, because the looping in list comprehension is done in C instead of a
>python construct. However, they are the type of efficiency that you
>shouldn't bother yourself with unless you're microoptimizing.

True enough, but dealing with large lists can be expensive,
particularly when appending.  Before I discovered sets, I found
significant time savings by creating a dictionary, adding as
necessary, then use d.keys() to get the keys back.

This became a significant factor when I was selecting unique
lines from about 1.3 million samples.

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

Independent self-reliant people would be a counterproductive anachronism
in the collective society of the future where people will be defined by
their associations.  1896 John Dewey, educational philosopher, proponent
of modern public schools.

From norman at khine.net  Tue Sep 28 20:13:51 2010
From: norman at khine.net (Norman Khine)
Date: Tue, 28 Sep 2010 20:13:51 +0200
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <i7t6h7$o2s$1@dough.gmane.org>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<i7r2v6$bg2$1@dough.gmane.org>
	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>
	<4CA1E617.8090604@fenx.com>
	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
	<i7t2sq$6pv$1@dough.gmane.org>
	<AANLkTikVMaqDUE7Ev37sO8WbqNYwQ4q0gXNrN62+n4Xb@mail.gmail.com>
	<i7t6h7$o2s$1@dough.gmane.org>
Message-ID: <AANLkTim0YMd8WvtXd6tJnzYa=m6+RVe0QQyerEqqigcc@mail.gmail.com>

ok, great.

one thing i wanted to ask is how could i extend the class so that i
can just change the name of the csv file?

On Tue, Sep 28, 2010 at 6:53 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 9/28/2010 9:37 AM Norman Khine said...
>>
>> thank you, here is the updated version:
>>
>> http://pastie.org/1186860
>>
>
>
> The only obvious redundancy is the duplicated sort of options just before
> the return. ?You only need the newer sort_key based one.
>
> Emile
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
?u?op ?p?sdn p,u?n? p??o? ??? ??s no? '?u???? s???? ??? pu? '?u??uo?
?q s,??? ???
%>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or
chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] )

From roberto03 at gmail.com  Tue Sep 28 20:15:39 2010
From: roberto03 at gmail.com (roberto)
Date: Tue, 28 Sep 2010 20:15:39 +0200
Subject: [Tutor] function error
In-Reply-To: <AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
Message-ID: <AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>

On Tue, Sep 28, 2010 at 12:35 PM, Nitin Das <nitin.162 at gmail.com> wrote:
> It seems that ur?turtle.position doesn't return a list because of this when
> indexing is done on that u get this kind of error.
> --nitin

it seemed to me that kind of error but then i found that it was a
list, as expected:

$  type(turtle.position())
$ <type 'list'>
$ abs(turtle.position()[0])
   13.858469413370102

that's why i'm going crazy ...

>
> On Tue, Sep 28, 2010 at 3:39 PM, Alan Gauld <alan.gauld at btinternet.com>
> wrote:
>>
>> "roberto" <roberto03 at gmail.com> wrote
>>
>>> i have the following error when i call this function:
>>> ?20 def outOfBounds():
>>> ---> 21 ? ? ? ? if abs(turtle.position()[0]) >
>>> turtle.window_height()/2 or abs(turtle.position()[1]) >
>>> turtle.window_width()/2:
>>> ? ?22 ? ? ? ? ? ? ? ? return "true"
>>> ? ?23 ? ? ? ? else:
>>>
>>> TypeError: 'function' object is unsubscriptable
>>>
>>> but i can't really figure out where is the problem with this function
>>> 'unsubscriptable';
>>
>> This means you are trying to use [] on a function.
>> eg you might be doing turtle.position[1] instead of turtle.position()[1]
>>
>> I can't see it in your code sample but I'd check carefully that your
>> parens() all balance correctly and are in the right place...
>>
>> HTH,
>>
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
roberto

From evert.rol at gmail.com  Tue Sep 28 20:26:30 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 28 Sep 2010 20:26:30 +0200
Subject: [Tutor] function error
In-Reply-To: <AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
	<AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
Message-ID: <38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>

>> It seems that ur turtle.position doesn't return a list because of this when
>> indexing is done on that u get this kind of error.
>> --nitin
> 
> it seemed to me that kind of error but then i found that it was a
> list, as expected:
> 
> $  type(turtle.position())
> $ <type 'list'>
> $ abs(turtle.position()[0])
>   13.858469413370102
> 
> that's why i'm going crazy ...

Perhaps if you provide the full traceback from the error (assuming you're still getting this error); tracebacks generally show the offending code as well. It may be something that's simply overlooked but shows in the traceback.



>> On Tue, Sep 28, 2010 at 3:39 PM, Alan Gauld <alan.gauld at btinternet.com>
>> wrote:
>>> 
>>> "roberto" <roberto03 at gmail.com> wrote
>>> 
>>>> i have the following error when i call this function:
>>>>  20 def outOfBounds():
>>>> ---> 21         if abs(turtle.position()[0]) >
>>>> turtle.window_height()/2 or abs(turtle.position()[1]) >
>>>> turtle.window_width()/2:
>>>>    22                 return "true"
>>>>    23         else:
>>>> 
>>>> TypeError: 'function' object is unsubscriptable
>>>> 
>>>> but i can't really figure out where is the problem with this function
>>>> 'unsubscriptable';
>>> 
>>> This means you are trying to use [] on a function.
>>> eg you might be doing turtle.position[1] instead of turtle.position()[1]
>>> 
>>> I can't see it in your code sample but I'd check carefully that your
>>> parens() all balance correctly and are in the right place...
>>> 
>>> HTH,
>>> 
>>> 
>>> --
>>> Alan Gauld
>>> Author of the Learn to Program web site
>>> http://www.alan-g.me.uk/
>>> 
>>> 
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>> 
>> 
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>> 
> 
> 
> 
> -- 
> roberto
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From susana.delgado_s at utzmg.edu.mx  Tue Sep 28 20:33:51 2010
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Tue, 28 Sep 2010 13:33:51 -0500
Subject: [Tutor] Writing a txt from dbf
Message-ID: <AANLkTi=SGUgXYSMN7NCrnzc5P1+5M=VTxarR1gRjaek2@mail.gmail.com>

Hello dear pythonists:

I'm developing an application in python, I'm new using this programming
language I used to work with Java, but in my job my superiors suggested me
to develop in this language.
I'm trying to read a dbf file, I already done it but my code shows me all
the lines without spaces, I want it toshow line per line and then write the
lines into a plain txt file. My code is:

from dbf import *
from string import strip
import sys
def demo1():
 a = open ("archivo.txt","w")
 dbf = Dbf('tapalpa_05_plani_point.dbf',new=False)

 for k in dbf:
  print '%s'%(strip(k[2]))

  l=()
  l=(strip(k[2]))
  a.write(l)

 dbf.close()
 a.close()


demo1()
I hope you can help me.
Thank you!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/9db29c58/attachment.html>

From mehgcap at gmail.com  Tue Sep 28 20:50:43 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Tue, 28 Sep 2010 14:50:43 -0400
Subject: [Tutor] filling 2d array with zeros
In-Reply-To: <4CA1F837.9000309@ieee.org>
References: <AANLkTinEy+ubfuS2FEebDCeeP3Sh=37GE23XyN7mMtfa@mail.gmail.com>
	<201009281046.20681.steve@pearwood.info>
	<AANLkTing4qqpWkeGXwhgDRjsz2fZ4MN+grLX7yGM0h69@mail.gmail.com>
	<201009282149.54175.steve@pearwood.info>
	<AANLkTi=wGBGhMHpicsxG-OZsZEwghp8mrru9UbGRR882@mail.gmail.com>
	<4CA1F837.9000309@ieee.org>
Message-ID: <AANLkTikXEj_V_U9ONPWXoA4m4WPc2wtTXfk21HEMtaBT@mail.gmail.com>

On 9/28/10, Dave Angel <davea at ieee.org> wrote:
>
>
> On 2:59 PM, Alex Hall wrote:
>> On 9/28/10, Steven D'Aprano<steve at pearwood.info>  wrote:
>>> <snip>
>>>
>>> PyPy is a version of Python written in Python. It has an incredible
>>> mission: to eventually produce versions of Python which are faster than
>>> pure C, despite being written in Python itself. Although they have a
>>> long, long way to go, they are making good progress, and PyPy can now
>>> run Python code faster than CPython. PyPy is becoming a generalised
>>> Just-In-Time compiler for high-level languages like Python.
>> Okay, I now have to go investigate this and see how it is even
>> possible; somewhere, the Python code has to get down to machine
>> code...
>>
> Just-in-time compiling  (JIT) is taking some high-level construct, such
> as python byte code or a java class file, and compiling it into machine
> code, at the time of first execution.  Java uses it heavily, to achieve
> its performance level.  The standard CPython does not, but simply
> interprets those byte codes.
>
> One advantage of just-in-time is that the translation can be specific to
> a particular processor, or even to a particular operating system and
> operating environment.  Conventional compiling is done by the developer,
> and he has to release multiple versions for multiple platforms.  And
> even then, he seldom takes advantage of the newer instructions of a
> given processor, which are changing quite frequently.  I'm sure there
> are at least a dozen different instruction supersets of the original
> Pentium processor, though most of the recent ones are relatively
> specialized (eg. for hashing, searching, encryption), and likely to
> affect libraries more than your main program.
Thanks for the info. That explains why Pypy said it only works on
Intel-based systems for the moment, and why special things must be
done for 64-bit processors.
>
> DaveA
>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From rwobben at hotmail.com  Tue Sep 28 21:15:00 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 28 Sep 2010 19:15:00 +0000
Subject: [Tutor] question
In-Reply-To: <SNT118-W487982F67A45AB9229C102AE660@phx.gbl>
References: <SNT118-W7B73F6A4B87ACBBB04BFCAE660@phx.gbl>,
	<4CA1F573.6090506@ieee.org>,
	<SNT118-W573AE8023170002E4B97DCAE660@phx.gbl>,
	<4CA20078.5080203@ieee.org>,
	<SNT118-W487982F67A45AB9229C102AE660@phx.gbl>
Message-ID: <SNT118-W271B06B5B6447DA752C639AE660@phx.gbl>



 


From: rwobben at hotmail.com
To: davea at ieee.org
Subject: RE: [Tutor] question
Date: Tue, 28 Sep 2010 19:14:29 +0000





 
> Date: Tue, 28 Sep 2010 10:49:28 -0400
> From: davea at ieee.org
> To: rwobben at hotmail.com; tutor at python.org
> Subject: Re: [Tutor] question
> 
> On 9/28/2010 10:22 AM, Roelof Wobben wrote:
> >
> >
> >
> >> Date: Tue, 28 Sep 2010 10:02:27 -0400
> >> From: davea at ieee.org
> >> To: rwobben at hotmail.com
> >> CC: tutor at python.org
> >> Subject: Re: [Tutor] question
> >>
> >>
> >>
> >> On 2:59 PM, Roelof Wobben wrote:
> >>> Hello,
> >>>
> >>>
> >>> Im now studying this page :
> >>> http://openbookproject.net/thinkcs/python/english2e/ch16.html
> >>>
> >>> But I don't get it why aces are now lower then deuces in the cmp function.
> >>>
> >>>
> >>> Roelof
> >>>
> >>>
> >> Why would you be surprised that aces are lower than deuces? If aces are
> >> represented by 1, and deuces by 2, then 1 is less than 2.
> >>
> >> Notice that because self.suit is compared first, an ace of spades is
> >> higher than a deuce of hearts. It's only within the same suit that an
> >> ace is "less than" a deuce.
> >>
> >> DaveA
> >>
> >>
> >>
> >>
> >
> > Hello Dave,
> >
> >
> >
> > In some games in the Netherlands Aces can have a value of 11 or 1 .
> >
> > So if Aces are 11 then Deuces is lesser then Aces.
> >
> >
> >
> > Can I say that the position of the list is a representation of the value.
> >
> >
> >
> > Roelof
> >
> >
> > 
> The class attribute was assigned as follows:
> 
> ranks = ["narf", "Ace", "2", "3", "4", "5", "6", "7",
> "8", "9", "10", "Jack", "Queen", "King"]
> 
> 
> So "Ace" is at position 1. And if you want an Ace, you'd have to supply a 1 to the constructor.
> 
> I would certainly agree that in many games this wouldn't be the desired case. Some games specify aces higher than kings, some have no ordering among face cards, some let the player choose.
> 
> If the Card class needed to cover all cases, then one might need to make the __cmp__() method parameterizable, so that at different times, the cards might sort differently.
> 
> But this is one implementation of the Card class, and hopefully it's self-consistent in the course.
> 
> 
> 
> DaveA
> 
> 
> 
> > 
> 
 
Oke,
 
Thanks.
Then now figuring out how to solve this problem :
 
Modify __cmp__ so that Aces are ranked higher than Kings
 
So aces with value 1 must be higher then Kings with 11 
 
I think I have to make another rule in the rank part like this 
 
If self.rank = Aces and self.rank = Kings then return -1 or 1
 
Tomorrrow I will investigate this. 
 
Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/52048641/attachment.html>

From joel.goldstick at gmail.com  Tue Sep 28 21:37:44 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 28 Sep 2010 15:37:44 -0400
Subject: [Tutor] Fwd:  Writing a txt from dbf
In-Reply-To: <AANLkTinTsStqfh-1Zu6Nmb0A451AS7XbtznD3onD_U-E@mail.gmail.com>
References: <AANLkTi=SGUgXYSMN7NCrnzc5P1+5M=VTxarR1gRjaek2@mail.gmail.com>
	<AANLkTinTsStqfh-1Zu6Nmb0A451AS7XbtznD3onD_U-E@mail.gmail.com>
Message-ID: <AANLkTinr8=RXsd2fKTpZpb23TcDHm9AQ+Wamua8wXRo1@mail.gmail.com>

On Tue, Sep 28, 2010 at 2:33 PM, Susana Iraiis Delgado Rodriguez
<susana.delgado_s at utzmg.edu.mx> wrote:
> Hello dear pythonists:
>
> I'm developing an application in python, I'm new using this programming
> language I used to work with Java, but in my job my superiors suggested me
> to develop in this language.
> I'm trying to read a dbf file, I already done it but my code shows me all
> the lines without spaces, I want it toshow line per line and then write the
> lines into a plain txt file. My code is:
>
> from dbf import *
> from string import strip
> import sys
> def demo1():
> ?a = open ("archivo.txt","w")
> ?dbf = Dbf('tapalpa_05_plani_point.dbf',new=False)
>
> ?for k in dbf:
> ??print '%s'%(strip(k[2]))
>
> ??l=()
> ??l=(strip(k[2]))
> ??a.write(l)
>
> ?dbf.close()
> ?a.close()
>
>
> demo1()
> I hope you can help me.
> Thank you!
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

I was going to run your code, but I am not sure what dbf module you
are using. ?I am running UBUNTU 9.10 and can't find a dbf module in
the repository.

What are you running?

--
Joel Goldstick



-- 
Joel Goldstick

From kb1pkl at aim.com  Tue Sep 28 22:03:21 2010
From: kb1pkl at aim.com (Corey Richardson)
Date: Tue, 28 Sep 2010 16:03:21 -0400
Subject: [Tutor] Operating in Place
Message-ID: <4CA24A09.2020309@aim.com>

  Hello tutors.

I hate doing this:
             string = string.lower()

Is there a way to do it without the "string =" part? Thanks.


From anand.shashwat at gmail.com  Tue Sep 28 22:12:20 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Wed, 29 Sep 2010 01:42:20 +0530
Subject: [Tutor] Operating in Place
In-Reply-To: <4CA24A09.2020309@aim.com>
References: <4CA24A09.2020309@aim.com>
Message-ID: <AANLkTi=4K46VH+i1AKkM3OPiiugL6-gZWa3BaqN3trrH@mail.gmail.com>

On Wed, Sep 29, 2010 at 1:33 AM, Corey Richardson <kb1pkl at aim.com> wrote:

>  Hello tutors.
>
> I hate doing this:
>            string = string.lower()
>
> Is there a way to do it without the "string =" part? Thanks.
>

1. string is a module which is deprecated. You should probably use str or s
in your example.
2. strings in python are immutable. If you need to change something, you
need to create a new string.


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/09b314a3/attachment.html>

From waynejwerner at gmail.com  Tue Sep 28 22:17:15 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 28 Sep 2010 15:17:15 -0500
Subject: [Tutor] Operating in Place
In-Reply-To: <4CA24A09.2020309@aim.com>
References: <4CA24A09.2020309@aim.com>
Message-ID: <AANLkTik5m8V_5GPRB0ZHJm4MSj+9W8PHvvGr5uRK66qB@mail.gmail.com>

On Tue, Sep 28, 2010 at 3:03 PM, Corey Richardson <kb1pkl at aim.com> wrote:

>  Hello tutors.
>
> I hate doing this:
>            string = string.lower()
>
> Is there a way to do it without the "string =" part? Thanks.
>

Not with a string. I suppose if you had your own class you could create
something, but you'd be doing the same thing behind the scenes.

Is there any particular reason why you don't like doing it? It's explicit
and easy to understand - saying that you want the lowercase version of the
string, but you don't care about the original string.

At least that's my take on it,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/d68c9f60/attachment.html>

From steve at alchemy.com  Tue Sep 28 22:27:59 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Tue, 28 Sep 2010 13:27:59 -0700
Subject: [Tutor] Operating in Place
In-Reply-To: <4CA24A09.2020309@aim.com>
References: <4CA24A09.2020309@aim.com>
Message-ID: <4CA24FCF.7050702@alchemy.com>

On 28-Sep-10 13:03, Corey Richardson wrote:
> I hate doing this:
> string = string.lower()
>
> Is there a way to do it without the "string =" part? Thanks.

Depends on the class.  In this specific case, string objects are 
immutable (for some good reasons which are beyond the immediate point), 
so once created, they can't be changed.  They can, of course, be used to 
create new strings, which is what string.lower() is doing.  And that new 
string is then given the name "string" again, replacing the old string 
object (which may still have other names referencing it elsewhere).

If you were wanting to modify a mutable object in-place, Python would be 
happy to oblige.  But not strings.

Sorry :)

From ranceh at gmail.com  Tue Sep 28 22:32:52 2010
From: ranceh at gmail.com (Rance Hall)
Date: Tue, 28 Sep 2010 15:32:52 -0500
Subject: [Tutor] Operating in Place
In-Reply-To: <4CA24A09.2020309@aim.com>
References: <4CA24A09.2020309@aim.com>
Message-ID: <AANLkTin51hPbPTDk6CF756591N2vwKhYFPsSu9HBDR4h@mail.gmail.com>

On Tue, Sep 28, 2010 at 3:03 PM, Corey Richardson <kb1pkl at aim.com> wrote:
> ?Hello tutors.
>
> I hate doing this:
> ? ? ? ? ? ?string = string.lower()
>
> Is there a way to do it without the "string =" part? Thanks.
>

I suppose the best answer is it depends on what you are doing with
string after you do string.lower()

you can use the string.lower() directly in IF statements and such without worry


a = "TEST"

if a.lower() == "test":
   do stuff

works for me.even on the new 3.1

From emile at fenx.com  Tue Sep 28 22:34:59 2010
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 28 Sep 2010 13:34:59 -0700
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <AANLkTim0YMd8WvtXd6tJnzYa=m6+RVe0QQyerEqqigcc@mail.gmail.com>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>	<i7r2v6$bg2$1@dough.gmane.org>	<AANLkTinfi2KkBUOBbcOOz5n3G=m+Cz7BhB5NEsT6BOiG@mail.gmail.com>	<4CA1E617.8090604@fenx.com>	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>	<i7t2sq$6pv$1@dough.gmane.org>	<AANLkTikVMaqDUE7Ev37sO8WbqNYwQ4q0gXNrN62+n4Xb@mail.gmail.com>	<i7t6h7$o2s$1@dough.gmane.org>
	<AANLkTim0YMd8WvtXd6tJnzYa=m6+RVe0QQyerEqqigcc@mail.gmail.com>
Message-ID: <i7tjhe$ov1$1@dough.gmane.org>

On 9/28/2010 11:13 AM Norman Khine said...
> ok, great.
>
> one thing i wanted to ask is how could i extend the class so that i
> can just change the name of the csv file?

Python provides for instance initialization with a class __init__ 
method, so you could modify your class as follows:



def sort_key(option):
     return "other" in option.itervalues(), option["name"]


class BusinessType(Enumerate):
     def __init__(self,cvsfile):
         self.cvsfile = cvsfile
     def get_options(cls):
         context = get_context()
         here = context.resource
         root = here.get_root().handler
         topics = root.get_handler(self.cvsfile)
         options = []
         for index, row in enumerate(topics.get_rows()):
             options.append({'name': row[0], 'value': MSG(row[1])})
         options.sort(key=sort_key)
         return options

Then, instead of invoking:

options = BusinessType().get_options()

You'd write:

options = BusinessType('topics.cvs').get_options()


Emile


From carter.danforth at gmail.com  Tue Sep 28 23:11:05 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Tue, 28 Sep 2010 17:11:05 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <4CA15135.3050506@ieee.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
Message-ID: <AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>

Thanks for the replies, Dave and Joel. The reason I'm not just using the
time or datetime modules for a random date is because it's restricted to
1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
about the leap years, Dave, as well the class instances; just updated it and
it's all working now, and also included the rest of the code too w/ answer
verification and time tracking.

I want to start using this program to test myself for speed calculation
using Zeller's formula, it's pretty cool for determining the days of dates -
http://mathforum.org/dr/math/faq/faq.calendar.html

Because of the way variables C and D are split up from the year in the
formula, I split up the year for self.c and self.y.

------------------------

import random, time, datetime, calendar

class Date:
    def __init__(self):
        self.c = random.randint(16,30)
        self.y = random.randint(0,99)
        self.month = random.randint(1,12)
        self.year = self.c*100 + self.y

        apr = [4,6,9,11]
        feb = [2]
        notleap = [1700, 1800, 1900, 3000]

        if self.month in feb:
            if self.year%4 == 0:
                if self.year in notleap:
                    self.k = random.randint(1,28)
                else:
                    self.k = random.randint(1,29)
            else:
                self.k = random.randint(1,28)
        elif self.month in apr:
            self.k = random.randint(1,30)
        else:
            self.k = random.randint(1,31)

        if self.month in [1,2]:
            d = self.y - 1
            m = self.month + 10
        else:
            d = self.y
            m = self.month - 2

        z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c

        if z < 0:
            r = (abs(z)/7)*7 + z + 7
        else:
            r = z%7

        dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4:
'Thursday', 5: 'Friday', 6: 'Saturday' }
        self.day = dict[r]

t1m = time.localtime().tm_min
t1s = time.localtime().tm_sec
t1 = t1m + t1s/100.0
n = 0
x = 0

while n < 10:
    newdate = Date()

    print '\n',calendar.month_name[newdate.month], newdate.k,',',
newdate.year,'=',
    answer = raw_input()
    if answer.capitalize() == newdate.day:
        pass
    else:
        x += 1
    n += 1

t2m = time.localtime().tm_min
t2s = time.localtime().tm_sec
t2 = t2m + t2s/100.0
td = t2 - t1

print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal time:',td


On Mon, Sep 27, 2010 at 10:21 PM, Dave Angel <davea at ieee.org> wrote:

>
>
> On 2:59 PM, Steven D'Aprano wrote:
>
> On Tue, 28 Sep 2010 08:55:36 am Carter Danforth wrote:
>
>
>  class Date:
>     c = random.randint(16,30)
>     y = random.randint(0,99)
>     month = random.randint(1,12)
>
>  Here's your problem: you are creating a class where all the attributes
> (called "members" in some other languages) belong to the class and are
> shared by all instances.
>
> Python classes are themselves objects, and the code inside the class
> body gets executed *once*, when the class is created. So in this case,
> the Date class chooses a single random month, *once*, and all instances
> share this attribute Date.month.
>
> To get the behaviour you are after, you need to use instance attributes,
> which means referring to self. The usual place to do this is in the
> __init__ method, which is called when the instance is being
> initialised:
>
> class Date:
>     def __init__(self):
>         self.month = random.randint(1,12)
>         # etc.
>
>
>
> By the way, why do you calculate a century and year separately, then add
> c+y to get the year? It would be easier to just say:
>
> year = random.randint(1600, 3099)
>
>
>
>
>  That's the big problem, although it's also worth pointing out that you'll
> need a new instance each time through the loop.  It's not enough to call
> Date(), you also have to bind it to a name, and use that name for attribute
> lookup.    So something like
>     mydate = Date()
>     year = mydate.y + ....
>
> But there are at least a few subtle problems left.  One is that many of the
> years are divisible by four but do not have 29 days in February.  For
> example, 1800, 1900, 2100 are not leap years.
>
> Next problem is that the dates are not evenly distributed over the entire
> range of years.  The 14th of February will be more likely to be chosen than
> the sixth of July.  You can decide that this is deliberate, but it is a
> consideration.
>
> Third, the program doesn't do anything to check the user's answer.  For
> that matter, there's no timing going on either.
>
> Depending on the learning goals of this project, I'd consider using the
> datetime module, and method:
>
> mydate = date.fromordinal(*ordinal*)
>
> Now you can make a single randint() call, once you precalculate the
> starting and ending dates desired.   And this module also gives you other
> things you need, such as the weekday() method.
>
> DaveA
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/d084885e/attachment-0001.html>

From steve at pearwood.info  Tue Sep 28 23:33:56 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 Sep 2010 07:33:56 +1000
Subject: [Tutor] if value in list of dictionaries
In-Reply-To: <i7t2ag$3du$1@dough.gmane.org>
References: <AANLkTinwoF_78WkhWY04bm+qC-btRjDiUOaGSjmS804Q@mail.gmail.com>
	<AANLkTikAbbBAaqE0sJQ1vYXkj_H9WtvowU+ZCeFfEha6@mail.gmail.com>
	<i7t2ag$3du$1@dough.gmane.org>
Message-ID: <201009290733.56883.steve@pearwood.info>

On Wed, 29 Sep 2010 01:41:22 am Peter Otten wrote:

> You should never iterate over a list or dictionary and add or remove
> items to it at the same time. That is a recipe for disaster even if
> it doesn't fail explicitly*
[...]

> (*) I'll leave it to Steven D'Aprano to add the fine print ;)


I'll be satisfied if you merely add the word "almost" between "should" 
and "never" :)



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 23:46:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 Sep 2010 07:46:15 +1000
Subject: [Tutor] Operating in Place
In-Reply-To: <4CA24A09.2020309@aim.com>
References: <4CA24A09.2020309@aim.com>
Message-ID: <201009290746.15696.steve@pearwood.info>

On Wed, 29 Sep 2010 06:03:21 am Corey Richardson wrote:
>   Hello tutors.
>
> I hate doing this:
>              string = string.lower()
>
> Is there a way to do it without the "string =" part? Thanks.

No, strings are immutable. Once they're created, they cannot be changed.

This is no different from:

x = 42
x = x/2  # or x /= 2 if you prefer

instead of:

x = 42
x/2


As an alternative you could look at the UserString module, and the 
MutableString class it includes, but MutableString has some serious 
limitations and is not really meant for serious work. But it might do 
the job you want.



-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 23:56:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 Sep 2010 07:56:26 +1000
Subject: [Tutor] Writing a txt from dbf
In-Reply-To: <AANLkTi=SGUgXYSMN7NCrnzc5P1+5M=VTxarR1gRjaek2@mail.gmail.com>
References: <AANLkTi=SGUgXYSMN7NCrnzc5P1+5M=VTxarR1gRjaek2@mail.gmail.com>
Message-ID: <201009290756.26507.steve@pearwood.info>

On Wed, 29 Sep 2010 04:33:51 am Susana Iraiis Delgado Rodriguez wrote:
> Hello dear pythonists:
>
> I'm developing an application in python, I'm new using this
> programming language I used to work with Java, but in my job my
> superiors suggested me to develop in this language.
> I'm trying to read a dbf file, I already done it but my code shows me
> all the lines without spaces, I want it toshow line per line and then
> write the lines into a plain txt file.

I am not sure what you mean. My guess is that you want something like:

alpha
beta
gamma
delta

in the file, but instead you get:

alphabetagammadelta


Am I right?



> My code is: 
>
> from dbf import *
> from string import strip

There is no need for this any more, as the functions in the string 
module are now also available as string methods. So instead of:

import string
print string.lower(my_string)


you can write:

my_string.lower()



> import sys
> def demo1():
>  a = open ("archivo.txt","w")
>  dbf = Dbf('tapalpa_05_plani_point.dbf',new=False)

As a matter of style, it is normal to use 4 spaces for indents, not 1. 
You are welcome to use whatever you like in your own code, but many 
people find 1 space indents hard to see and so when writing for others 
(such as when asking a question here) you should use at least 2 spaces.


>  for k in dbf:
>   print '%s'%(strip(k[2]))

The print command automatically adds a newline after the string, so each 
printed string should be on its own line. But later, when you write the 
string to the file, you must add the newline yourself.

>   l=()
>   l=(strip(k[2]))
>   a.write(l)

There's no need to clear l with the line l=() first. Just write:

    l = k[2].strip()
    a.write(l + '\n')




-- 
Steven D'Aprano

From steve at pearwood.info  Tue Sep 28 23:56:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 Sep 2010 07:56:47 +1000
Subject: [Tutor] Operating in Place
In-Reply-To: <AANLkTi=4K46VH+i1AKkM3OPiiugL6-gZWa3BaqN3trrH@mail.gmail.com>
References: <4CA24A09.2020309@aim.com>
	<AANLkTi=4K46VH+i1AKkM3OPiiugL6-gZWa3BaqN3trrH@mail.gmail.com>
Message-ID: <201009290756.48194.steve@pearwood.info>

On Wed, 29 Sep 2010 06:12:20 am Shashwat Anand wrote:
> On Wed, Sep 29, 2010 at 1:33 AM, Corey Richardson <kb1pkl at aim.com> 
wrote:
> >  Hello tutors.
> >
> > I hate doing this:
> >            string = string.lower()
> >
> > Is there a way to do it without the "string =" part? Thanks.
>
> 1. string is a module which is deprecated. You should probably use
> str or s in your example.

Actually, in this case Corey is not using the string module, but is 
using string as the name of a variable.



-- 
Steven D'Aprano

From mehgcap at gmail.com  Tue Sep 28 23:58:28 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Tue, 28 Sep 2010 17:58:28 -0400
Subject: [Tutor] using "in" with a dictionary
Message-ID: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>

Hi all, yet again:
I have a dictionary that will look something like:
d={
 (1,2):"a",
 (3,4):"b"
}

How can I say:
if (1,2) in d: print d[(1,2)]
This is false, so I expect to have to use d.keys, but I am not quite sure how.
I will be using this in a loop, and I have to know if there is a key
in the dictionary called (i,j) and, if there is, I have to grab the
value at that slot. If not I have to print something else. When I
tried "in" in the interpreter, I got something about builtin function
not being iterable. TIA for any suggestions.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From waynejwerner at gmail.com  Wed Sep 29 00:10:52 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 28 Sep 2010 17:10:52 -0500
Subject: [Tutor] using "in" with a dictionary
In-Reply-To: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
References: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
Message-ID: <AANLkTi=xARJ7dgygd4WvxqKbf-2i-kFXKiLgj0G7szmp@mail.gmail.com>

On Tue, Sep 28, 2010 at 4:58 PM, Alex Hall <mehgcap at gmail.com> wrote:

> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
>  (1,2):"a",
>  (3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]
> This is false, so I expect to have to use d.keys, but I am not quite sure
> how.
> I will be using this in a loop, and I have to know if there is a key
> in the dictionary called (i,j) and, if there is, I have to grab the
> value at that slot. If not I have to print something else. When I
> tried "in" in the interpreter, I got something about builtin function
> not being iterable. TIA for any suggestions.
>

 >>> d = {(1,2):"a"}
>>> if (1,2) in d:
...     print d[(1,2)]
...
a

you tried that?

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/d0311024/attachment.html>

From steve at alchemy.com  Wed Sep 29 00:12:50 2010
From: steve at alchemy.com (Steve Willoughby)
Date: Tue, 28 Sep 2010 15:12:50 -0700
Subject: [Tutor] using "in" with a dictionary
In-Reply-To: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
References: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
Message-ID: <4CA26862.1080503@alchemy.com>

On 28-Sep-10 14:58, Alex Hall wrote:
> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
>   (1,2):"a",
>   (3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]

Did you try this?  It looks fine to me as it is.
(1,2) is an immutable value (a tuple), so it is able to be used as a 
dictionary key.

if (1,2) in d

is perfectly valid, and would yield the True value as a result

if (1,2) in d: print d[(1,2)]

also is fine.  What specifically happens when you try this?


> This is false, so I expect to have to use d.keys, but I am not quite sure how.
> I will be using this in a loop, and I have to know if there is a key
> in the dictionary called (i,j) and, if there is, I have to grab the
> value at that slot. If not I have to print something else. When I
> tried "in" in the interpreter, I got something about builtin function
> not being iterable. TIA for any suggestions.
>

Sounds like there's more in your code than in your question.  If you 
give us a more complete picture of what you're doing, we can likely be 
more helpful to you.

if i=1 and j=2, then:

if (i,j) in d

would also be true.

From steve at pearwood.info  Wed Sep 29 00:15:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 29 Sep 2010 08:15:26 +1000
Subject: [Tutor] using "in" with a dictionary
In-Reply-To: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
References: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
Message-ID: <201009290815.26325.steve@pearwood.info>

On Wed, 29 Sep 2010 07:58:28 am Alex Hall wrote:
> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
>  (1,2):"a",
>  (3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]

Exactly like that:


>>> d = {(1,2): 'a', (3,4): 'b'}
>>> if (1,2) in d: print d[(1,2)]
...
a


> This is false, so I expect to have to use d.keys, but I am not quite
> sure how. I will be using this in a loop, and I have to know if there
> is a key in the dictionary called (i,j) and, if there is, I have to
> grab the value at that slot. If not I have to print something else.
> When I tried "in" in the interpreter, I got something about builtin
> function not being iterable. TIA for any suggestions.

Without knowing exactly what you wrote, and what error you got, I have 
no clue why you got that.



-- 
Steven D'Aprano

From sander.sweers at gmail.com  Wed Sep 29 00:22:02 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Wed, 29 Sep 2010 00:22:02 +0200
Subject: [Tutor] using "in" with a dictionary
In-Reply-To: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
References: <AANLkTinjL_wnqfxL-uJzUsiW_m3yLBvzGUy7Waqxo2HE@mail.gmail.com>
Message-ID: <AANLkTinBhSVnzoRbJdUeGRFKZ=R2A7AzegW9R30TfMPn@mail.gmail.com>

On 28 September 2010 23:58, Alex Hall <mehgcap at gmail.com> wrote:
> Hi all, yet again:
> I have a dictionary that will look something like:
> d={
> ?(1,2):"a",
> ?(3,4):"b"
> }
>
> How can I say:
> if (1,2) in d: print d[(1,2)]

This will work fine.

> This is false

Not it is not..
>>> d = {(1,2):"a",(3,4):"b"}
>>> (1,2) in d
True

>, so I expect to have to use d.keys, but I am not quite sure how.
> I will be using this in a loop, and I have to know if there is a key
> in the dictionary called (i,j) and, if there is, I have to grab the
> value at that slot. If not I have to print something else.

>>> d = {1:"a",2:"b"}
>>> for x in range(1,4):
	if x in d:
		print "Found %s in dict d and has value %s" % (x, d[x])
	else:
		print "Value %s is not in dict d" % x

		
Found 1 in dict d and has value a
Found 2 in dict d and has value b
Value 3 is not in dict d

> When I tried "in" in the interpreter, I got something about builtin function
> not being iterable. TIA for any suggestions.

What was the code you tried out? Please do provide this as it helps
figure out what was going on.

Greets
Sander

From therealdotcomboy at gmail.com  Wed Sep 29 01:22:21 2010
From: therealdotcomboy at gmail.com (Rodney Lewis)
Date: Tue, 28 Sep 2010 16:22:21 -0700
Subject: [Tutor] I am looking for a book on Beginners who never
 programmed before or have no experience in programming
In-Reply-To: <AANLkTikJxsvN+u4-g=n1N5hRa0rPM_YX7poPBGoeuEwu@mail.gmail.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com>
	<AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>
	<201009282147.42408.steve@pearwood.info>
	<AANLkTikJxsvN+u4-g=n1N5hRa0rPM_YX7poPBGoeuEwu@mail.gmail.com>
Message-ID: <AANLkTinoKAkuVhDvJ5Um56S5DeW6pNATzND3So61MpJ4@mail.gmail.com>

making games is the best way to learn programming, and the book is free

http://programming.gather.com/viewArticle.action?articleId=281474978440241
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/adf2e947/attachment.html>

From alan.gauld at btinternet.com  Wed Sep 29 02:15:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 29 Sep 2010 01:15:46 +0100
Subject: [Tutor] I am looking for a book on Beginners who
	neverprogrammed before or have no experience in programming
References: <333453.11381.qm@web53602.mail.re2.yahoo.com><AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com>
	<201009282147.42408.steve@pearwood.info>
Message-ID: <i7u0fo$ca3$1@dough.gmane.org>

"Steven D'Aprano" <steve at pearwood.info> wrote

> I've never heard of "Head First Programming" -- how are they
> unconventional?

They are a bit too "cutesy" for my liking, slow to get to any depth
but engaging for the sound-byte generation. Lots of cartoons and
jokes. I'd say its a bit like O'Reilly's take on the Dummies books.

I was briefly involved in reviewing an early HF Python book but it was 
so
badly done the project was scrapped while they found a new writing 
team.
They obviously have done this and I hope its now a good book because
I could see the merit in the style. But cute style still needs 
accurate
content! I will be looking out for it in my local bookshop, the 
editorial
team were very keen to see that the end product should be good.

Alan G.




From davea at ieee.org  Wed Sep 29 03:34:52 2010
From: davea at ieee.org (Dave Angel)
Date: Tue, 28 Sep 2010 21:34:52 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>	<201009281027.08146.steve@pearwood.info>	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
Message-ID: <4CA297BC.20602@ieee.org>

  On 9/28/2010 5:11 PM, Carter Danforth wrote:
> Thanks for the replies, Dave and Joel. The reason I'm not just using the
> time or datetime modules for a random date is because it's restricted to
> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
> about the leap years, Dave, as well the class instances; just updated it and
> it's all working now, and also included the rest of the code too w/ answer
> verification and time tracking.
>
> I want to start using this program to test myself for speed calculation
> using Zeller's formula, it's pretty cool for determining the days of dates -
> http://mathforum.org/dr/math/faq/faq.calendar.html
>
> Because of the way variables C and D are split up from the year in the
> formula, I split up the year for self.c and self.y.
>
> ------------------------
>
> import random, time, datetime, calendar
>
> class Date:
>      def __init__(self):
>          self.c = random.randint(16,30)
>          self.y = random.randint(0,99)
>          self.month = random.randint(1,12)
>          self.year = self.c*100 + self.y
>
>          apr = [4,6,9,11]
>          feb = [2]
>          notleap = [1700, 1800, 1900, 3000]
>
>          if self.month in feb:
>              if self.year%4 == 0:
>                  if self.year in notleap:
>                      self.k = random.randint(1,28)
>                  else:
>                      self.k = random.randint(1,29)
>              else:
>                  self.k = random.randint(1,28)
>          elif self.month in apr:
>              self.k = random.randint(1,30)
>          else:
>              self.k = random.randint(1,31)
>
>          if self.month in [1,2]:
>              d = self.y - 1
>              m = self.month + 10
>          else:
>              d = self.y
>              m = self.month - 2
>
>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>
>          if z<  0:
>              r = (abs(z)/7)*7 + z + 7
>          else:
>              r = z%7
>
>          dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4:
> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>          self.day = dict[r]
>
> t1m = time.localtime().tm_min
> t1s = time.localtime().tm_sec
> t1 = t1m + t1s/100.0
> n = 0
> x = 0
>
> while n<  10:
>      newdate = Date()
>
>      print '\n',calendar.month_name[newdate.month], newdate.k,',',
> newdate.year,'=',
>      answer = raw_input()
>      if answer.capitalize() == newdate.day:
>          pass
>      else:
>          x += 1
>      n += 1
>
> t2m = time.localtime().tm_min
> t2s = time.localtime().tm_sec
> t2 = t2m + t2s/100.0
> td = t2 - t1
>
> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal time:',td
>
>
> <snip>
>
(You top-posted your response, so your message is out of order)

I haven't tried to run your code, but there is at least one problem.

Your notleap list is very incomplete.

notleap = [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600, 2700, 2900, 3000]

I'm a little suspicious of your version of Zeller.  I wouldn't think 
that last term should have a 2* in it.

I'm not sure why you use a dictionary to calculate self.day.  A list 
would work just as well.

DaveA



From phuongpnh at gmail.com  Wed Sep 29 05:46:37 2010
From: phuongpnh at gmail.com (Pham Nguyen Huy Phuong)
Date: Tue, 28 Sep 2010 20:46:37 -0700
Subject: [Tutor] Problems install Python
Message-ID: <AANLkTi=9bCZUAn0NF1ANV8eKkPe+xkXGQ-DiTAUxPPC0@mail.gmail.com>

Dear all,
I had just download PeGreSQL, unzip and installed it, but I have a problem
such as:

phuongpnh at ubuntu:~/PyGreSQL-4.0$ python setup.py build
sh: pg_config: not found
Traceback (most recent call last):
  File "setup.py", line 94, in <module>
    pg_include_dir = pg_config('includedir')
  File "setup.py", line 56, in pg_config
    raise Exception("pg_config tool is not available.")
Exception: pg_config tool is not available.

I do not know this errors. Could you help me, please? I can not install it
right now.
Thanks you very much.
Best regards,
Phuong
-- 
FIT - HUFI
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100928/5cc393fe/attachment.html>

From evert.rol at gmail.com  Wed Sep 29 11:25:37 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 29 Sep 2010 11:25:37 +0200
Subject: [Tutor] Problems install Python
In-Reply-To: <AANLkTi=9bCZUAn0NF1ANV8eKkPe+xkXGQ-DiTAUxPPC0@mail.gmail.com>
References: <AANLkTi=9bCZUAn0NF1ANV8eKkPe+xkXGQ-DiTAUxPPC0@mail.gmail.com>
Message-ID: <5F72711E-E3AA-44B8-BABB-B48C59DE4374@gmail.com>

> I had just download PeGreSQL, unzip and installed it, but I have a problem such as:
> 
> phuongpnh at ubuntu:~/PyGreSQL-4.0$ python setup.py build
> sh: pg_config: not found
> Traceback (most recent call last):
>   File "setup.py", line 94, in <module>
>     pg_include_dir = pg_config('includedir')
>   File "setup.py", line 56, in pg_config
>     raise Exception("pg_config tool is not available.")
> Exception: pg_config tool is not available.
> 
> I do not know this errors. Could you help me, please? I can not install it right now.

Have you installed Postgresql? You probaby need the development package for that.
Pygresql depends on Postgresql, and if you install from source as here, you probably need the Postgresql development stuff.

But since you're on Ubuntu, can't you just install Pygresql through a package manager? That would take care of everything.


  Evert


From __peter__ at web.de  Wed Sep 29 11:42:29 2010
From: __peter__ at web.de (Peter Otten)
Date: Wed, 29 Sep 2010 11:42:29 +0200
Subject: [Tutor] generating independent random numbers
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
Message-ID: <i7v1lg$63b$1@dough.gmane.org>

Carter Danforth wrote:

> Thanks for the replies, Dave and Joel. The reason I'm not just using the
> time or datetime modules for a random date is because it's restricted to
> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer

The datetime module is not restricted to 1970...2038. It allows years 
1...9999 (it uses the Gregorian calendar even before its adoption). 

>>> import datetime
>>> datetime.MINYEAR, datetime.MAXYEAR
(1, 9999)
>>> datetime.date(1500, 2, 29)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
>>> datetime.date(1600, 2, 29)
datetime.date(1600, 2, 29)

The range allowed by the time module is probably implementation dependent. I 
can do things like

>>> time.gmtime(-11670998400)
time.struct_time(tm_year=1600, tm_mon=2, tm_mday=29, tm_hour=0, tm_min=0, 
tm_sec=0, tm_wday=1, tm_yday=60, tm_isdst=0)

>>> time.gmtime(2**55)
time.struct_time(tm_year=1141709097, tm_mon=6, tm_mday=13, tm_hour=6, 
tm_min=26, tm_sec=8, tm_wday=6, tm_yday=164, tm_isdst=0)

>>> time.gmtime(2**56)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: (75, 'Value too large for defined data type')

Peter


From ewald.ertl at gmail.com  Wed Sep 29 12:30:41 2010
From: ewald.ertl at gmail.com (Ewald Ertl)
Date: Wed, 29 Sep 2010 12:30:41 +0200
Subject: [Tutor] generating independent random numbers
In-Reply-To: <i7v1lg$63b$1@dough.gmane.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
	<i7v1lg$63b$1@dough.gmane.org>
Message-ID: <AANLkTinE1XWbwbC-0DkOKx6rtcCSdjh8_hL3iNBv0c-v@mail.gmail.com>

Hi,

On Wed, Sep 29, 2010 at 11:42 AM, Peter Otten <__peter__ at web.de> wrote:

> Carter Danforth wrote:
>
> > Thanks for the replies, Dave and Joel. The reason I'm not just using the
> > time or datetime modules for a random date is because it's restricted to
> > 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
>
> The datetime module is not restricted to 1970...2038. It allows years
> 1...9999 (it uses the Gregorian calendar even before its adoption).
>
> >>> import datetime
> >>> datetime.MINYEAR, datetime.MAXYEAR
> (1, 9999)
> >>> datetime.date(1500, 2, 29)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: day is out of range for month
> >>> datetime.date(1600, 2, 29)
> datetime.date(1600, 2, 29)
>
> Just an attempt from my side:
The year 1500 didn't have a 29th of February, the 28th work for me but 29th
also fails here.
>>> datetime.date( 1500, 2, 28 )
datetime.date(1500, 2, 28)
>>> datetime.date( 1500, 2, 29 )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month


HTH
Ewald
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/e07517da/attachment.html>

From __peter__ at web.de  Wed Sep 29 13:28:11 2010
From: __peter__ at web.de (Peter Otten)
Date: Wed, 29 Sep 2010 13:28:11 +0200
Subject: [Tutor] generating independent random numbers
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
	<i7v1lg$63b$1@dough.gmane.org>
	<AANLkTinE1XWbwbC-0DkOKx6rtcCSdjh8_hL3iNBv0c-v@mail.gmail.com>
Message-ID: <i7v7rl$1tf$1@dough.gmane.org>

Ewald Ertl wrote:

>> Just an attempt from my side:
> The year 1500 didn't have a 29th of February, the 28th work for me but
> 29th also fails here.
>>>> datetime.date( 1500, 2, 28 )
> datetime.date(1500, 2, 28)
>>>> datetime.date( 1500, 2, 29 )
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> ValueError: day is out of range for month

Yes, it's an expected "failure". I should have said that explicitly.

Peter 



From Calle_Python at live.se  Wed Sep 29 13:20:54 2010
From: Calle_Python at live.se (Calle's Pyt(h)onkonto)
Date: Wed, 29 Sep 2010 13:20:54 +0200
Subject: [Tutor] I am looking for a book on Beginners who never
	programmed before or have no experience in programming
In-Reply-To: <AANLkTinoKAkuVhDvJ5Um56S5DeW6pNATzND3So61MpJ4@mail.gmail.com>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com><AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com><201009282147.42408.steve@pearwood.info><AANLkTikJxsvN+u4-g=n1N5hRa0rPM_YX7poPBGoeuEwu@mail.gmail.com>
	<AANLkTinoKAkuVhDvJ5Um56S5DeW6pNATzND3So61MpJ4@mail.gmail.com>
Message-ID: <SNT104-DS8314F7D2C2040D8F1AC1AF8670@phx.gbl>

Or if you're like me (= Thinks reading a guide online is annoying since you have to switch between your browser and IDLE all the time), and would like to have a book that is easy to read and easy to understand, I would recommend Python Programming For The Absolute Beginner 3rd editon by Michael Dawson. I'm on the second chapter of the book, and have already learned alot about Python. Plus it's very good written.


Hope I helped a little.
//
Calle


From: Rodney Lewis 
Sent: Wednesday, September 29, 2010 1:22 AM
To: tutor at python.org 
Subject: Re: [Tutor] I am looking for a book on Beginners who never programmed before or have no experience in programming


making games is the best way to learn programming, and the book is free

http://programming.gather.com/viewArticle.action?articleId=281474978440241


--------------------------------------------------------------------------------


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/bf5f8d18/attachment.html>

From mail at timgolden.me.uk  Wed Sep 29 13:40:35 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 29 Sep 2010 12:40:35 +0100
Subject: [Tutor] I am looking for a book on Beginners who
 never	programmed before or have no experience in programming
In-Reply-To: <SNT104-DS8314F7D2C2040D8F1AC1AF8670@phx.gbl>
References: <333453.11381.qm@web53602.mail.re2.yahoo.com><AANLkTimxGUxuUWRfwtb4dopFQKGDvKPqC1Qg8SOQRScq@mail.gmail.com><201009282147.42408.steve@pearwood.info><AANLkTikJxsvN+u4-g=n1N5hRa0rPM_YX7poPBGoeuEwu@mail.gmail.com>	<AANLkTinoKAkuVhDvJ5Um56S5DeW6pNATzND3So61MpJ4@mail.gmail.com>
	<SNT104-DS8314F7D2C2040D8F1AC1AF8670@phx.gbl>
Message-ID: <4CA325B3.70601@timgolden.me.uk>

On 29/09/2010 12:20, Calle's Pyt(h)onkonto wrote:
> Or if you're like me (= Thinks reading a guide online is annoying
> since you have to switch between your browser and IDLE all the time),
> and would like to have a book that is easy to read and easy to
> understand,

Merely from that perspective alone, you might be interested in
something like http://trypython.org which gives you the main Python
tutorial side by side with a console in a browser window. It
uses Silverlight (it's put together by Michael Foord, long associated
with promoting IronPython) which may be a stumbling block for
technical or philosophical reasons, but it's quite a neat tool.

TJG

From susana.delgado_s at utzmg.edu.mx  Wed Sep 29 15:35:05 2010
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Wed, 29 Sep 2010 08:35:05 -0500
Subject: [Tutor] Writing a txt from dbf
Message-ID: <AANLkTi=fhqJQKL1Ogc8-Gm-xF9BWWaHuzfmGYNFhmiTq@mail.gmail.com>

Hello Steven!

Your guess was rigth, that's what I'm looking for!  I need an output as:
beta
gamma
etc...
but I'm showing betagammaetc..

What can I do to my code to get the first ouput? By the way thanks for
answering!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/4c89867d/attachment.html>

From alan.gauld at btinternet.com  Wed Sep 29 18:33:58 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 29 Sep 2010 17:33:58 +0100
Subject: [Tutor] Writing a txt from dbf
References: <AANLkTi=fhqJQKL1Ogc8-Gm-xF9BWWaHuzfmGYNFhmiTq@mail.gmail.com>
Message-ID: <i7vpps$r8c$1@dough.gmane.org>


"Susana Iraiis Delgado Rodriguez" <susana.delgado_s at utzmg.edu.mx> 
wrote

> Your guess was rigth, that's what I'm looking for!  I need an output 
> as:
> beta
> gamma
> etc...
> but I'm showing betagammaetc..

I assume you mean in the file? print adds a newline automatically when
printing to stdout.

Steven already showed you how to add a \n when writing the data to the 
file.
Have you tried that? Are you still having problems?

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



From carter.danforth at gmail.com  Wed Sep 29 18:45:01 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Wed, 29 Sep 2010 12:45:01 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <4CA297BC.20602@ieee.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
	<4CA297BC.20602@ieee.org>
Message-ID: <AANLkTinH-ztMGypNnCqw+MPyGRDN=+WphmAj9j9tRuGt@mail.gmail.com>

Wow... I'm really slipping here with the leaps years, good catch on the
2000s. And yeah, a list does make a whole lot more sense. Thanks Dave.

I've checked multiple sources on Zeller's formula, initially came across it
on this book on vedic math (highly recommend it): http://amzn.to/bNXBM6. But
here's the Wikipedia on it:
http://en.wikipedia.org/wiki/Zeller%27s_congruence

It's not *2 in the Julian calendar, but it is in Gregorian, which is what
we're also using for the leap yrs - http://en.wikipedia.org/wiki/Leap_year


On Tue, Sep 28, 2010 at 9:34 PM, Dave Angel <davea at ieee.org> wrote:

>  On 9/28/2010 5:11 PM, Carter Danforth wrote:
>
>> Thanks for the replies, Dave and Joel. The reason I'm not just using the
>> time or datetime modules for a random date is because it's restricted to
>> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
>> about the leap years, Dave, as well the class instances; just updated it
>> and
>> it's all working now, and also included the rest of the code too w/ answer
>> verification and time tracking.
>>
>> I want to start using this program to test myself for speed calculation
>> using Zeller's formula, it's pretty cool for determining the days of dates
>> -
>> http://mathforum.org/dr/math/faq/faq.calendar.html
>>
>> Because of the way variables C and D are split up from the year in the
>> formula, I split up the year for self.c and self.y.
>>
>> ------------------------
>>
>> import random, time, datetime, calendar
>>
>> class Date:
>>     def __init__(self):
>>         self.c = random.randint(16,30)
>>         self.y = random.randint(0,99)
>>         self.month = random.randint(1,12)
>>         self.year = self.c*100 + self.y
>>
>>         apr = [4,6,9,11]
>>         feb = [2]
>>         notleap = [1700, 1800, 1900, 3000]
>>
>>         if self.month in feb:
>>             if self.year%4 == 0:
>>                 if self.year in notleap:
>>                     self.k = random.randint(1,28)
>>                 else:
>>                     self.k = random.randint(1,29)
>>             else:
>>                 self.k = random.randint(1,28)
>>         elif self.month in apr:
>>             self.k = random.randint(1,30)
>>         else:
>>             self.k = random.randint(1,31)
>>
>>         if self.month in [1,2]:
>>             d = self.y - 1
>>             m = self.month + 10
>>         else:
>>             d = self.y
>>             m = self.month - 2
>>
>>         z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>>
>>         if z<  0:
>>             r = (abs(z)/7)*7 + z + 7
>>         else:
>>             r = z%7
>>
>>         dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday',
>> 4:
>> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>>         self.day = dict[r]
>>
>> t1m = time.localtime().tm_min
>> t1s = time.localtime().tm_sec
>> t1 = t1m + t1s/100.0
>> n = 0
>> x = 0
>>
>> while n<  10:
>>     newdate = Date()
>>
>>     print '\n',calendar.month_name[newdate.month], newdate.k,',',
>> newdate.year,'=',
>>     answer = raw_input()
>>     if answer.capitalize() == newdate.day:
>>         pass
>>     else:
>>         x += 1
>>     n += 1
>>
>> t2m = time.localtime().tm_min
>> t2s = time.localtime().tm_sec
>> t2 = t2m + t2s/100.0
>> td = t2 - t1
>>
>> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal
>> time:',td
>>
>>
>> <snip>
>>
>>  (You top-posted your response, so your message is out of order)
>
> I haven't tried to run your code, but there is at least one problem.
>
> Your notleap list is very incomplete.
>
> notleap = [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600, 2700, 2900,
> 3000]
>
> I'm a little suspicious of your version of Zeller.  I wouldn't think that
> last term should have a 2* in it.
>
> I'm not sure why you use a dictionary to calculate self.day.  A list would
> work just as well.
>
> DaveA
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/15f5d903/attachment-0001.html>

From susana.delgado_s at utzmg.edu.mx  Wed Sep 29 18:57:44 2010
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Wed, 29 Sep 2010 11:57:44 -0500
Subject: [Tutor] Writing txt from dbf
Message-ID: <AANLkTinEOkuT6MNLCwrsAb8X4U-wdVhtK4X8XiEdubc4@mail.gmail.com>

Thanks Steven and Alan, your recommendation worked perfectly!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/b12df981/attachment.html>

From davea at ieee.org  Wed Sep 29 19:53:28 2010
From: davea at ieee.org (Dave Angel)
Date: Wed, 29 Sep 2010 13:53:28 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>	<201009281027.08146.steve@pearwood.info>	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
Message-ID: <4CA37D18.7020300@ieee.org>

  On 9/28/2010 5:11 PM, Carter Danforth wrote:
> Thanks for the replies, Dave and Joel. The reason I'm not just using the
> time or datetime modules for a random date is because it's restricted to
> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
> about the leap years, Dave, as well the class instances; just updated it and
> it's all working now, and also included the rest of the code too w/ answer
> verification and time tracking.
>
> I want to start using this program to test myself for speed calculation
> using Zeller's formula, it's pretty cool for determining the days of dates -
> http://mathforum.org/dr/math/faq/faq.calendar.html
>
> Because of the way variables C and D are split up from the year in the
> formula, I split up the year for self.c and self.y.
>
> ------------------------
>
> import random, time, datetime, calendar
>
> class Date:
>      def __init__(self):
>          self.c = random.randint(16,30)
>          self.y = random.randint(0,99)
>          self.month = random.randint(1,12)
>          self.year = self.c*100 + self.y
>
>          apr = [4,6,9,11]
>          feb = [2]
>          notleap = [1700, 1800, 1900, 3000]
>
>          if self.month in feb:
>              if self.year%4 == 0:
>                  if self.year in notleap:
>                      self.k = random.randint(1,28)
>                  else:
>                      self.k = random.randint(1,29)
>              else:
>                  self.k = random.randint(1,28)
>          elif self.month in apr:
>              self.k = random.randint(1,30)
>          else:
>              self.k = random.randint(1,31)
>
>          if self.month in [1,2]:
>              d = self.y - 1
>              m = self.month + 10
>          else:
>              d = self.y
>              m = self.month - 2
>
>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>
>          if z<  0:
>              r = (abs(z)/7)*7 + z + 7
>          else:
>              r = z%7
>
>          dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4:
> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>          self.day = dict[r]
>
> t1m = time.localtime().tm_min
> t1s = time.localtime().tm_sec
> t1 = t1m + t1s/100.0
> n = 0
> x = 0
>
> while n<  10:
>      newdate = Date()
>
>      print '\n',calendar.month_name[newdate.month], newdate.k,',',
> newdate.year,'=',
>      answer = raw_input()
>      if answer.capitalize() == newdate.day:
>          pass
>      else:
>          x += 1
>      n += 1
>
> t2m = time.localtime().tm_min
> t2s = time.localtime().tm_sec
> t2 = t2m + t2s/100.0
> td = t2 - t1
>
> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal time:',td
>
> <snip>
>
You top-posted again.  Put your comments after the part you're quoting, 
not before.

You still have a problem in the code, and I still think it's in the 
2*self.c, though I don't have time to debug it.

Look up the day for  1/1/2099, and for 1/1/2100  and it comes out the 
same.  That's not correct.  No adjacent years start on the same day, 
it's always either one day or two.

You have too much in one function (method), which makes it hard to debug 
it.  Factor it into separate functions, and then test each 
independently.  And using k  for day and d for year make no sense to me, 
though perhaps it does in some other language.

DaveA




From roberto03 at gmail.com  Wed Sep 29 20:54:20 2010
From: roberto03 at gmail.com (roberto)
Date: Wed, 29 Sep 2010 20:54:20 +0200
Subject: [Tutor] function error
In-Reply-To: <38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
	<AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
	<38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
Message-ID: <AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>

On Tue, Sep 28, 2010 at 8:26 PM, Evert Rol <evert.rol at gmail.com> wrote:
>
> Perhaps if you provide the full traceback from the error (assuming you're still getting this >error); tracebacks generally show the offending code as well. It may be something that's >simply overlooked but shows in the traceback.
>
>

here it is:

TypeError                                 Traceback (most recent call last)

~/randomMove2.py in <module>()
----> 1
      2
      3
      4
      5

~/randomMove2.py in randomMove2(d1, d2, a1, a2)
      6          while 1:
      7                  turtle.left(random.uniform(a1,a2))
----> 8                  checkForward.checkForward(random.uniform(d1,d2))
      9                  if forward_failed == 'true':
     10                          turtle.right(180)

~/checkForward.py in checkForward(distance)
      8
      9         turtle.forward(distance)
---> 10         forward_failed = outOfBounds()
     11         turtle.setx(old_position[0]); turtle.sety(old_position[1])
     12         turtle._pen.down()

~/checkForward.py in out_of_bounds()
     19
     20 def outOfBounds():
---> 21         if (abs(turtle.position()[0]) >
turtle.window_height()/2) or (abs(turtle.position()[1]) >
turtle.window_width()/2):
     22                 return "true"
     23         else:

TypeError: 'function' object is unsubscriptable


thank you
--
roberto

From susana.delgado_s at utzmg.edu.mx  Wed Sep 29 21:49:53 2010
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Wed, 29 Sep 2010 14:49:53 -0500
Subject: [Tutor] Runnig a windows.exe from python
Message-ID: <AANLkTim==GuM3DCZ+=i3d=v5GRgeP0-X8bSE1RBNOJQc@mail.gmail.com>

Hello everyone:

I'm working in a simple python module to run a external command, this
command is named "ogr2ogr.exe" . When I execute my python script :

*import os
def call():
     os.system(' "C:\\Archivos de programa\\FWTools2.4.7\\bin\\ogr2ogr.exe"
')*
*     raw_input()*
*call()*
It runs, but if I want to enter arguments: *ogr2ogr*  to test my .exe, it
shows me an error *"ogr2ogr is not define", *any suggestion?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/e0bf255f/attachment.html>

From evert.rol at gmail.com  Wed Sep 29 21:53:14 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Wed, 29 Sep 2010 21:53:14 +0200
Subject: [Tutor] function error
In-Reply-To: <AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
	<AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
	<38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
	<AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>
Message-ID: <BC5C81BF-D76F-4C53-83CA-F6D38276169A@gmail.com>

>> Perhaps if you provide the full traceback from the error (assuming you're still getting this >error); tracebacks generally show the offending code as well. It may be something that's >simply overlooked but shows in the traceback.
>> 
>> 
> 
> here it is:
> 
> TypeError                                 Traceback (most recent call last)
> 
> ~/randomMove2.py in <module>()
> ----> 1
>      2
>      3
>      4
>      5
> 
> ~/randomMove2.py in randomMove2(d1, d2, a1, a2)
>      6          while 1:
>      7                  turtle.left(random.uniform(a1,a2))
> ----> 8                  checkForward.checkForward(random.uniform(d1,d2))
>      9                  if forward_failed == 'true':
>     10                          turtle.right(180)
> 
> ~/checkForward.py in checkForward(distance)
>      8
>      9         turtle.forward(distance)
> ---> 10         forward_failed = outOfBounds()
>     11         turtle.setx(old_position[0]); turtle.sety(old_position[1])
>     12         turtle._pen.down()
> 
> ~/checkForward.py in out_of_bounds()
>     19
>     20 def outOfBounds():
> ---> 21         if (abs(turtle.position()[0]) >
> turtle.window_height()/2) or (abs(turtle.position()[1]) >
> turtle.window_width()/2):
>     22                 return "true"
>     23         else:
> 
> TypeError: 'function' object is unsubscriptable


The only thing that strikes me as a bit odd, is that the last bit if given as '~/checkForward.py in out_of_bounds()', while the actual function seems to be called outOfBounds(). I don't know this traceback (ie, I can't tell what Python environment/editor you're using), but that could suggest the byte-compiled code you are running doesn't match with the actual current code. 
So you may have changed the function name in the meantime, *as well as* fixed a parenthesis in the process. But perhaps you haven't then recompiled your current code, and for some reason your Python executable hasn't picked up the most recent source code and recompiled that for you. 
If this is the case, it may be dependent on your development environment that does this (somewhat incorrectly, assuming you have at least saved the source file), but as I mentioned, I have no idea what you're using.

Then again, this is still a guess. But it's the only thing I can see that stands out.

Cheers,

  Evert


From steve at pearwood.info  Wed Sep 29 22:37:00 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 30 Sep 2010 06:37:00 +1000
Subject: [Tutor] Runnig a windows.exe from python
In-Reply-To: <AANLkTim==GuM3DCZ+=i3d=v5GRgeP0-X8bSE1RBNOJQc@mail.gmail.com>
References: <AANLkTim==GuM3DCZ+=i3d=v5GRgeP0-X8bSE1RBNOJQc@mail.gmail.com>
Message-ID: <201009300637.01014.steve@pearwood.info>

On Thu, 30 Sep 2010 05:49:53 am Susana Iraiis Delgado Rodriguez wrote:
> Hello everyone:
>
> I'm working in a simple python module to run a external command, this
> command is named "ogr2ogr.exe" . When I execute my python script :
>
> *import os
> def call():
>      os.system(' "C:\\Archivos de
> programa\\FWTools2.4.7\\bin\\ogr2ogr.exe" ')*
> *     raw_input()*
> *call()*
> It runs, but if I want to enter arguments: *ogr2ogr*  to test my
> .exe, it shows me an error *"ogr2ogr is not define", *any suggestion?

Please don't add extra "bits" around the code you use -- there's no need 
to add asterisks * around the code. Just copy and paste it it into the 
email.

Can you please copy and paste the exact error message you get? Include 
the full traceback, not just the last line.

Also, it is a little-known thing that Windows accepts forward slashes as 
well as back-slashes in pathnames. So it is easier to write:

"C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe" 

than:

"C:\\Archivos de programa\\FWTools2.4.7\\bin\\ogr2ogr.exe" 



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Wed Sep 29 23:13:42 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 29 Sep 2010 22:13:42 +0100
Subject: [Tutor] function error
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com><i7sesd$7rc$1@dough.gmane.org><AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com><AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com><38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
	<AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>
Message-ID: <i80a6c$amv$1@dough.gmane.org>

"roberto" <roberto03 at gmail.com> wrote

>> Perhaps if you provide the full traceback from the error

> here it is:
>
> TypeError                                 Traceback (most recent 
> call last)
>
> ~/randomMove2.py in <module>()
> ----> 1
>      2
>      3
>      4
>      5
...
> ~/checkForward.py in out_of_bounds()
>     19
>     20 def outOfBounds():
> ---> 21         if (abs(turtle.position()[0]) >
> turtle.window_height()/2) or (abs(turtle.position()[1]) >
> turtle.window_width()/2):
>     22                 return "true"
>     23         else:
>
> TypeError: 'function' object is unsubscriptable

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?

HTH

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



From alan.gauld at btinternet.com  Wed Sep 29 23:18:16 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 29 Sep 2010 22:18:16 +0100
Subject: [Tutor] Runnig a windows.exe from python
References: <AANLkTim==GuM3DCZ+=i3d=v5GRgeP0-X8bSE1RBNOJQc@mail.gmail.com>
Message-ID: <i80aev$buv$1@dough.gmane.org>

"Susana Iraiis Delgado Rodriguez" <susana.delgado_s at utzmg.edu.mx> 
wrote

> I'm working in a simple python module to run a external command, 
> this
> command is named "ogr2ogr.exe" . When I execute my python script :
>
> *import os
> def call():
>     os.system(' "C:\\Archivos de 
> programa\\FWTools2.4.7\\bin\\ogr2ogr.exe"
> ')*
> *     raw_input()*
> *call()*
> It runs, but if I want to enter arguments: *ogr2ogr*  to test my 
> .exe, it
> shows me an error *"ogr2ogr is not define", *any suggestion?

You need to read the arfguments before calling the exe. Then create 
the full
command string and pass that tro os.system.

However os.system is a blunt instrument, you will find you have much 
more
control using the subprocess module which supercedes os.system and
various others ways of executing external programs. It take a wee bit
more effort but the extra control is worth it.

The documentation  has numerous examples and the "Using the OS"
topic of my tutorial has some info too.

HTH

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



From carter.danforth at gmail.com  Thu Sep 30 03:17:36 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Wed, 29 Sep 2010 21:17:36 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <4CA37D18.7020300@ieee.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<201009281027.08146.steve@pearwood.info>
	<4CA15135.3050506@ieee.org>
	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>
	<4CA37D18.7020300@ieee.org>
Message-ID: <AANLkTinm+mfbTTYHo7saWUn-aRpHX=9gWj-wxnsvj9Np@mail.gmail.com>

On Wed, Sep 29, 2010 at 1:53 PM, Dave Angel <davea at ieee.org> wrote:

>  On 9/28/2010 5:11 PM, Carter Danforth wrote:
>
>> Thanks for the replies, Dave and Joel. The reason I'm not just using the
>> time or datetime modules for a random date is because it's restricted to
>> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
>> about the leap years, Dave, as well the class instances; just updated it
>> and
>> it's all working now, and also included the rest of the code too w/ answer
>> verification and time tracking.
>>
>> I want to start using this program to test myself for speed calculation
>> using Zeller's formula, it's pretty cool for determining the days of dates
>> -
>> http://mathforum.org/dr/math/faq/faq.calendar.html
>>
>> Because of the way variables C and D are split up from the year in the
>> formula, I split up the year for self.c and self.y.
>>
>> ------------------------
>>
>> import random, time, datetime, calendar
>>
>> class Date:
>>     def __init__(self):
>>         self.c = random.randint(16,30)
>>         self.y = random.randint(0,99)
>>         self.month = random.randint(1,12)
>>         self.year = self.c*100 + self.y
>>
>>         apr = [4,6,9,11]
>>         feb = [2]
>>         notleap = [1700, 1800, 1900, 3000]
>>
>>         if self.month in feb:
>>             if self.year%4 == 0:
>>                 if self.year in notleap:
>>                     self.k = random.randint(1,28)
>>                 else:
>>                     self.k = random.randint(1,29)
>>             else:
>>                 self.k = random.randint(1,28)
>>         elif self.month in apr:
>>             self.k = random.randint(1,30)
>>         else:
>>             self.k = random.randint(1,31)
>>
>>         if self.month in [1,2]:
>>             d = self.y - 1
>>             m = self.month + 10
>>         else:
>>             d = self.y
>>             m = self.month - 2
>>
>>         z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>>
>>         if z<  0:
>>             r = (abs(z)/7)*7 + z + 7
>>         else:
>>             r = z%7
>>
>>         dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday',
>> 4:
>> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>>         self.day = dict[r]
>>
>> t1m = time.localtime().tm_min
>> t1s = time.localtime().tm_sec
>> t1 = t1m + t1s/100.0
>> n = 0
>> x = 0
>>
>> while n<  10:
>>     newdate = Date()
>>
>>     print '\n',calendar.month_name[newdate.month], newdate.k,',',
>> newdate.year,'=',
>>     answer = raw_input()
>>     if answer.capitalize() == newdate.day:
>>         pass
>>     else:
>>         x += 1
>>     n += 1
>>
>> t2m = time.localtime().tm_min
>> t2s = time.localtime().tm_sec
>> t2 = t2m + t2s/100.0
>> td = t2 - t1
>>
>> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal
>> time:',td
>>
>> <snip>
>>
>>  You top-posted again.  Put your comments after the part you're quoting,
> not before.
>
> You still have a problem in the code, and I still think it's in the
> 2*self.c, though I don't have time to debug it.
>
> Look up the day for  1/1/2099, and for 1/1/2100  and it comes out the same.
>  That's not correct.  No adjacent years start on the same day, it's always
> either one day or two.
>
> You have too much in one function (method), which makes it hard to debug
> it.  Factor it into separate functions, and then test each independently.
>  And using k  for day and d for year make no sense to me, though perhaps it
> does in some other language.
>
> DaveA
>
>
Hey Dave, you probably left c and y alone when comparing the years. If the
date's 1/1/2099, then self.c = 20 and self.y=99. If you try doing it again
while changing those values, for 1/1/2099, the day comes out to be Thursday,
and for 1/1/2100 you'll get Wednesday.

Glad you pointed out the 2100 date though, there actually was a problem in
it, but it's not the 2*self.c; I had to account for d = y - 1 when y = 00
(zeller subtracts months by 2, so it needs to be the previous yr for
jan/feb).

Below is the updated code, I put in a few comments to make it read easier.

----------------------

import random, time, datetime, calendar

class Date:
    def __init__(self):
        self.c = random.randint(16,30) # first two digits in a year
        self.y = random.randint(0,99)  # last two digits in a year
        self.month = random.randint(1,12)
        self.year = self.c*100 + self.y

        apr = [4,6,9,11]
        feb = [2]
        notleap = [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600, 2700,
2900, 3000]

        if self.month in feb:          # assigns days, given the month
            if self.year%4 == 0:
                if self.year in notleap:
                    self.k = random.randint(1,28)
                else:
                    self.k = random.randint(1,29)
            else:
                self.k = random.randint(1,28)
        elif self.month in apr:
            self.k = random.randint(1,30)
        else:
            self.k = random.randint(1,31)

        if self.month in [1,2]:        # months in zeller's rule are
subtracted by 2
            if self.y == 0:            # need to acct for jan/feb year
change
                d = 99
                m = self.month + 10
            else:
                d = self.y - 1
                m = self.month + 10
        else:
            d = self.y
            m = self.month - 2

        z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c  # -->
Zeller's formula

        if z < 0:                      # the remainder of z/7 determines the
day of the week
            r = (abs(z)/7)*7 + z + 7   # need to account for negative z
values by adding 7 to remainder
        else:
            r = z%7

        week =
('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
        self.day = week[r]

t1m = time.localtime().tm_min
t1s = time.localtime().tm_sec
t1 = t1m + t1s/100.0
n = 0
x = 0

while n < 10:
    newdate = Date()
    print '\n  ',calendar.month_name[newdate.month], str(newdate.k) +
',',newdate.year,'=',
    answer = raw_input()
    if answer.capitalize() == newdate.day:
        pass
    else:
        x += 1
    n += 1

t2m = time.localtime().tm_min
t2s = time.localtime().tm_sec
t2 = t2m + t2s/100.0
td = t2 - t1

print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal time:',td
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/fc9d331f/attachment.html>

From davea at ieee.org  Thu Sep 30 06:03:57 2010
From: davea at ieee.org (Dave Angel)
Date: Thu, 30 Sep 2010 00:03:57 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <AANLkTinm+mfbTTYHo7saWUn-aRpHX=9gWj-wxnsvj9Np@mail.gmail.com>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>	<201009281027.08146.steve@pearwood.info>	<4CA15135.3050506@ieee.org>	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>	<4CA37D18.7020300@ieee.org>
	<AANLkTinm+mfbTTYHo7saWUn-aRpHX=9gWj-wxnsvj9Np@mail.gmail.com>
Message-ID: <4CA40C2D.6000809@ieee.org>

  On 9/29/2010 9:17 PM, Carter Danforth wrote:
> On Wed, Sep 29, 2010 at 1:53 PM, Dave Angel<davea at ieee.org>  wrote:
>
>>   On 9/28/2010 5:11 PM, Carter Danforth wrote:
>>
>>> Thanks for the replies, Dave and Joel. The reason I'm not just using the
>>> time or datetime modules for a random date is because it's restricted to
>>> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer
>>> about the leap years, Dave, as well the class instances; just updated it
>>> and
>>> it's all working now, and also included the rest of the code too w/ answer
>>> verification and time tracking.
>>>
>>> I want to start using this program to test myself for speed calculation
>>> using Zeller's formula, it's pretty cool for determining the days of dates
>>> -
>>> http://mathforum.org/dr/math/faq/faq.calendar.html
>>>
>>> Because of the way variables C and D are split up from the year in the
>>> formula, I split up the year for self.c and self.y.
>>>
>>> ------------------------
>>>
>>> import random, time, datetime, calendar
>>>
>>> class Date:
>>>      def __init__(self):
>>>          self.c = random.randint(16,30)
>>>          self.y = random.randint(0,99)
>>>          self.month = random.randint(1,12)
>>>          self.year = self.c*100 + self.y
>>>
>>>          apr = [4,6,9,11]
>>>          feb = [2]
>>>          notleap = [1700, 1800, 1900, 3000]
>>>
>>>          if self.month in feb:
>>>              if self.year%4 == 0:
>>>                  if self.year in notleap:
>>>                      self.k = random.randint(1,28)
>>>                  else:
>>>                      self.k = random.randint(1,29)
>>>              else:
>>>                  self.k = random.randint(1,28)
>>>          elif self.month in apr:
>>>              self.k = random.randint(1,30)
>>>          else:
>>>              self.k = random.randint(1,31)
>>>
>>>          if self.month in [1,2]:
>>>              d = self.y - 1
>>>              m = self.month + 10
>>>          else:
>>>              d = self.y
>>>              m = self.month - 2
>>>
>>>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>>>
>>>          if z<   0:
>>>              r = (abs(z)/7)*7 + z + 7
>>>          else:
>>>              r = z%7
>>>
>>>          dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday',
>>> 4:
>>> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>>>          self.day = dict[r]
>>>
>>> t1m = time.localtime().tm_min
>>> t1s = time.localtime().tm_sec
>>> t1 = t1m + t1s/100.0
>>> n = 0
>>> x = 0
>>>
>>> while n<   10:
>>>      newdate = Date()
>>>
>>>      print '\n',calendar.month_name[newdate.month], newdate.k,',',
>>> newdate.year,'=',
>>>      answer = raw_input()
>>>      if answer.capitalize() == newdate.day:
>>>          pass
>>>      else:
>>>          x += 1
>>>      n += 1
>>>
>>> t2m = time.localtime().tm_min
>>> t2s = time.localtime().tm_sec
>>> t2 = t2m + t2s/100.0
>>> td = t2 - t1
>>>
>>> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal
>>> time:',td
>>>
>>> <snip>
>>>
>>>   You top-posted again.  Put your comments after the part you're quoting,
>> not before.
>>
>> You still have a problem in the code, and I still think it's in the
>> 2*self.c, though I don't have time to debug it.
>>
>> Look up the day for  1/1/2099, and for 1/1/2100  and it comes out the same.
>>   That's not correct.  No adjacent years start on the same day, it's always
>> either one day or two.
>>
>> You have too much in one function (method), which makes it hard to debug
>> it.  Factor it into separate functions, and then test each independently.
>>   And using k  for day and d for year make no sense to me, though perhaps it
>> does in some other language.
>>
>> DaveA
>>
>>
> Hey Dave, you probably left c and y alone when comparing the years. If the
> date's 1/1/2099, then self.c = 20 and self.y=99. If you try doing it again
> while changing those values, for 1/1/2099, the day comes out to be Thursday,
> and for 1/1/2100 you'll get Wednesday.
>
> Glad you pointed out the 2100 date though, there actually was a problem in
> it, but it's not the 2*self.c; I had to account for d = y - 1 when y = 00
> (zeller subtracts months by 2, so it needs to be the previous yr for
> jan/feb).
>
> Below is the updated code, I put in a few comments to make it read easier.
>
> ----------------------
>
> import random, time, datetime, calendar
>
> class Date:
>      def __init__(self):
>          self.c = random.randint(16,30) # first two digits in a year
>          self.y = random.randint(0,99)  # last two digits in a year
>          self.month = random.randint(1,12)
>          self.year = self.c*100 + self.y
>
>          apr = [4,6,9,11]
>          feb = [2]
>          notleap = [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600, 2700,
> 2900, 3000]
>
>          if self.month in feb:          # assigns days, given the month
>              if self.year%4 == 0:
>                  if self.year in notleap:
>                      self.k = random.randint(1,28)
>                  else:
>                      self.k = random.randint(1,29)
>              else:
>                  self.k = random.randint(1,28)
>          elif self.month in apr:
>              self.k = random.randint(1,30)
>          else:
>              self.k = random.randint(1,31)
>
>          if self.month in [1,2]:        # months in zeller's rule are
> subtracted by 2
>              if self.y == 0:            # need to acct for jan/feb year
> change
>                  d = 99
>                  m = self.month + 10
>              else:
>                  d = self.y - 1
>                  m = self.month + 10
>          else:
>              d = self.y
>              m = self.month - 2
>
>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c  # -->
> Zeller's formula
>
>          if z<  0:                      # the remainder of z/7 determines the
> day of the week
>              r = (abs(z)/7)*7 + z + 7   # need to account for negative z
> values by adding 7 to remainder
>          else:
>              r = z%7
>
>          week =
> ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
>          self.day = week[r]
>
> t1m = time.localtime().tm_min
> t1s = time.localtime().tm_sec
> t1 = t1m + t1s/100.0
> n = 0
> x = 0
>
> while n<  10:
>      newdate = Date()
>      print '\n  ',calendar.month_name[newdate.month], str(newdate.k) +
> ',',newdate.year,'=',
>      answer = raw_input()
>      if answer.capitalize() == newdate.day:
>          pass
>      else:
>          x += 1
>      n += 1
>
> t2m = time.localtime().tm_min
> t2s = time.localtime().tm_sec
> t2 = t2m + t2s/100.0
> td = t2 - t1
>
> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal time:',td
>
In order to check it out, I refactored the zeller portion into a 
separate function.  Since there was no reason to make it a class member, 
I had to do a lot of editing.  And since I couldn't understand the 
one-letter symbols, I changed them as well.

Your code is much more verbose than needed.  If you just used 4 digit 
years, that last bug wouldn't have happened.

I think you have another bug, the logic for z<0 is incorrect, but also 
unnecessary.  For some negative values, it'll produce a 7, which would 
give you a subscript error in your week[r] expression.  But Python does 
the right thing with remainders of negative values, so all you need is 
the %7.

Consider using 306/10 for the month, and 1461/4 for the year, and then 
-year/100, and + year/400.  Then you get actual number of days, Make 
that a function, and when you call it here, you use modulo 7 for day of 
week.  But you can then test it independently.

How about:

def getDay2(year, month, day):
     if month < 3:
         year -= 1
         month += 12
     z = day + (month-4)*306/10 + year*1461/4 - year/100 + year/400
     return z- 275

Or of course:

def getDay3(year, month, day):
     mydate = datetime.date(year, month, day)
     return mydate.toordinal()

which gives identical results for all dates in that range.

And of course if you write one more function:

def getDate(days):
     mydate = datetime.date.fromordinal(days)
     return mydate.year, mydate.month, mydate.day

then you can make your random date much simpler as well:

year, month, day = getDate(random.randint(584023, 1095727))

assuming you want to fix the other bug:  date range from 1600 through 
3000.  Your present code goes to 3099.

The body of your method then looks something like (untested)

     self.year, self.month, self.day = getDate(random.randint(584023, 
1095727))
     r = getDay2(self.year, self.month, self.day)

   week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
   self.dayname = week[r]

Incidentally, there's another problem in your code -- when comparing the day string, you uppercase one of them, but not the other.



DaveA


From jjhartley at gmail.com  Thu Sep 30 06:29:59 2010
From: jjhartley at gmail.com (James Hartley)
Date: Wed, 29 Sep 2010 21:29:59 -0700
Subject: [Tutor] system()? popen2()? How to execute a command & save its
	output?
Message-ID: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>

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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100929/023352ee/attachment.html>

From davea at ieee.org  Thu Sep 30 06:38:31 2010
From: davea at ieee.org (Dave Angel)
Date: Thu, 30 Sep 2010 00:38:31 -0400
Subject: [Tutor] generating independent random numbers
In-Reply-To: <4CA40C2D.6000809@ieee.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>	<201009281027.08146.steve@pearwood.info>	<4CA15135.3050506@ieee.org>	<AANLkTimS=d8GVm5tOM_4JRqdeX=G03MuQr+9igqdXfzJ@mail.gmail.com>	<4CA37D18.7020300@ieee.org>	<AANLkTinm+mfbTTYHo7saWUn-aRpHX=9gWj-wxnsvj9Np@mail.gmail.com>
	<4CA40C2D.6000809@ieee.org>
Message-ID: <4CA41447.9010107@ieee.org>



On 2:59 PM, Dave Angel wrote:
>  On 9/29/2010 9:17 PM, Carter Danforth wrote:
>> On Wed, Sep 29, 2010 at 1:53 PM, Dave Angel<davea at ieee.org>  wrote:
>>
>>>   On 9/28/2010 5:11 PM, Carter Danforth wrote:
>>>
>>>> Thanks for the replies, Dave and Joel. The reason I'm not just 
>>>> using the
>>>> time or datetime modules for a random date is because it's 
>>>> restricted to
>>>> 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the 
>>>> pointer
>>>> about the leap years, Dave, as well the class instances; just 
>>>> updated it
>>>> and
>>>> it's all working now, and also included the rest of the code too w/ 
>>>> answer
>>>> verification and time tracking.
>>>>
>>>> I want to start using this program to test myself for speed 
>>>> calculation
>>>> using Zeller's formula, it's pretty cool for determining the days 
>>>> of dates
>>>> -
>>>> http://mathforum.org/dr/math/faq/faq.calendar.html
>>>>
>>>> Because of the way variables C and D are split up from the year in the
>>>> formula, I split up the year for self.c and self.y.
>>>>
>>>> ------------------------
>>>>
>>>> import random, time, datetime, calendar
>>>>
>>>> class Date:
>>>>      def __init__(self):
>>>>          self.c = random.randint(16,30)
>>>>          self.y = random.randint(0,99)
>>>>          self.month = random.randint(1,12)
>>>>          self.year = self.c*100 + self.y
>>>>
>>>>          apr = [4,6,9,11]
>>>>          feb = [2]
>>>>          notleap = [1700, 1800, 1900, 3000]
>>>>
>>>>          if self.month in feb:
>>>>              if self.year%4 == 0:
>>>>                  if self.year in notleap:
>>>>                      self.k = random.randint(1,28)
>>>>                  else:
>>>>                      self.k = random.randint(1,29)
>>>>              else:
>>>>                  self.k = random.randint(1,28)
>>>>          elif self.month in apr:
>>>>              self.k = random.randint(1,30)
>>>>          else:
>>>>              self.k = random.randint(1,31)
>>>>
>>>>          if self.month in [1,2]:
>>>>              d = self.y - 1
>>>>              m = self.month + 10
>>>>          else:
>>>>              d = self.y
>>>>              m = self.month - 2
>>>>
>>>>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c
>>>>
>>>>          if z<   0:
>>>>              r = (abs(z)/7)*7 + z + 7
>>>>          else:
>>>>              r = z%7
>>>>
>>>>          dict = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 
>>>> 'Wednesday',
>>>> 4:
>>>> 'Thursday', 5: 'Friday', 6: 'Saturday' }
>>>>          self.day = dict[r]
>>>>
>>>> t1m = time.localtime().tm_min
>>>> t1s = time.localtime().tm_sec
>>>> t1 = t1m + t1s/100.0
>>>> n = 0
>>>> x = 0
>>>>
>>>> while n<   10:
>>>>      newdate = Date()
>>>>
>>>>      print '\n',calendar.month_name[newdate.month], newdate.k,',',
>>>> newdate.year,'=',
>>>>      answer = raw_input()
>>>>      if answer.capitalize() == newdate.day:
>>>>          pass
>>>>      else:
>>>>          x += 1
>>>>      n += 1
>>>>
>>>> t2m = time.localtime().tm_min
>>>> t2s = time.localtime().tm_sec
>>>> t2 = t2m + t2s/100.0
>>>> td = t2 - t1
>>>>
>>>> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal
>>>> time:',td
>>>>
>>>> <snip>
>>>>
>>>>   You top-posted again.  Put your comments after the part you're 
>>>> quoting,
>>> not before.
>>>
>>> You still have a problem in the code, and I still think it's in the
>>> 2*self.c, though I don't have time to debug it.
>>>
>>> Look up the day for  1/1/2099, and for 1/1/2100  and it comes out 
>>> the same.
>>>   That's not correct.  No adjacent years start on the same day, it's 
>>> always
>>> either one day or two.
>>>
>>> You have too much in one function (method), which makes it hard to 
>>> debug
>>> it.  Factor it into separate functions, and then test each 
>>> independently.
>>>   And using k  for day and d for year make no sense to me, though 
>>> perhaps it
>>> does in some other language.
>>>
>>> DaveA
>>>
>>>
>> Hey Dave, you probably left c and y alone when comparing the years. 
>> If the
>> date's 1/1/2099, then self.c = 20 and self.y=99. If you try doing it 
>> again
>> while changing those values, for 1/1/2099, the day comes out to be 
>> Thursday,
>> and for 1/1/2100 you'll get Wednesday.
>>
>> Glad you pointed out the 2100 date though, there actually was a 
>> problem in
>> it, but it's not the 2*self.c; I had to account for d = y - 1 when y 
>> = 00
>> (zeller subtracts months by 2, so it needs to be the previous yr for
>> jan/feb).
>>
>> Below is the updated code, I put in a few comments to make it read 
>> easier.
>>
>> ----------------------
>>
>> import random, time, datetime, calendar
>>
>> class Date:
>>      def __init__(self):
>>          self.c = random.randint(16,30) # first two digits in a year
>>          self.y = random.randint(0,99)  # last two digits in a year
>>          self.month = random.randint(1,12)
>>          self.year = self.c*100 + self.y
>>
>>          apr = [4,6,9,11]
>>          feb = [2]
>>          notleap = [1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600, 
>> 2700,
>> 2900, 3000]
>>
>>          if self.month in feb:          # assigns days, given the month
>>              if self.year%4 == 0:
>>                  if self.year in notleap:
>>                      self.k = random.randint(1,28)
>>                  else:
>>                      self.k = random.randint(1,29)
>>              else:
>>                  self.k = random.randint(1,28)
>>          elif self.month in apr:
>>              self.k = random.randint(1,30)
>>          else:
>>              self.k = random.randint(1,31)
>>
>>          if self.month in [1,2]:        # months in zeller's rule are
>> subtracted by 2
>>              if self.y == 0:            # need to acct for jan/feb year
>> change
>>                  d = 99
>>                  m = self.month + 10
>>              else:
>>                  d = self.y - 1
>>                  m = self.month + 10
>>          else:
>>              d = self.y
>>              m = self.month - 2
>>
>>          z = self.k + (13*m-1)/5 + d + d/4 + self.c/4 - 2*self.c  # -->
>> Zeller's formula
>>
>>          if z<  0:                      # the remainder of z/7 
>> determines the
>> day of the week
>>              r = (abs(z)/7)*7 + z + 7   # need to account for negative z
>> values by adding 7 to remainder
>>          else:
>>              r = z%7
>>
>>          week =
>> ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
>>          self.day = week[r]
>>
>> t1m = time.localtime().tm_min
>> t1s = time.localtime().tm_sec
>> t1 = t1m + t1s/100.0
>> n = 0
>> x = 0
>>
>> while n<  10:
>>      newdate = Date()
>>      print '\n  ',calendar.month_name[newdate.month], str(newdate.k) +
>> ',',newdate.year,'=',
>>      answer = raw_input()
>>      if answer.capitalize() == newdate.day:
>>          pass
>>      else:
>>          x += 1
>>      n += 1
>>
>> t2m = time.localtime().tm_min
>> t2s = time.localtime().tm_sec
>> t2 = t2m + t2s/100.0
>> td = t2 - t1
>>
>> print '\n',x,'out of 10 wrong\nAvg time/question:',td/10,'\nTotal 
>> time:',td
>>
> In order to check it out, I refactored the zeller portion into a 
> separate function.  Since there was no reason to make it a class 
> member, I had to do a lot of editing.  And since I couldn't understand 
> the one-letter symbols, I changed them as well.
>
> Your code is much more verbose than needed.  If you just used 4 digit 
> years, that last bug wouldn't have happened.
>
> I think you have another bug, the logic for z<0 is incorrect, but also 
> unnecessary.  For some negative values, it'll produce a 7, which would 
> give you a subscript error in your week[r] expression.  But Python 
> does the right thing with remainders of negative values, so all you 
> need is the %7.
>
> Consider using 306/10 for the month, and 1461/4 for the year, and then 
> -year/100, and + year/400.  Then you get actual number of days, Make 
> that a function, and when you call it here, you use modulo 7 for day 
> of week.  But you can then test it independently.
>
> How about:
>
> def getDay2(year, month, day):
>     if month < 3:
>         year -= 1
>         month += 12
>     z = day + (month-4)*306/10 + year*1461/4 - year/100 + year/400
>     return z- 275
>
> Or of course:
>
> def getDay3(year, month, day):
>     mydate = datetime.date(year, month, day)
>     return mydate.toordinal()
>
> which gives identical results for all dates in that range.
>
> And of course if you write one more function:
>
> def getDate(days):
>     mydate = datetime.date.fromordinal(days)
>     return mydate.year, mydate.month, mydate.day
>
> then you can make your random date much simpler as well:
>
> year, month, day = getDate(random.randint(584023, 1095727))
>
> assuming you want to fix the other bug:  date range from 1600 through 
> 3000.  Your present code goes to 3099.
>
> The body of your method then looks something like (untested)
>
>     self.year, self.month, self.day = getDate(random.randint(584023, 
> 1095727))
>     r = getDay2(self.year, self.month, self.day)
>
>   week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
> "Friday", "Saturday"]
>   self.dayname = week[r]
>
> Incidentally, there's another problem in your code -- when comparing 
> the day string, you uppercase one of them, but not the other.
>
>
>
> DaveA
>
>
Sorry, I mentioned %7, but forgot to include it in my last sample.  It's 
still untested, but closer.

self.year, self.month, self.day = getDate(random.randint(584023, 1095727))
r = getDay2(self.year, self.month, self.day)
week = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
"Friday", "Saturday"]
self.dayname = week[r%7]

DaveA


From vnbang2003 at yahoo.com  Thu Sep 30 06:44:46 2010
From: vnbang2003 at yahoo.com (vijay)
Date: Thu, 30 Sep 2010 10:14:46 +0530 (IST)
Subject: [Tutor] system()? popen2()? How to execute a command & save its
	output?
In-Reply-To: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
Message-ID: <55136.73252.qm@web95305.mail.in2.yahoo.com>

command_name = 'ps -ax|grep ?sometext >>/tmp/output.txt'f = os.popen('%s' %command_name)
            fp = open('/tmp/output.txt')
print fp.readlines()

With Regards
Vijay


--- On Thu, 30/9/10, James Hartley <jjhartley at gmail.com> wrote:

From: James Hartley <jjhartley at gmail.com>
Subject: [Tutor] system()? popen2()? How to execute a command & save its output?
To: tutor at python.org
Date: Thursday, 30 September, 2010, 9:59 AM

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


-----Inline Attachment Follows-----

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/4f2d1140/attachment.html>

From cfuller084 at thinkingplanet.net  Thu Sep 30 07:00:34 2010
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Thu, 30 Sep 2010 00:00:34 -0500
Subject: [Tutor] system()? popen2()? How to execute a command & save its
	output?
In-Reply-To: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
References: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
Message-ID: <201009300000.35219.cfuller084@thinkingplanet.net>


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


From roberto03 at gmail.com  Thu Sep 30 11:02:51 2010
From: roberto03 at gmail.com (roberto)
Date: Thu, 30 Sep 2010 11:02:51 +0200
Subject: [Tutor] function error
In-Reply-To: <i80a6c$amv$1@dough.gmane.org>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
	<AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
	<38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
	<AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>
	<i80a6c$amv$1@dough.gmane.org>
Message-ID: <AANLkTinCLd93ST=OWoHVoMRNTMdVVuFf=EAVnDsHYBGU@mail.gmail.com>

On Wed, Sep 29, 2010 at 11:13 PM, Alan Gauld <alan.gauld at 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

From alan.gauld at btinternet.com  Thu Sep 30 11:04:26 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 30 Sep 2010 10:04:26 +0100
Subject: [Tutor] system()? popen2()? How to execute a command & save
	itsoutput?
References: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
Message-ID: <i81jr1$rl1$1@dough.gmane.org>


"James Hartley" <jjhartley at 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/




From jojo.mwebaze at gmail.com  Thu Sep 30 11:47:55 2010
From: jojo.mwebaze at gmail.com (Jojo Mwebaze)
Date: Thu, 30 Sep 2010 11:47:55 +0200
Subject: [Tutor] __import__()
In-Reply-To: <2683D022-51EA-4E64-9134-0EA2B677F9A8@xs4all.nl>
References: <2683D022-51EA-4E64-9134-0EA2B677F9A8@xs4all.nl>
Message-ID: <AANLkTikPheQeMBsbckKn=xvAd1F_uk-_LhjVkpG+h21O@mail.gmail.com>

On Thu, Sep 23, 2010 at 5:26 PM, Pete <pkoek11 at 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 at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/8afc2a69/attachment.html>

From ralf at schoenian-online.de  Thu Sep 30 12:13:04 2010
From: ralf at schoenian-online.de (ralf at schoenian-online.de)
Date: Thu, 30 Sep 2010 12:13:04 +0200 (CEST)
Subject: [Tutor] system()? popen2()? How to execute a command & save its
 output?
In-Reply-To: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
References: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
Message-ID: <166069185.141810.1285841584802.JavaMail.open-xchange@oxltgw14.schlund.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 <jjhartley at 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
> 

?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/b51fe150/attachment.html>

From steve at pearwood.info  Thu Sep 30 13:25:32 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 30 Sep 2010 21:25:32 +1000
Subject: [Tutor] generating independent random numbers
In-Reply-To: <4CA41447.9010107@ieee.org>
References: <AANLkTinAUiygmRhR=mTsGGeunSkGESeSja2zT4gWYHn-@mail.gmail.com>
	<4CA40C2D.6000809@ieee.org> <4CA41447.9010107@ieee.org>
Message-ID: <201009302125.33070.steve@pearwood.info>

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

From alan.gauld at btinternet.com  Thu Sep 30 13:45:40 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Thu, 30 Sep 2010 11:45:40 +0000 (GMT)
Subject: [Tutor] function error
In-Reply-To: <AANLkTinCLd93ST=OWoHVoMRNTMdVVuFf=EAVnDsHYBGU@mail.gmail.com>
References: <AANLkTik1zL0q6-qfZFdFamdU1fb3mnDAmthifjbeQMN3@mail.gmail.com>
	<i7sesd$7rc$1@dough.gmane.org>
	<AANLkTi=AMXimWVLr=eVTK0KHKALVpUvo0KsZVpYZ=1si@mail.gmail.com>
	<AANLkTinkCPC4eb9MMhj890kju4rTSqQpZ3kQhrVf9yFs@mail.gmail.com>
	<38D9DADF-E1A8-4BDC-8FF8-5F48C5510B23@gmail.com>
	<AANLkTimnoxb5gpX8D8NhU3Ji5KLUvmvg70XUeWPOZc51@mail.gmail.com>
	<i80a6c$amv$1@dough.gmane.org>
	<AANLkTinCLd93ST=OWoHVoMRNTMdVVuFf=EAVnDsHYBGU@mail.gmail.com>
Message-ID: <102031.75642.qm@web86707.mail.ird.yahoo.com>

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 <roberto03 at gmail.com>
> To: Alan Gauld <alan.gauld at btinternet.com>
> Cc: tutor at 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.gauld at 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
> 

From delegbede at dudupay.com  Thu Sep 30 13:57:03 2010
From: delegbede at dudupay.com (delegbede at dudupay.com)
Date: Thu, 30 Sep 2010 11:57:03 +0000
Subject: [Tutor] Printing prime numbers
Message-ID: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry>

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

From anand.shashwat at gmail.com  Thu Sep 30 15:41:33 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Thu, 30 Sep 2010 19:11:33 +0530
Subject: [Tutor] Printing prime numbers
In-Reply-To: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry>
References: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry>
Message-ID: <AANLkTik_-RwKfb4CCQup=wJttkhvLaAgqWkk-uiBCOQG@mail.gmail.com>

On Thu, Sep 30, 2010 at 5:27 PM, <delegbede at 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 at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/7417c1b1/attachment.html>

From delegbede at dudupay.com  Thu Sep 30 15:51:39 2010
From: delegbede at dudupay.com (delegbede at dudupay.com)
Date: Thu, 30 Sep 2010 13:51:39 +0000
Subject: [Tutor] Printing prime numbers
In-Reply-To: <AANLkTik_-RwKfb4CCQup=wJttkhvLaAgqWkk-uiBCOQG@mail.gmail.com>
References: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry><AANLkTik_-RwKfb4CCQup=wJttkhvLaAgqWkk-uiBCOQG@mail.gmail.com>
Message-ID: <2076462260-1285854700-cardhu_decombobulator_blackberry.rim.net-1478201634-@bda308.bisx.produk.on.blackberry>

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.shashwat at gmail.com>
Date: Thu, 30 Sep 2010 19:11:33 
To: <delegbede at dudupay.com>
Cc: <tutor at python.org>
Subject: Re: [Tutor] Printing prime numbers

On Thu, Sep 30, 2010 at 5:27 PM, <delegbede at 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 at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
~l0nwlf

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/c04b050f/attachment-0001.html>

From emmanuel.ruellan at laposte.net  Thu Sep 30 15:52:49 2010
From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan)
Date: Thu, 30 Sep 2010 15:52:49 +0200
Subject: [Tutor] Printing prime numbers
In-Reply-To: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry>
References: <361937526-1285847825-cardhu_decombobulator_blackberry.rim.net-239086245-@bda308.bisx.produk.on.blackberry>
Message-ID: <AANLkTi=Pu8hXvw23dmjaHJC0+oPxEHT5vrObW9_M6LSo@mail.gmail.com>

On Thu, Sep 30, 2010 at 1:57 PM, <delegbede at dudupay.com> wrote:

>
> 1 is prime
>

One is /not/ prime. </pedant>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/75154883/attachment.html>

From amonroe at columbus.rr.com  Thu Sep 30 16:27:43 2010
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Thu, 30 Sep 2010 10:27:43 -0400
Subject: [Tutor] system()? popen2()? How to execute a command & save
	itsoutput?
In-Reply-To: <i81jr1$rl1$1@dough.gmane.org>
References: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
	<i81jr1$rl1$1@dough.gmane.org>
Message-ID: <191621564266.20100930102743@columbus.rr.com>


>> 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


From tvsm at hotmail.com  Thu Sep 30 15:24:06 2010
From: tvsm at hotmail.com (T MURPHY)
Date: Thu, 30 Sep 2010 09:24:06 -0400
Subject: [Tutor] Doubly linked list
Message-ID: <BLU0-SMTP145CF1EF5F77D6506C4C1C0D3680@phx.gbl>

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.

From jjhartley at gmail.com  Thu Sep 30 19:49:07 2010
From: jjhartley at gmail.com (James Hartley)
Date: Thu, 30 Sep 2010 10:49:07 -0700
Subject: [Tutor] system()? popen2()? How to execute a command & save
	itsoutput?
In-Reply-To: <191621564266.20100930102743@columbus.rr.com>
References: <AANLkTinqe50EW5idgv7aq0u2JiL0H9JLs6bALts1H2T8@mail.gmail.com>
	<i81jr1$rl1$1@dough.gmane.org>
	<191621564266.20100930102743@columbus.rr.com>
Message-ID: <AANLkTi=_XqURPiJqmtUp=dpkF2_vAjRMDe0DEsHORRwd@mail.gmail.com>

On Thu, Sep 30, 2010 at 7:27 AM, R. Alan Monroe <amonroe at columbus.rr.com>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
>
> 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/a553be33/attachment.html>

From susana.delgado_s at utzmg.edu.mx  Thu Sep 30 20:05:08 2010
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Thu, 30 Sep 2010 13:05:08 -0500
Subject: [Tutor] Runnig a windows.exe from python
Message-ID: <AANLkTin3+GGX3Fzr6DyAkSWNHv9WnF0d78Z4OnvYre-4@mail.gmail.com>

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
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/0c7694b1/attachment.html>

From rwobben at hotmail.com  Thu Sep 30 20:38:19 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 30 Sep 2010 18:38:19 +0000
Subject: [Tutor] inheritance problem
Message-ID: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>


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
         
             
 
 

 
     

     
    
 
    

    
 
 
     



  		 	   		  

From evert.rol at gmail.com  Thu Sep 30 21:03:50 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Thu, 30 Sep 2010 21:03:50 +0200
Subject: [Tutor] inheritance problem
In-Reply-To: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>
References: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>
Message-ID: <DC5567FC-BBA7-4B03-8C14-6F0D5B20BF63@gmail.com>

  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


From bgailer at gmail.com  Thu Sep 30 21:12:48 2010
From: bgailer at gmail.com (Bob Gailer)
Date: Thu, 30 Sep 2010 15:12:48 -0400
Subject: [Tutor] inheritance problem
In-Reply-To: <AANLkTimmHRKtUNVyFwBpvh+PqkZpE5LSZv93PdMMCgH+@mail.gmail.com>
References: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>
	<AANLkTimmHRKtUNVyFwBpvh+PqkZpE5LSZv93PdMMCgH+@mail.gmail.com>
Message-ID: <AANLkTindZ8Vk3oKx_419JF_KzoDc06Uqm8BRwT4avV5J@mail.gmail.com>

Sorry I hit the send button instead of the save button

On Thu, Sep 30, 2010 at 2:58 PM, Bob Gailer <bgailer at gmail.com> wrote:
> On Thu, Sep 30, 2010 at 2:38 PM, Roelof Wobben <rwobben at 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

From emile at fenx.com  Thu Sep 30 21:45:16 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 30 Sep 2010 12:45:16 -0700
Subject: [Tutor] Doubly linked list
In-Reply-To: <BLU0-SMTP145CF1EF5F77D6506C4C1C0D3680@phx.gbl>
References: <BLU0-SMTP145CF1EF5F77D6506C4C1C0D3680@phx.gbl>
Message-ID: <i82pc3$l37$1@dough.gmane.org>

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






From fomcl at yahoo.com  Thu Sep 30 21:46:47 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 30 Sep 2010 12:46:47 -0700 (PDT)
Subject: [Tutor] (de)serialization questions
Message-ID: <79871.56708.qm@web110701.mail.gq1.yahoo.com>

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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/1fea82a9/attachment.html>

From fomcl at yahoo.com  Thu Sep 30 21:50:37 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 30 Sep 2010 12:50:37 -0700 (PDT)
Subject: [Tutor] inheritance problem
In-Reply-To: <AANLkTindZ8Vk3oKx_419JF_KzoDc06Uqm8BRwT4avV5J@mail.gmail.com>
References: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>
	<AANLkTimmHRKtUNVyFwBpvh+PqkZpE5LSZv93PdMMCgH+@mail.gmail.com>
	<AANLkTindZ8Vk3oKx_419JF_KzoDc06Uqm8BRwT4avV5J@mail.gmail.com>
Message-ID: <403268.33602.qm@web110704.mail.gq1.yahoo.com>


>> 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 <bgailer at gmail.com>
To: Roelof Wobben <rwobben at hotmail.com>; tutor at 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 <bgailer at gmail.com> wrote:
> On Thu, Sep 30, 2010 at 2:38 PM, Roelof Wobben <rwobben at 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 at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100930/9efc7a25/attachment-0001.html>

From joel.goldstick at gmail.com  Thu Sep 30 22:08:24 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Thu, 30 Sep 2010 16:08:24 -0400
Subject: [Tutor] inheritance problem
In-Reply-To: <AANLkTindZ8Vk3oKx_419JF_KzoDc06Uqm8BRwT4avV5J@mail.gmail.com>
References: <SNT118-W30E7087DE4B30267389693AE680@phx.gbl>
	<AANLkTimmHRKtUNVyFwBpvh+PqkZpE5LSZv93PdMMCgH+@mail.gmail.com>
	<AANLkTindZ8Vk3oKx_419JF_KzoDc06Uqm8BRwT4avV5J@mail.gmail.com>
Message-ID: <AANLkTik5dZwu6SnQVmiPDrHjcLnLQ5Trw3u+DUXPSj+D@mail.gmail.com>

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 ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick

From alan.gauld at btinternet.com  Thu Sep 30 23:42:41 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 30 Sep 2010 22:42:41 +0100
Subject: [Tutor] Doubly linked list
References: <BLU0-SMTP145CF1EF5F77D6506C4C1C0D3680@phx.gbl>
Message-ID: <i8308o$kdd$1@dough.gmane.org>


"T MURPHY" <tvsm at 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/