Re: [Tutor] key/value order in dictionaries
Steve Poe wrote: Hi tutor list, In dictionaries, I know that the keys are immutable, and the values can change What about the place/order of the key/order? I thought that they were sequential and they do not change. You were wrong :) A lot of electronic ink has been spilt on this subject over the years, and if you Google for things like "python ordered dictionary" you'll find various discussions and implementations. In CPython dictionaries won't generally change order if nothing's inserted or changed. But you certainly don't want to rely on that as a characteristic. A Python dictionary is considered inherently unordered (rather like a set). TJG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key/value order in dictionaries
Python dictionaries are not ordered & the order you will get when you print a dictionary is the order that the python virtual machines thinks optimal for that dictionary for its own internal procedures. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Mixing in and Mixing out classes in python
Hello, I am using the following function to mixin in classes into specific object instances (this is adapted from python-list written py J.Jacob "new-style-classes-mixin", Fri Aug 9 14:05:41 CEST 2002): *** def doMixin(targetInstance, extraClass): """ Mixin new style classes see thread python tutor list, appends the given name onto the class name """ class NewClass(extraClass,targetInstance.__class__): pass NewClass.__name__=targetInstance.__class__.__name__+"_"+extraClass.__name__ targetInstance.__class__=NewClass try: extraClass.initialize(targetInstance) except AttributeError: pass *** Is there an analogous way to "Mixout" classes from an instance at runtime? Thank you, Tomaz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communication between threads
> > I'm looking for some thoughts on how two separate threads can > communicate in Python > You will probably get out of your doubts by reading about the SocketServer module and SocketServer.ThreadingTCPServer class. Once your get a server up & running you can run parallel threads, from there you can build a global dictionary & use it to share data between you threads. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Communication between threads
This is a great suggestion. I too learned how to do threading in python from reading code. For me I read the btdownloadheadless.py code. Which comes as part of the standard bittorrent client in linux. On Thu, Jul 31, 2008 at 7:11 AM, Monika Jisswel <[EMAIL PROTECTED]> wrote: >> I'm looking for some thoughts on how two separate threads can >> communicate in Python > > You will probably get out of your doubts by reading about the SocketServer > module > and SocketServer.ThreadingTCPServer class. > > Once your get a server up & running you can run parallel threads, from there > you can build > > a global dictionary & use it to share data between you threads. > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading List from File
Hi Everyone, I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text file and assign those values to a list, x, such that: x = ["aaa", "bbb", "ccc"] The code that I have come up with looks like this: >>> x = [] >>> f = open(r'c:\test.txt', 'r') >>> x.extend(f.readlines()) >>> x ['"aaa","bbb","ccc"'] If you look closely, there is an extra pair of single quotes (') that encapsulates the string. Therefore, len(x) returns 1, instead of 3. Is there a function to "separate" this list out? I hope my question makes sense. Thanks in advance. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
On Thu, Jul 31, 2008 at 8:07 AM, S Python <[EMAIL PROTECTED]> wrote: > Hi Everyone, > > I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text > file and assign those values to a list, x, such that: > > x = ["aaa", "bbb", "ccc"] > > The code that I have come up with looks like this: > > >>> x = [] > >>> f = open(r'c:\test.txt', 'r') > >>> x.extend(f.readlines()) > >>> x > ['"aaa","bbb","ccc"'] > > If you look closely, there is an extra pair of single quotes (') that > encapsulates the string. Therefore, len(x) returns 1, instead of 3. Is > there a function to "separate" this list out? I hope my question makes > sense. > > Thanks in advance. > > Samir > > This is an answer by a novice, and it may not be the best around; Why don't you first get rid of the quotation marks and then split on the comma: >>> f = open(r'c:\test.txt', 'r').read().replace('"', '') >>> x = [] >>> x.extend(f.split(",")) >>> x ['aa', ' bb', ' cc'] >>> len(x) 3 > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد الغزالي "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
If your list is in the format: aaa,bbb,ccc You can use foo = in_file.readline.split(',') -- Amin Rainmaker--- Begin Message --- Hi Everyone, I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text file and assign those values to a list, x, such that: x = ["aaa", "bbb", "ccc"] The code that I have come up with looks like this: >>> x = [] >>> f = open(r'c:\test.txt', 'r') >>> x.extend(f.readlines()) >>> x ['"aaa","bbb","ccc"'] If you look closely, there is an extra pair of single quotes (') that encapsulates the string. Therefore, len(x) returns 1, instead of 3. Is there a function to "separate" this list out? I hope my question makes sense. Thanks in advance. Samir --- End Message --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
This is what I'd use... But it'd also be rather easy with regex... Oh well. Here: >>> f = open('intext', 'r') >>> foo = f.readline().strip().replace('"','').split(',') >>> foo ['aaa', 'bbb', 'ccc'] Cheers On 1/08/2008, at 1:49 AM, [EMAIL PROTECTED] wrote: If your list is in the format: aaa,bbb,ccc You can use foo = in_file.readline.split(',') -- Amin Rainmaker From: "S Python" <[EMAIL PROTECTED]> Date: 1 August 2008 1:07:22 AM To: tutor@python.org Subject: [Tutor] Reading List from File Hi Everyone, I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a text file and assign those values to a list, x, such that: x = ["aaa", "bbb", "ccc"] The code that I have come up with looks like this: >>> x = [] >>> f = open(r'c:\test.txt', 'r') >>> x.extend(f.readlines()) >>> x ['"aaa","bbb","ccc"'] If you look closely, there is an extra pair of single quotes (') that encapsulates the string. Therefore, len(x) returns 1, instead of 3. Is there a function to "separate" this list out? I hope my question makes sense. Thanks in advance. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] To Specify a directory path to download
Hello, I am new to python this is the code I have written to download a file from the internet and then send en email if any error occurs during download. I just want know how to specify which folder to download my files. It automatically downloads file to the directory where TEST1.txt sits... import urllib import traceback import sys import cStringIO import ncbi_SendEmail import os.path import os try: for url in open("test1.txt"): save_to = os.path.basename(url.strip()) urllib.urlretrieve(url.strip(),save_to) except: mssg = cStringIO.StringIO() traceback.print_exc(file=mssg) ncbi_SendEmail.email(mssg.getvalue()); mssg.close() Thanks a Ton! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
S Python wrote: Hi Everyone, I am trying to read a comma-delimitted list ("aaa","bbb","ccc") In this case, the standard library provides csv for parsing comma separated files. It's not the same as rolling your own, but it is made specifically for this use case... Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 53, Issue 110
> > Message: 5 > Date: Thu, 31 Jul 2008 09:07:22 -0400 > From: "S Python" <[EMAIL PROTECTED]> > Subject: [Tutor] Reading List from File > To: tutor@python.org > Message-ID: > <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-1" > > Hi Everyone, > > I am trying to read a comma-delimitted list ("aaa","bbb","ccc") from a > text > file and assign those values to a list, x, such that: > > x = ["aaa", "bbb", "ccc"] > > The code that I have come up with looks like this: > > >>> x = [] > >>> f = open(r'c:\test.txt', 'r') > >>> x.extend(f.readlines()) > >>> x > ['"aaa","bbb","ccc"'] > > If you look closely, there is an extra pair of single quotes (') that > encapsulates the string. Therefore, len(x) returns 1, instead of 3. > Is > there a function to "separate" this list out? I hope my question > makes > sense. I think you are better off using the csv module. If you have a comma separated file you could... import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row I yanked this straight out of the Python Reference Library :) > > Thanks in advance. > > Samir > -- next part -- > An HTML attachment was scrubbed... > URL: > <http://mail.python.org/pipermail/tutor/attachments/20080731/9f329f25/attachment-0001.htm> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Emile is right, in python you can do most of the stuff yourself by hand coding it, or you can use pre-made bullet proof and ready to go modules, here you can go for the csv module that comes part of the standard library. import csv myfile = open('file', 'r') # open file for reading data = csv.Reader(myfile, delimeter = ',') # let csv module load it print data 2008/7/31 Emile van Sebille <[EMAIL PROTECTED]> > S Python wrote: > >> Hi Everyone, >> I am trying to read a comma-delimitted list ("aaa","bbb","ccc") >> > > In this case, the standard library provides csv for parsing comma separated > files. It's not the same as rolling your own, but it is made specifically > for this use case... > > Emile > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Monika Jisswel wrote: Emile is right, in python you can do most of the stuff yourself by hand coding it, or you can use pre-made bullet proof and ready to go modules, here you can go for the csv module that comes part of the standard library. Yes -- and you'll avoid the pitfalls of dealing with embedded commas and quotes in the data. CSV can be messy. See http://en.wikipedia.org/wiki/Comma-separated_values for an overview of csv file content. Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] To Specify a directory path to download
> > urllib.urlretrieve(url.strip(),save_to) > could be changed into this : folder = '/home/html-data/' urllib.urlretrieve(url.strip(),folder+save_to) 2008/7/31 swati jarial <[EMAIL PROTECTED]> > Hello, > > I am new to python this is the code I have written to download a file from > the internet and then send en email if any error occurs during download. I > just want know how to specify which folder to download my files. It > automatically downloads file to the directory where TEST1.txt sits... > > import urllib > import traceback > import sys > import cStringIO > import ncbi_SendEmail > import os.path > import os > > try: > > for url in open("test1.txt"): > save_to = os.path.basename(url.strip()) > urllib.urlretrieve(url.strip(),save_to) > > except: > mssg = cStringIO.StringIO() > traceback.print_exc(file=mssg) > ncbi_SendEmail.email(mssg.getvalue()); > mssg.close() > > > > Thanks a Ton! > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Hi Everyone, Thanks for the variety of responses in such a short amount of time. This distribution list is incredible. Sorry for the delayed reply as I wanted to test what everyone suggested, so here goes: --- @Amin: I tried your suggestion, but perhaps I don't understand your syntax. Here is what I tried and the resulting error message: >>> f = open(r'C:\test.txt', 'r') >>> foo = f.readline.split(',') Traceback (most recent call last): File "", line 1, in foo = f.readline.split(',') AttributeError: 'builtin_function_or_method' object has no attribute 'split' Do you know what I did wrong? --- @Emad, Brett: Thank you for your solutions. They do exactly what I was looking for. --- @Chad: Thanks for your suggestion. I think I like it best for its simplicity. --- @Emile, Monika, kinuthi: The CSV standard library looks interesting but I am having mixed results in implementing it. For example, it works when I try this: >>> reader = csv.reader(open(r'c:\test.txt', 'rb')) >>> for row in reader: print row ['aaa', 'bbb', 'ccc'] but it fails when I try: >>> import csv >>> myfile = open(r'c:\test.txt', 'r') >>> data = csv.Reader(myfile, delimeter = ',') Traceback (most recent call last): File "", line 1, in data = csv.Reader(myfile, delimeter = ',') AttributeError: 'module' object has no attribute 'Reader' The error looks similar to what I received when I tried Amin's approach. Am I missing something? --- It's interesting to note that for the solutions to work correctly, I had to remove the quotation marks from the input file. Thanks again to EVERYONE who took the time to respond. I appreciate your help. Samir ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
oops it is reader not Reader (all lower case), so this line : data = csv.Reader(myfile, delimeter = ',') should be data = csv.reader(myfile, delimeter = ',') 2008/7/31 S Python <[EMAIL PROTECTED]> > Hi Everyone, > > Thanks for the variety of responses in such a short amount of time. > This distribution list is incredible. > > Sorry for the delayed reply as I wanted to test what everyone > suggested, so here goes: > > --- > > @Amin: I tried your suggestion, but perhaps I don't understand your > syntax. Here is what I tried and the resulting error message: > > >>> f = open(r'C:\test.txt', 'r') > >>> foo = f.readline.split(',') > > Traceback (most recent call last): > File "", line 1, in >foo = f.readline.split(',') > AttributeError: 'builtin_function_or_method' object has no attribute > 'split' > > Do you know what I did wrong? > > --- > > @Emad, Brett: Thank you for your solutions. They do exactly what I > was looking for. > > --- > > @Chad: Thanks for your suggestion. I think I like it best for its > simplicity. > > --- > > @Emile, Monika, kinuthi: The CSV standard library looks interesting > but I am having mixed results in implementing it. For example, it > works when I try this: > > >>> reader = csv.reader(open(r'c:\test.txt', 'rb')) > >>> for row in reader: >print row > > > ['aaa', 'bbb', 'ccc'] > > but it fails when I try: > > >>> import csv > >>> myfile = open(r'c:\test.txt', 'r') > >>> data = csv.Reader(myfile, delimeter = ',') > > Traceback (most recent call last): > File "", line 1, in > data = csv.Reader(myfile, delimeter = ',') > AttributeError: 'module' object has no attribute 'Reader' > > The error looks similar to what I received when I tried Amin's > approach. Am I missing something? > > --- > > It's interesting to note that for the solutions to work correctly, I > had to remove the quotation marks from the input file. > > Thanks again to EVERYONE who took the time to respond. I appreciate your > help. > > Samir > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Monika, Thanks for your help. I got it to work using the following (also had to spell "delimiter"): >>> import csv >>> myfile = open(r'c:\test.txt', 'r') >>> data = csv.reader(myfile, delimiter=',') >>> print data <_csv.reader object at 0x00D41870> >>> for item in data: print item ['aaa', 'bbb', 'ccc'] I think it was referred to in another post, but I have found this page to be helpful: http://docs.python.org/lib/csv-examples.html Thanks. Samir On Thu, Jul 31, 2008 at 2:20 PM, Monika Jisswel <[EMAIL PROTECTED]> wrote: > oops it is reader not Reader (all lower case), so this line : data = > csv.Reader(myfile, delimeter = ',') > should be data = csv.reader(myfile, delimeter = ',') > > > 2008/7/31 S Python <[EMAIL PROTECTED]> >> >> Hi Everyone, >> >> Thanks for the variety of responses in such a short amount of time. >> This distribution list is incredible. >> >> Sorry for the delayed reply as I wanted to test what everyone >> suggested, so here goes: >> >> --- >> >> @Amin: I tried your suggestion, but perhaps I don't understand your >> syntax. Here is what I tried and the resulting error message: >> >> >>> f = open(r'C:\test.txt', 'r') >> >>> foo = f.readline.split(',') >> >> Traceback (most recent call last): >> File "", line 1, in >>foo = f.readline.split(',') >> AttributeError: 'builtin_function_or_method' object has no attribute >> 'split' >> >> Do you know what I did wrong? >> >> --- >> >> @Emad, Brett: Thank you for your solutions. They do exactly what I >> was looking for. >> >> --- >> >> @Chad: Thanks for your suggestion. I think I like it best for its >> simplicity. >> >> --- >> >> @Emile, Monika, kinuthi: The CSV standard library looks interesting >> but I am having mixed results in implementing it. For example, it >> works when I try this: >> >> >>> reader = csv.reader(open(r'c:\test.txt', 'rb')) >> >>> for row in reader: >>print row >> >> >> ['aaa', 'bbb', 'ccc'] >> >> but it fails when I try: >> >> >>> import csv >> >>> myfile = open(r'c:\test.txt', 'r') >> >>> data = csv.Reader(myfile, delimeter = ',') >> >> Traceback (most recent call last): >> File "", line 1, in >>data = csv.Reader(myfile, delimeter = ',') >> AttributeError: 'module' object has no attribute 'Reader' >> >> The error looks similar to what I received when I tried Amin's >> approach. Am I missing something? >> >> --- >> >> It's interesting to note that for the solutions to work correctly, I >> had to remove the quotation marks from the input file. >> >> Thanks again to EVERYONE who took the time to respond. I appreciate your >> help. >> >> Samir >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
S Python wrote: f = open(r'C:\test.txt', 'r') foo = f.readline.split(',') readline is the function/method name readline() executes that function/method and returns a value try typing in 'type(f.readline)' vs 'type(f.readline())' you can't .split() a function but you may split its return value. but it fails when I try: import csv myfile = open(r'c:\test.txt', 'r') data = csv.Reader(myfile, delimeter = ',') Python is case sensitive -- reader is different from Reader. HTH, Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Emile is rigth, there should be a () there. I'm sorry, im writing this from my cellphone and there's not a pc around XD. I didn,t know about the csv module either and had to do over complicated things to deal with embedded commas, thx for that too :). -- Amin Rainmaker--- Begin Message --- S Python wrote: f = open(r'C:\test.txt', 'r') foo = f.readline.split(',') readline is the function/method name readline() executes that function/method and returns a value try typing in 'type(f.readline)' vs 'type(f.readline())' you can't .split() a function but you may split its return value. but it fails when I try: import csv myfile = open(r'c:\test.txt', 'r') data = csv.Reader(myfile, delimeter = ',') Python is case sensitive -- reader is different from Reader. HTH, Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --- End Message --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading List from File
Emile, Amin: Thank you both for your replies. I was able to get it working using: >>> f = open(r'c:\test.txt', 'r') >>> foo = f.readline().split(',') Samir On Thu, Jul 31, 2008 at 3:00 PM, <[EMAIL PROTECTED]> wrote: > Emile is rigth, there should be a () there. > I'm sorry, im writing this from my cellphone and there's not a pc around XD. > I didn,t know about the csv module either and had to do over complicated > things to deal with embedded commas, thx for that too :). > > -- > Amin Rainmaker > > -- Forwarded message -- > From: Emile van Sebille <[EMAIL PROTECTED]> > To: tutor@python.org > Date: Thu, 31 Jul 2008 11:34:56 -0700 > Subject: Re: [Tutor] Reading List from File > S Python wrote: > > f = open(r'C:\test.txt', 'r') > foo = f.readline.split(',') > > readline is the function/method name > readline() executes that function/method and returns a value > > try typing in 'type(f.readline)' vs 'type(f.readline())' > > you can't .split() a function but you may split its return value. > >> but it fails when I try: >> > import csv > myfile = open(r'c:\test.txt', 'r') > data = csv.Reader(myfile, delimeter = ',') >> > > Python is case sensitive -- reader is different from Reader. > > HTH, > > Emile > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Memory error - how to manage large data sets?
Kepala Pening wrote: def sumEvenFibonacci( limit ): a, b = 1, 1 # don't waste with a = 0 sum = 0 while b < limit: if b%2 == 0: sum += b a, b = b, a + b return sum print sumEvenFibonacci( 200 ) Every 3rd element in the Fibonacci series is an even number. So one could economize slightly: def sumEvenFibonacci(limit): a, b = 1, 1 # don't waste with a = 0 sum = 0 while b < limit: a, b = b, a + b sum += b a, b = b, a + b a, b = b, a + b return sum -- Bob Gailer 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Mixing in and Mixing out classes in python
"Tomaz Bevec" <[EMAIL PROTECTED]> wrote I am using the following function to mixin in classes into specific object instances ... Is there an analogous way to "Mixout" classes from an instance at runtime? I'm sure it is possible but... Are you just asking out of interest? Or do you have a real world need for this? Using multiple inheritence is a non trivial aspect of OOP (albeit powerful) that is fraught with difficulty and potential side effects. Adding a mixin at run time is difficult enough, removing one would bend my brain way too far I suspect. (Many coding standards insist on limiting MI to two classes or even banning it outright as being too bug prone.) Dynamic mixins add a whole new complexity (it's somewhat akin to the FAQ here about dynamically naming variables) all you generic code has to take account of the new method introduced and any potential side-effects that may not be handled in your code. Unless your mixin classes are ultra clean and stateless in their implementation you run a risk of breaking things in ways that are almost impossible to debug. I've never come across a need for dynamic mixin additions and I'm interested in how you think you might use this. (CLOS is the only other place I've even seen this discussed and it's possible there with some under the covers work but I've never seen it used!) Curious, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Memory error - how to manage large data sets?
"Kepala Pening" <[EMAIL PROTECTED]> wrote However, to have limit = 2, perhaps I should do while b <= limit. Thanks Alan for pointing it out. No probs, forgetting to test both ends of the range is a common mistake. In fact good testing practice says that for any range of values you should test - the lowest legal value - correct result - one lower than the lowest - fails gracefully - much lower than lowest - fails gracefully - a mid range value - correct result - the highest legal value - correct value (Of course testing the "highest possible value" would be tricky in your case! :-) - one higher than the highest - fails gracefully - much higher than the legal limit - fails gracefully - an invalid value - fails gracefully (eg in your case limit = 'four') So that's at least 8 tests for every range parameter/variable in your code. Automated testing is "A Good Thing" :-) Alan G. - Original Message - From: "Alan Gauld" <[EMAIL PROTECTED]> To: tutor@python.org Date: Thu, 31 Jul 2008 06:39:32 +0100 Subject: Re: [Tutor] Memory error - how to manage large data sets? "Kepala Pening" <[EMAIL PROTECTED]> wrote > def sumEvenFibonacci( limit ): > a, b = 1, 1 # don't waste with a = 0 > sum = 0 > while b < limit: > if b%2 == 0: sum += b > a, b = b, a + b > return sum > > print sumEvenFibonacci( 200 ) Does it work for limit = 2? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Style help: long strings with formatting
Alan Gauld wrote: "W W" <[EMAIL PROTECTED]> wrote output = "At an average weekly savings of $%.02f, your monthly savings will be $%.02f. \n Your annual savings will be $%.02f." % (diff, monthly_savings, annual_savings) print output. As you can see, it's very much longer than the 72 characters suggested in the PEP 8 found here: http://www.python.org/dev/peps/pep-0008/ Use a triple quoted string for multiline output output = """ At an average weekly savings of \t$%.02f, your monthly savings will be \t$%.02f. Your annual savings will be \t$%.02f. """ % (diff, monthly_savings, annual_savings) print output I know it would be fairly trivial to split it up into several strings, and concatenating or printing each one. Multiline strings are designed to save you having to do that. Alan, you have a couple of \n that the OP did not ask for. Wayne, besides Alan's suggestion you might be looking for something like : Output = ('At an average weekly savings of $%.02f, your monthly ' 'savings will be $%.02f. \n Your annual savings will' ' be $%.02f.') % (diff, monthly_savings, annual_savings) or : Output = ( 'At an average weekly savings of $%.02f, your monthly ' 'savings will be $%.02f. \n Your annual savings will' ' be $%.02f.' ) % ( diff , monthly_savings , annual_savings) Or whatever. Parenthesis will help a lot when formatting your code. HTH ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Mixing in and Mixing out classes in python
Thanks for your reply Alan, I am partially asking out of interest, but I also have a potential application. I'm working on a simulation of cellular growth patterns (basically cell instances interacting stochastically on a lattice). Anyway, there are many different cell "behaviors" that I have to simulate, and cells can potentially gain and lose these "behaviors" over the course of the simulation. It would be too much to put every behavior function in the cell class, so I'm writing each behavior as a mixin and mixing it in (and initializing it) when necessary or when biological function is gained by the cells. In addition some of the behaviors would be too big (as in lines of code) if they were implemented in one function so splitting functionality up in my mixin class makes it conceptually easier for me. Also the behaviors sometimes need access to the internals of the cell class. After I mixin a class every method that starts with the word 'behavior.*' in that class is called when I update the simulation. All of my mixins inherit from "object" only. So far my approach is working well, but I don't have a clean way for cells to lose functionality. Hence my question about mixin out. I tried to just delete the 'behavior.*' functions with the del operator (like for an attribute) but it didn't work. I have however thought of a number of ways to work around this, and per your suggestion I think I'll just try something else, but if you have any idea on how to dynamically mix out I'd be glad to here it. Thanks, Tomaz --- On Thu, 7/31/08, Alan Gauld <[EMAIL PROTECTED]> wrote: > From: Alan Gauld <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Mixing in and Mixing out classes in python > To: tutor@python.org > Date: Thursday, July 31, 2008, 3:16 PM > "Tomaz Bevec" <[EMAIL PROTECTED]> wrote > > > I am using the following function to mixin in classes > > into specific object instances ... > > > Is there an analogous way to "Mixout" > classes from an instance at > > runtime? > > I'm sure it is possible but... > > Are you just asking out of interest? > Or do you have a real world need for this? > > Using multiple inheritence is a non trivial aspect of OOP > (albeit > powerful) > that is fraught with difficulty and potential side effects. > Adding a > mixin at > run time is difficult enough, removing one would bend my > brain way too > far I suspect. (Many coding standards insist on limiting MI > to two > classes > or even banning it outright as being too bug prone.) > > Dynamic mixins add a whole new complexity (it's > somewhat akin to > the FAQ here about dynamically naming variables) all you > generic > code has to take account of the new method introduced and > any > potential side-effects that may not be handled in your > code. Unless > your mixin classes are ultra clean and stateless in their > implementation > you run a risk of breaking things in ways that are almost > impossible > to debug. > > I've never come across a need for dynamic mixin > additions and > I'm interested in how you think you might use this. > (CLOS is the only > other place I've even seen this discussed and it's > possible there > with some under the covers work but I've never seen it > used!) > > Curious, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Mixing in and Mixing out classes in python
On Thu, Jul 31, 2008 at 8:09 PM, Tomaz Bevec <[EMAIL PROTECTED]> wrote: > Thanks for your reply Alan, > > I am partially asking out of interest, but I also have a potential > application. > > I'm working on a simulation of cellular growth patterns (basically cell > instances interacting stochastically on a lattice). Anyway, there are many > different cell "behaviors" that I have to simulate, and cells can potentially > gain and lose these "behaviors" over the course of the simulation. It would > be too much to put every behavior function in the cell class, so I'm writing > each behavior as a mixin and mixing it in (and initializing it) when > necessary or when biological function is gained by the cells. Perhaps you could keep the behaviors in a dictionary? You could override __getattr__() in the cell class to look up attributes whose names start with 'behavior' in the dict. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key/value order in dictionaries
On Thursday 31 July 2008 05:33, Monika Jisswel wrote: > Python dictionaries are not ordered & the order you will get when you print > a dictionary is the order that the python virtual machines thinks optimal > for that dictionary for its own internal procedures. If you need an ordered dictionary, such things exist. The implementation I use is at http://www.voidspace.org.uk/python/modules.shtml, but there may be one or two other popular ones out there. You probably shouldn't use them unless you have a specific need to. They will be a lot slower, and extra dependencies always complicates distribution. Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor