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:
a b c
d
a x
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:
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:
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:
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:
References: <20100831022240.GA6772@scriptkitchen.com>
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(_)
>
>
> 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>
<20100901014522.GA17953@scriptkitchen.com>
Message-ID:
"Payal" 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:
Message-ID:
"Ranjith Kumar" 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:
References:
Message-ID: <4C7E12D0.908@otenet.gr>
On 09/01/2010 11:17 AM, Alan Gauld wrote:
> "Ranjith Kumar" 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:
References:
Message-ID:
On Wed, Sep 1, 2010 at 1:47 PM, Alan Gauld wrote:
> "Ranjith Kumar" 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:
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:
<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:
References:
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:
References:
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:
>
>
> a b c
> d
>
> a x
>
>
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
item, yield it.
Things get tricky if you can nest lines...
a bdc
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:
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
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:
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: <4C7E12D0.908@otenet.gr>
<4C7E13F9.6050202@otenet.gr>
Message-ID:
"Nick Raptis" 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:
"Currall, Andrew" 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:
References:
<4C7E12D0.908@otenet.gr>
<4C7E13F9.6050202@otenet.gr>
Message-ID:
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:
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:
References:
<4C7E12D0.908@otenet.gr> <4C7E13F9.6050202@otenet.gr>
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: <4C7E12D0.908@otenet.gr> <4C7E13F9.6050202@otenet.gr>
<4C7EC77B.5070400@alchemy.com>
Message-ID:
"Steve Willoughby" 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>
<20100901014522.GA17953@scriptkitchen.com>
Message-ID:
Alan Gauld wrote:
> "Payal" 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)
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:
References: <20100901014522.GA17953@scriptkitchen.com>
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:
References:
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:
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:
References:
Message-ID:
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:
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:
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:
Message-ID:
"Colleen Glaeser" 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:
References:
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
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:
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:
References:
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:
References:
Message-ID:
>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 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:
Message-ID:
"Dipo Elegbede" 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:
References:
Message-ID:
On Thu, Sep 2, 2010 at 11:05 PM, David Hutto 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:
References:
Message-ID:
On Fri, Sep 3, 2010 at 2:51 PM, David Hutto wrote:
> On Thu, Sep 2, 2010 at 11:05 PM, David Hutto 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:
References:
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:
<201009041112.28651.steve@pearwood.info>
Message-ID:
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 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:
References:
<201009041112.28651.steve@pearwood.info>
Message-ID:
On Fri, Sep 3, 2010 at 9:57 PM, 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
>
> On Fri, Sep 3, 2010 at 9:12 PM, Steven D'Aprano 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:
References:
<201009041112.28651.steve@pearwood.info>
Message-ID:
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:
"Gregory, Matthew" 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:
References:
<201009041112.28651.steve@pearwood.info>
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:
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:
References:
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:
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:
References:
Message-ID:
On 9/4/10, 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?
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:
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:
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:
References:
Message-ID:
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 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:
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:
References:
Message-ID:
On 4 September 2010 19:14, 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?
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:
References:
Message-ID:
On 4 September 2010 19:25, Sander Sweers 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:
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:
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:
References:
Message-ID:
On 04/09/2010 18:29, Sander Sweers wrote:
> On 4 September 2010 19:25, Sander Sweers 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:
References:
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:
References:
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:
References:
Message-ID:
On Sat, Sep 4, 2010 at 1:40 PM, aug dawg 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:
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:
References:
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:
References:
Message-ID: <1283628316.29106.12.camel@Nokia-N900>
----- Original message -----
> On 9/4/10, 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?
> 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:
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:
Message-ID:
"aug dawg" 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:
<1283628316.29106.12.camel@Nokia-N900>
Message-ID:
>> On 9/4/10, 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?
>> 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:
References:
<1283628316.29106.12.camel@Nokia-N900>
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:
<1283628316.29106.12.camel@Nokia-N900>
<13254518884.20100904182431@columbus.rr.com>
Message-ID:
>> ? ? 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:
References:
<13254518884.20100904182431@columbus.rr.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:
References:
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:
<4C8298E4.5040507@ieee.org>
Message-ID:
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 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:
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:
References:
Message-ID:
> 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:
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:
References: <4C8298E4.5040507@ieee.org>
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:
<4C82F34A.90607@gmail.com>
Message-ID:
> ?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:
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
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:
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:
References:
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
> 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: ,
<201009052355.33195.steve@pearwood.info>
Message-ID:
> 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
> > 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:
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:
References:
Message-ID:
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 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:
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:
References:
<201009052355.33195.steve@pearwood.info>
Message-ID:
On Sun, Sep 5, 2010 at 4:17 PM, Roelof Wobben 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:
References: ,
,
Message-ID:
> 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:
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:
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:
References:
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:
References:
Message-ID:
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 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:
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:
<201009041112.28651.steve@pearwood.info>
<201009042016.13581.steve@pearwood.info>
Message-ID:
On Sat, Sep 4, 2010 at 6:16 AM, Steven D'Aprano 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:
References:
Message-ID:
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:
On Sun, Sep 5, 2010 at 8:51 PM, Micheal Beatty 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:
>>> 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:
References: