Re: [Tutor] quick question
On 28/09/2012 06:18, jh wrote: [snip] The subtotal of your items is: 26010.8502 The total amount of your items plus tax is: 27,571.50 My question here is, why does my subtotal have so many decimals when I never went above 2 in my input? Thanks in advance, J Brett Ritter has already answered your question, but a web search would have found the answer a lot faster, as this has been asked umpteen times on Python lists alone. Also note that if you'd have formatted the output in the same way that you did for the total you'd never have noticed. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Netiquette
On Sep 28, 2012 4:47 AM, "Dwight Hutto" wrote: > > On Wed, Sep 26, 2012 at 6:59 AM, Walter Prins wrote: > > Dwight, > > > > On 26 September 2012 09:26, Dwight Hutto wrote: > >> The only face I personally want to see of him > >>> because of this is his back. > >>> > >> > >> You wanna see my ass, because that's what you want homo. Butt just > >> look, you can't touch. > > > > The personal attacks and innuendo are really not acceptable and you're > > apparently deliberately twisting/misinterpreting Mark's words there. > > Oooh, a PR attack in another post. > > > > Wy out of line and quite disingenuous. Would you respond so > > aggressively to people in person? No? Well why do you think it's OK > > to be abusive on the internet? (If you do think it's OK to be this > > abusive to people in person, then you're sadly mistaken.) Grow up. > > Walk away. Learn to be polite to people you don't know. This is not > > the school playground and you're not 5 years old. > > But he started it. > > Do some careful > > introspection. > > Yeah, all up in my fucking cranium with nothing but me and God to hold > on to one another. > > > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Probably not a good idea to advertise that your the CEO of hitwebdevelopment.com if your gonna post like that. Bodsda ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] lazily decorated sort
Hi all, I'm wondering if anyone has seen or knows of a good way to do a lazily decorated sort. I was reading about how good the DSU (decorate, sort, undecorate) approach is but the problem that we are running into in SymPy is that we want to get by with a fast hash sort if possible, and only decorate to break ties *if necessary*. It's a pity to decorate with an expensive function if you don't need it but I don't know how to only decorate when there are ties. Do you have any ideas how to do the following better: def f(): """delay for 2 seconds""" from time import time from random import random t=time() while time()-t<1: pass return random class foo(object): """an object that calls the delay function when comparing""" def __eq__(self, other): return f() == f() def __lt__(self, other): return f() < f() def lazyDSU(seq, keys=[]): """Return sorted seq, breaking ties by lazily applying keys successively as needed from the list of provided keys.""" if not keys: seq = sorted(seq) else: d = defaultdict(list) f = keys.pop(0) for a in seq: d[f(a)].append(a) seq = [] for k in sorted(d.keys()): if len(d[k]) > 1 and keys: seq.extend(lazyDSU(d[k], keys=keys[1:])) else: seq.extend(d[k]) return tuple(seq) >>> lazyDSU(range(5)) # fast (0, 1, 2, 3, 4) >>> [i[0] for i in lazyDSU(zip(range(5), [foo()]*5))] # fast, no ties [0, 1, 2, 3, 4] >>> [i[0] for i in lazyDSU([(0, foo())] + list(zip(range(5), [foo()]*5)))] # >>> slower [0, 0, 1, 2, 3, 4] The last run takes 4 seconds (but not 12 seconds) because only two had to have ties broken. In the examples, no keys were passed but the discretionary decoration was demonstrated. /Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to print array without adding newline
Thank you for your reply. I understand that it is odd, but my program is being called from a hubot and returning data to it as well. I have figured out how to make the changes to get it to output the correct data in the correct format, but now I am getting a "Premature end of script headers" error. I have the correct #! line and the output from the command line shows no errors that would be interfering. Is there a way to make sure it is showing me all the errors? To increase error logging? -- !/usr/bin/env python import cloudfiles import random import sys import array conn = cloudfiles.get_connection('username', 'key') containers = conn.get_all_containers() i=0 print "Content-type: text/html"; wholelist=containers[0].list_objects() random.shuffle(wholelist) newlist=[] #newlist=wholelist[:] try: #print sys.argv[1] if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") #print sys.argv[1] del wholelist[int(sys.argv[1]):] while i < int(sys.argv[1]): newlist.append("http://example.com/"+wholelist[i].rstrip()) i = i+1 except IndexError, e: del newlist[5] except Exception, err: print 'Caught an exception' print newlist, --- Vicki > ---Original Message--- > From: Dave Angel > To: vickistan > Cc: tutor@python.org > Subject: Re: [Tutor] how to print array without adding newline > Sent: Sep 06 '12 05:13 > > On 08/18/2012 09:17 PM, vickistan wrote: > > Hello: I am trying to output an array to another program that takes an > array > > as input, but the print statement adds a newline. If it were adding to each > > individual element, I could solve it easily, but it is adding one at the > end > > of the array. Is there another way to print an array besides > > > > print arrayname > > > > If it were a string, I have a whole host of options, but I need it to be > > output as an array. Each element is a url. I call it from a browser, and it > > works except for the added newline. > > > > Here are the relevant lines: > > > > = > > /* code that connects to cloudfiles omitted */ > > > > containers = conn.get_all_containers() > > i=0 > > print "Content-type: text/html\n\n"; > > wholelist=containers[0].list_objects() > > random.shuffle(wholelist) > > newlist=[] > > try: > > del wholelist[int(sys.argv[1]):] > > while i < int(sys.argv[1]): > > newlist.append("http://example.com/"+wholelist[i].rstrip()) > > i = i+1 > > except IndexError, e: > > del newlist[5] > > print newlist > > == > > > > The output I am seeing is as follows: > > > > ['http://example.com/wet-longhaireddachshund.jpg', > > 'http://example.com/dachshund2.jpg', > > 'http://example.com/dachshundingrass.jpg'] > > > > Any tips on better coding practices are welcome, but please don't beat me > up > > > > Thanks, > > vickistan > > > > > > > > I don't see any arrays in that code, just lists. i also don't see how > that program could produce exactly that ouput, as it also prints > > "Content-type: text/html\n\n"; > > But if you literally mean that only the final newline is a problem, then > just end the print statement with a comma: > print newlist, > > If you want more flexibility, instead of printing the list as a single > entity, you can just loop through it. that way, you can choose which > newlines you want, if any. > for item in newlist: > print repr(item),#or many other variants. But you probably > want some delimeter at least. > > > it's not clear what your other program is expecting for stdin, since > there is no single standard for "takes an array for input." it's also > unclear why a trailing linefeed should hurt you. But I hope this will > help some. > > > -- > > DaveA > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] python new window
I have used python a lot at school and am relatively good with it. I just tried to get it on my mac and i try to open a "new window" and every time I do it freezes and i have to either do a forced quit or unplug the whole computer. I have been able to get into a "new window" through programs i saved on a jump drive at school and brought home but every time i try to do anything from that window it freezes. i tried re downloading it but that didn't help. can some one please help me zack dunphey ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing a function to examine a directory and testing with unittest
Hi. I have an assigment where I'm need to write a module containing a function to examine the contents of the current working directory and print out a count of how many files have each extension (".txt", ".doc", etc.) I am a beginner in Python. This is the code of the function module: --- import os from collections import Counter path = ":c//mypath/dir" dirs = os.listdir( path ) filenames = {"this.txt", "that.txt", "the_other.txt","this.doc","that.doc","this.pdf","first.txt","that.pdf"} extensions = [] for filename in filenames: f = open(filename, "w") f.write("Some text\n") f.close() name , ext = os.path.splitext(f.name) extensions.append(ext) # This would print all the files and directories for file in dirs: print(file) for ext, count in Counter(extensions).items(): print("Count for %s: " % ext, count) --- path is just an example - not real path. I need to make this module into a function and write a separate unittest module to verify by testing that the function gives correct results. Help and pointers are much appreciated. -- Sukhvinder Singh +4740633099 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] new student
I am looking for some recommendations books to read.websites,links,any information would be appreciated. Thanks, jmslgil...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] list all links with certain extension in an html file python
I want to extract (no I don't want to download) all links that end in a certain extension. Suppose there is a webpage, and in the head of that webpage there are 4 different CSS files linked to external server. Let the head look like this: http://foo.bar/part1.css";> http://foo.bar/part2.css";> http://foo.bar/part3.css";> http://foo.bar/part4.css";> Please note that I don't want to download those CSS, instead I want something like this (to stdout): http://foo.bar/part1.css http://foo.bar/part1.css http://foo.bar/part1.css http://foo.bar/part1.css Also I don't want to use external libraries. I am asking for: which libraries and functions should I use? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Storing information as attributes or as a dictionary
Dear all, Suppose I have a parser that parses information stored in e.g. an XML file. I would like to store the information contained in this XML file as a Python object. One option is to create a class like this: class Record(object): pass and store the information in the XML file as attributes of objects of this class, as in >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record.name "John Doe" >>> record.birthday "February 30, 1920" Alternatively I could subclass the dictionary class: class Record(dict): pass and have something like >>> handle = open("myxmlfile.xml") >>> record = parse(handle) # returns a Record object >>> record['name'] "John Doe" >>> record['birthday'] "February 30, 1920" I can see some advantage to using a dictionary, because it allows me to use the same strings as keys in the dictionary as in used in the XML file itself. But are there some general guidelines for when to use a dictionary-like class, and when to use attributes to store information? In particular, are there any situations where there is some advantage in using attributes? Thanks, -Michiel. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to save text or dat file using python
Hello I am new user of python pls let me know how to save dat or txt file using python? what is the basic cmd for this? thanks a lot in advance ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] floating point rounding inconsistency
Hello, I am new to python, and I was experimenting with the round function, and came across what appears to be a bug in floating point rounding. I am guessing there is a valid explanation for it. When I round the floating points 10.6[0-9]5 to two decimal places, it rounds as expected for 6 of the 10, but not for the other 4. When I try the same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 possibilties, and not for the analogous floats. Also, python storing the numbers as they are represented at the prompt. i.e. 10.665 is stored as 10.665, not something like 10.66501 or 10.664. Can anyone explain to me what's happening? $ python Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> round(10.605,2) 10.61 >>> round(10.615,2) 10.62 >>> round(10.625,2) 10.63 >>> round(10.635,2) 10.63 >>> round(10.645,2) 10.64 >>> round(10.655,2) 10.65 >>> round(10.665,2) 10.66 >>> round(10.675,2) 10.68 >>> round(10.685,2) 10.69 >>> round(10.695,2) 10.7 >>> round(10.705,2) 10.71 >>> round(10.715,2) 10.71 >>> round(10.725,2) 10.72 >>> round(10.735,2) 10.73 >>> round(10.745,2) 10.74 >>> round(10.755,2) 10.76 >>> round(10.765,2) 10.77 >>> round(10.775,2) 10.78 >>> round(10.785,2) 10.79 >>> round(10.795,2) 10.79 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: regarding saving data in ASCII format
Hello i am new user of python pls let me know how to save the data in ascii formate Suppose I hv two column data in x and y like x(:,-1) and y(:,0) then how to save this in [x(:,-1), y(:,0)]; and then save this in ascii or dat file? thanks a lot in advance -- preeti gaikwad ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
I would like tutorial ? Thank You ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] assembly language and boot loader
Hi there, Is there any IDE or Python interpreter that can show the assembly language generated by each line of python code? Is there any popular boot loader written in Python (plus some assembly code)? Thanks, Jerry___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python for Absolute Beginners
Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access the Companion Guide. Do I need it? Do I have to purchase it? How do I get it? The site he sends me to is very confusing.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On Fri, Sep 28, 2012 at 9:44 AM, CHERRY PHOUTHAVONG wrote: > I would like tutorial ? Thank You > What tutorial ? > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrou...@gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
On 11/09/2012 12:44, Chris Smith wrote: Hi all, I'm wondering if anyone has seen or knows of a good way to do a lazily decorated sort. I was reading about how good the DSU (decorate, sort, undecorate) approach is but the problem that we are running into in SymPy is that we want to get by with a fast hash sort if possible, and only decorate to break ties *if necessary*. It's a pity to decorate with an expensive function if you don't need it but I don't know how to only decorate when there are ties. Do you have any ideas how to do the following better: def f(): """delay for 2 seconds""" from time import time from random import random t=time() while time()-t<1: pass return random class foo(object): """an object that calls the delay function when comparing""" def __eq__(self, other): return f() == f() def __lt__(self, other): return f() < f() def lazyDSU(seq, keys=[]): """Return sorted seq, breaking ties by lazily applying keys successively as needed from the list of provided keys.""" if not keys: seq = sorted(seq) else: d = defaultdict(list) f = keys.pop(0) for a in seq: d[f(a)].append(a) seq = [] for k in sorted(d.keys()): if len(d[k]) > 1 and keys: seq.extend(lazyDSU(d[k], keys=keys[1:])) else: seq.extend(d[k]) return tuple(seq) lazyDSU(range(5)) # fast (0, 1, 2, 3, 4) [i[0] for i in lazyDSU(zip(range(5), [foo()]*5))] # fast, no ties [0, 1, 2, 3, 4] [i[0] for i in lazyDSU([(0, foo())] + list(zip(range(5), [foo()]*5)))] # slower [0, 0, 1, 2, 3, 4] The last run takes 4 seconds (but not 12 seconds) because only two had to have ties broken. In the examples, no keys were passed but the discretionary decoration was demonstrated. /Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor It's my understanding that DSU is unneccessary in modern versions of Python so I suggest you read http://docs.python.org/howto/sorting.html http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Sorting these before you go any further, if you haven't already done so already that is. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hello
On 17/09/2012 20:21, Fation Beqirllari wrote: I have a php code and I want to translate it to python..Can you help me please,or show me how to do it ? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor A better subject would help and no, we don't show you how to do it. You show us that you'd made some sort of attempt at translating the code and run into a problem, then we'll help. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to save text or dat file using python
On 20/09/2012 17:14, Preeti Gaikwad wrote: Hello I am new user of python pls let me know how to save dat or txt file using python? what is the basic cmd for this? thanks a lot in advance ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Yod need to write some code. When you run into problems show us your code and if appropriate the entire traceback and we'll help. As a starter search the web for something like "Python with file write". -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On 28/09/2012 05:14, CHERRY PHOUTHAVONG wrote: I would like tutorial ? Thank You ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Given that your subject is specifically no subject that's a tricky one. If you're talking about a Python tutorial, a good starting point is the Python tutorial http://docs.python.org/tutorial/ :) -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python new window
Hi Zack, On 11 September 2012 22:18, zack dunphey wrote: > I have used python a lot at school and am relatively good with it. I just > tried to get it on my mac and i try to open a "new window" and every time I > do it freezes and i have to either do a forced quit or unplug the whole > computer. I have been able to get into a "new window" through programs i > saved on a jump drive at school and brought home but every time i try to do > anything from that window it freezes. i tried re downloading it but that > didn't help. > can some one please help me I'd like to help but I have no idea what you're talking about. What is a "new window"? Is that something that your script tries to do? Or do you mean a window to view and run your code? Could you be more specific about what exactly you're doing? Python does many things and can be used in many different ways so you cannot assume that anyone else really has any idea what you are doing. Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 19 September 2012 19:27, Andrew Tritt wrote: > Hello, > > I am new to python, and I was experimenting with the round function, and > came across what appears to be a bug in floating point rounding. I am > guessing there is a valid explanation for it. > > When I round the floating points 10.6[0-9]5 to two decimal places, it > rounds as expected for 6 of the 10, but not for the other 4. When I try the > same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 > possibilties, and not for the analogous floats. > > Also, python storing the numbers as they are represented at the prompt. > i.e. 10.665 is stored as 10.665, not something like 10.66501 or > 10.664. > > Can anyone explain to me what's happening? > It is because Python (like all programming languages I know) represents floating point numbers in base 2. This is discussed in the python.orgtutorial: http://docs.python.org/tutorial/floatingpoint.html Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: regarding saving data in ASCII format
On 21/09/2012 14:20, Preeti Gaikwad wrote: Hello i am new user of python pls let me know how to save the data in ascii formate Suppose I hv two column data in x and y like x(:,-1) and y(:,0) then how to save this in [x(:,-1), y(:,0)]; and then save this in ascii or dat file? thanks a lot in advance ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Please see my response to your other question :) -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assembly language and boot loader
On 23 September 2012 05:46, Fit Wii wrote: > Is there any IDE or Python interpreter that can show the assembly language > generated by each line of python code? Is there any popular boot loader > written in Python (plus some assembly code)? > Python doesn't generate assembly language code. It does, however, compile python code to bytecode which is like assembly for the Python interpreter rather than for the CPU. Have a look at the dis module: http://docs.python.org/library/dis.html Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assembly language and boot loader
On 23/09/2012 05:46, Fit Wii wrote: Hi there, Is there any IDE or Python interpreter that can show the assembly language generated by each line of python code? Is there any popular boot loader written in Python (plus some assembly code)? Thanks, Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I don't know about getting down to assembly but the dis module http://docs.python.org/library/dis.html can show you the byte code. -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new student
On Sat, Sep 8, 2012 at 12:08 PM, james gillis wrote: > I am looking for some recommendations books to > read.websites,links,any information would be appreciated. Thanks, > jmslgil...@gmail.com > http://python.org/doc/ is a nice place to start. -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list all links with certain extension in an html file python
On 16 September 2012 08:20, Santosh Kumar wrote: > I want to extract (no I don't want to download) all links that end in > a certain extension. > > Suppose there is a webpage, and in the head of that webpage there are > 4 different CSS files linked to external server. Let the head look > like this: > > http://foo.bar/part1.css > "> > http://foo.bar/part2.css > "> > http://foo.bar/part3.css > "> > http://foo.bar/part4.css > "> > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > > Also I don't want to use external libraries. I am asking for: which > libraries and functions should I use? > If you don't want to use any third-party libraries then the standard library has a module urllib2 for downloading a html file and htmlparser for parsing it: http://docs.python.org/library/urllib2.html#examples http://docs.python.org/library/htmlparser.html#example-html-parser-application Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 28/09/2012 12:56, Oscar Benjamin wrote: On 19 September 2012 19:27, Andrew Tritt wrote: Hello, I am new to python, and I was experimenting with the round function, and came across what appears to be a bug in floating point rounding. I am guessing there is a valid explanation for it. When I round the floating points 10.6[0-9]5 to two decimal places, it rounds as expected for 6 of the 10, but not for the other 4. When I try the same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 possibilties, and not for the analogous floats. Also, python storing the numbers as they are represented at the prompt. i.e. 10.665 is stored as 10.665, not something like 10.66501 or 10.664. Can anyone explain to me what's happening? It is because Python (like all programming languages I know) represents floating point numbers in base 2. This is discussed in the python.orgtutorial: http://docs.python.org/tutorial/floatingpoint.html Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The Python round function is itself problematic. The idea of deprecating it is currently being discussed on Python ideas. This quote from Calvin Spealman is typical "Also, I'd be completely in support of dropping round() and agree it gets misused and leads to too much confusion. We should promote the right ways, and sometimes to show the right path you need to lock another door and throw away the key.". -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
On 11/09/12 21:44, Chris Smith wrote: Hi all, I'm wondering if anyone has seen or knows of a good way to do a lazily decorated sort. I was reading about how good the DSU (decorate, sort, undecorate) approach is but the problem that we are running into in SymPy is that we want to get by with a fast hash sort if possible, and only decorate to break ties *if necessary*. It's a pity to decorate with an expensive function if you don't need it but I don't know how to only decorate when there are ties. Firstly, unless you intend supporting Python 2.3 or older, there is (probably) no need for an explicit DSU approach. Instead, use the key argument to sorted and list.sort. I'm not sure I completely understand your question. If you know ahead of time that you can avoid DSU, you can do this: if condition: x = sorted(something) else: x = sorted(something, key=func) But I imagine that's not what you mean. My guess is that you want the sort to be sufficiently clever that instead of doing this: decorate every item compare decorated items, and sort as needed undecorate every item you want it to do this: compare items, sorting as needed if they are equal, compare decorated items (which will never tie???) Am I close? I think you could arrange that two ways: 1) A two-pass sort; first, sort undecorated, then scan looking for ties, if you find any, sort again with a key function; (This is safe, since sorting in Python is now guaranteed to be stable.) 2) or use a key function that does something like this: class SmartComparator(object): def __init__(self, item): self.item = item def __cmp__(self, other): x = cmp(self.item, other.item) if x == 0: return cmp(self.decorate(self.item), self.decorate(other.item)) return x def decorate(self, value): # expensive magic goes in here... sorted(items, key=SmartComparator) I think the second version is more promising, since it avoids a linear search for ties. You will need to check the documentation to see whether sorting relies on __cmp__ or rich comparisons (__gt__, __lt__, __eq__, etc.). If you need any help, don't hesitate to ask. P.S. I just discovered sympy recently, it is awesome. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 09/19/2012 02:27 PM, Andrew Tritt wrote: > Hello, > > I am new to python, and I was experimenting with the round function, and > came across what appears to be a bug in floating point rounding. I am > guessing there is a valid explanation for it. Welcome to the Python tutor; hope you enjoy learning and using python. Not a bug, and not specific to Python. And not new - many threads already discuss this. > > When I round the floating points 10.6[0-9]5 to two decimal places, it > rounds as expected for 6 of the 10, but not for the other 4. When I try the > same for 10.7[0-9]5, I experience the same problem, but for 5 of the 10 > possibilties, and not for the analogous floats. > > Also, python storing the numbers as they are represented at the prompt. > i.e. 10.665 is stored as 10.665, not something like 10.66501 or > 10.664. > > Can anyone explain to me what's happening? Yep, Python does not store the number 10.065 in any of the forms you appear to expect. it instead converts it to binary floating point, and stores the nearest value that can represent. Sometimes such a value will convert back to the decimal value you started with, sometimes not. This is not a new problem - it was highlighted in the textbook i used for Fortran in 1967. But it was more or less made permanent by the Intel 8087 chip, which did binary floating point, and did not do decimal floating point. The IEEE committee then standardized pretty much on what was already done, and that's what's on all the Intel and AMD chips we see now. Generally, the way to avoid the problem is to mask it while displaying. Use some form of formatting to represent the precision you expect. See the article Oscar pointed you to: http://docs.python.org/tutorial/floatingpoint.html -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
Chris Smith wrote: > I'm wondering if anyone has seen or knows of a good way to do a lazily > decorated sort. I was reading about how good the DSU (decorate, sort, > undecorate) approach is but the problem that we are running into in > SymPy is that we want to get by with a fast hash sort if possible, and > only decorate to break ties *if necessary*. It's a pity to decorate > with an expensive function if you don't need it but I don't know how > to only decorate when there are ties. Do you have any ideas how to do > the following better: Here's an implementation that uses the key argument that is supported by list.sort() and the built-in sorted(). A generator function (keys(value)) is used to calculate the partial keys as necessary. import time import random from contextlib import contextmanager from functools import total_ordering try: from itertools import izip except ImportError: # python 3 izip = zip def make_key(keys): @total_ordering class Key(object): def __init__(self, value): self._keys = keys(value) self._cached = [] def keys(self): for k in self._cached: yield k for k in self._keys: self._cached.append(k) yield k def __eq__(self, other): return all(a == b for a, b in izip(self.keys(), other.keys())) def __lt__(self, other): for a, b in izip(self.keys(), other.keys()): if a == b: pass else: return a < b return False return Key @contextmanager def bench(description): print("starting...") start = time.time() yield stop = time.time() print(description.format(stop - start)) if __name__ == "__main__": N = 10 def keys(value): """user defined lazy key""" yield value time.sleep(.1) yield random.random() data = list(range(N)) + [N, N] wanted = list(data) random.shuffle(data) with bench("lazy key: {:.1f}s"): got = sorted(data, key=make_key(keys)) assert got == wanted with bench("eager key: {:.1f}s"): got = sorted(data, key=lambda value: tuple(keys(value))) assert got == wanted ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to save text or dat file using python
On 09/20/2012 12:14 PM, Preeti Gaikwad wrote: > Hello I am new user of python pls let me know how to save dat or txt file > using python? what is the basic cmd for this? thanks a lot in advance > > Have you written any code that READs files? Check out the open() function, in particular the "w" or "wb" mode. Then use the method write(), on the file object returned by open(). -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assembly language and boot loader
On 28/09/12 21:59, Oscar Benjamin wrote: On 23 September 2012 05:46, Fit Wii wrote: Is there any IDE or Python interpreter that can show the assembly language generated by each line of python code? Is there any popular boot loader written in Python (plus some assembly code)? That's two unjustified assumptions in two questions. Boot loaders need to be small and fast, which is why they are written in Forth or C. There aren't ANY boot loaders written in Python, let alone popular ones. It's quite silly to be even thinking about writing a boot loader in Python -- common hardware may require the boot loader to fit in just 64K of memory. Regular Python requires megabytes of memory just to start itself. I suppose it is just barely possible that TinyPy or Pycorn could be used, but I doubt it anyone has. Python doesn't generate assembly language code. Pardon me, but I'm pretty sure that PyPy's JIT compiler will. Well, reasonably sure. Slightly confident. I'm guessing. :) However, I expect it only exists at runtime and you won't be able to get to it. Besides, it will be heavily optimized and ugly as sin. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 28/09/12 22:15, Mark Lawrence wrote: The Python round function is itself problematic. The idea of deprecating it is currently being discussed on Python ideas. This quote from Calvin Spealman is typical "Also, I'd be completely in support of dropping round() and agree it gets misused and leads to too much confusion. We should promote the right ways, and sometimes to show the right path you need to lock another door and throw away the key.". Isn't that the same Calvin Spealman who wrote the blog post spreading FUD that Python was at risk of dying because, well, frankly because he was utterly ignorant of just how much Python code is written in the places where he thought no Python was written? I'm not impressed. He sprouts off about how you can't use Python on mobile devices, when you can. What makes you think his opinions on breaking working code just because he thinks he knows the "right ways" are any less ignorant? Deprecating and dropping features causes pain to developers who are already using them correctly. There is strong opposition on deprecating round. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick question
On 28/09/12 19:03, Mark Lawrence wrote: On 28/09/2012 06:18, jh wrote: [snip] The subtotal of your items is: 26010.8502 The total amount of your items plus tax is: 27,571.50 My question here is, why does my subtotal have so many decimals when I never went above 2 in my input? Thanks in advance, J Brett Ritter has already answered your question, but a web search would have found the answer a lot faster, as this has been asked umpteen times on Python lists alone. And I'm sure it will be asked a bazillion more times :/ Also note that if you'd have formatted the output in the same way that you did for the total you'd never have noticed. That's not strictly true, and by that I mean it's completely wrong :) String formatting can only hide so much. There are many ways to stumble over binary floating point issues. For example, this is using Python 3.2 which tries really hard to print a sensible float approximation for you: py> d = 1/10 py> numbers = [d]*10 py> print(numbers) [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] Here we have 0.1 repeated ten times. So if we add them, we ought to get one, right? py> total = sum(numbers) py> total == 1 False What's going on? If we look at the total, we see that it adds up to slightly *less* than the expected one: py> print(total) 0. But if we print 0.1 in full precision, we see that it is slightly *greater* that 0.1 in decimal: py> print("%.17f" % d) 0.10001 So that's TWO nasty surprises (so far) with binary floating point numbers: * not all "nice" decimal numbers, like 0.1, can be stored exactly in a binary float; * and when you add ten numbers slightly greater than 0.1, the result can actually be less than 1.0 !!! Welcome to binary floating point hell. And this has nothing to do with Python, the same thing happens in *any* language with binary floats. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Netiquette
On Fri, 28 Sep 2012, Bod Soutar wrote: On Sep 28, 2012 4:47 AM, "Dwight Hutto" wrote: > Yeah, all up in my fucking cranium with nothing but me and God to hold > on to one another. > > -- > Best Regards, > David Hutto > CEO: http://www.hitwebdevelopment.com Probably not a good idea to advertise that your the CEO of hitwebdevelopment.com if your gonna post like that. Bodsda That's OK, if you don't like that sort of attitude you're obviously not in his target market (the one that enjoys was it 60MB GIF files, and background music). -W___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 28/09/2012 13:37, Steven D'Aprano wrote: On 28/09/12 22:15, Mark Lawrence wrote: Deprecating and dropping features causes pain to developers who are already using them correctly. There is strong opposition on deprecating round. And there is strong support for deprecating round. Personally I'm staying out of the blood bath as I've never used it :) -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list all links with certain extension in an html file
On Fri, Sep 28, 2012 at 1:10 PM, wrote: > Date: Sun, 16 Sep 2012 12:50:09 +0530 > From: Santosh Kumar > To: tutor@python.org > Subject: [Tutor] list all links with certain extension in an html file > python > Message-ID: > < > cae7maqa53x8pav96q2ka0vajhnjtrz_rgzcmh_cbsaqdiz5...@mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > I want to extract (no I don't want to download) all links that end in > a certain extension. > > http://foo.bar/part1.css > "> > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > > Also I don't want to use external libraries. I am asking for: which > libraries and functions should I use? > > > do you mean, you want to parse the file and the URL of those css files, then parse the file, there are many parsing options http://lxml.de/parsing.html you don't have to use external libraries either, you may use http://docs.python.org/library/htmlparser.html or regular expressions or may be I did't understood what you really want to do. Br - Hussain ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to print array without adding newline
On Sep 6, 2012, at 9:49 AM, vi...@thepenguin.org wrote: > Thank you for your reply. I understand that it is odd, but my program is > being called from a hubot and returning data to it as well. I have figured > out how to make the changes to get it to output the correct data in the > correct format, but now I am getting a "Premature end of script headers" > error. I have the correct #! line and the output from the command line shows > no errors that would be interfering. Is there a way to make sure it is > showing me all the errors? To increase error logging? > -- > !/usr/bin/env python > import cloudfiles > import random > import sys > import array > > conn = cloudfiles.get_connection('username', 'key') > > containers = conn.get_all_containers() > i=0 > print "Content-type: text/html"; > wholelist=containers[0].list_objects() > random.shuffle(wholelist) > newlist=[] > #newlist=wholelist[:] > try: > #print sys.argv[1] >if "=" in sys.argv[1]: sys.argv[1] = sys.argv[1].rstrip("=") > #print sys.argv[1] >del wholelist[int(sys.argv[1]):] >while i < int(sys.argv[1]): >newlist.append("http://example.com/"+wholelist[i].rstrip()) >i = i+1 > except IndexError, e: >del newlist[5] > except Exception, err: >print 'Caught an exception' > print newlist, > --- > Vicki > Python doesn't know what to do with: !/usr/bin/env python try #!usr/bin/env python so python doesn't see it, only the the shell. -Bill ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list all links with certain extension in an html file python
Santosh Kumar, 16.09.2012 09:20: > I want to extract (no I don't want to download) all links that end in > a certain extension. > > Suppose there is a webpage, and in the head of that webpage there are > 4 different CSS files linked to external server. Let the head look > like this: > > http://foo.bar/part1.css";> > http://foo.bar/part2.css";> > http://foo.bar/part3.css";> > http://foo.bar/part4.css";> > > Please note that I don't want to download those CSS, instead I want > something like this (to stdout): > > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > http://foo.bar/part1.css > > Also I don't want to use external libraries. That's too bad because lxml.html would make this really easy. See the iterlinks() method here: http://lxml.de/lxmlhtml.html#working-with-links Note this this also handles links in embedded CSS code etc., although you might not be interested in that, if the example above is representative for your task. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten <__pete...@web.de> wrote: > > def make_key(keys): > @total_ordering > class Key(object): > def __init__(self, value): > self._keys = keys(value) > self._cached = [] Using a generator/iterator to pump the key values into a cache is a great idea. But I think it would generally be nicer to let "keys" be a sequence of functions. Then define the generator in make_key() before you define the class: def make_key(keys): def _keys(value): for key in keys: yield key(value) @total_ordering class Key(object): def __init__(self, value): self._keys = _keys(value) self._cached = [] Also, as far as I can see in the code, implementing "total_ordering" is unnecessary for sorting. One only needs to implement __lt__. It's used by binarysort() to test the pivot via the IFLT/ISLT macros: http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 > def __lt__(self, other): > for a, b in izip(self.keys(), other.keys()): > if a == b: > pass > else: > return a < b > return False Or test for "!=": def __lt__(self, other): for a, b in izip(self.keys(), other.keys()): if a != b: return a < b return False ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to save text or dat file using python
Preeti Gaikwad wrote: > Hello I am new user of python pls let me know how to save dat or txt file > using python? what is the basic cmd for this? thanks a lot in advance Try reading: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python for Absolute Beginners
On 9/27/2012 9:42 AM Debbie Snowdon said... Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access the Companion Guide. Do I need it? Do I have to purchase it? How do I get it? The site he sends me to is very confusing. I'd ask your instructor or look in the book to see if the author has provided contact info. HTH. Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Translate PHP to Python
As Mark pointed out - a better subject would help. I have changed it this time. On 9/17/2012 3:21 PM, Fation Beqirllari wrote: I have a php code and I want to translate it to python..Can you help me > please,or show me how to do it ? In what context do you run the PHP? A web server responding to a request, or standalone? If it is web server responding to a request then you might consider using a Python based web framework. Why do you want to translate it to Python? Which version of Python? How much expertise do you have in Python coding? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python new window
On 11/09/12 22:18, zack dunphey wrote: I have used python a lot at school and am relatively good with it. > I just tried to get it on my mac and i try to open a "new window" OK, Python doesn't have any windows so you must be talking about some kind of add-on tool - like IDLE maybe? If so please be specific about which tool, which python version, which OS (MacOSX here I assume) and exactly what you did - which menu, command key etc you used. > I have been able to get into a "new window" through programs > i saved on a jump drive at school and brought home Again using which OS, which python version, which tool? but every time i try to do anything from that window it freezes. Which Window? i tried re downloading it but that didn't help. What exactly are you downloading? How are you installing it? And how are you running it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Just flushed the moderation queue
I'm just back from 2 weeks vacation and catching up on mail etc. I flushed the python tutor mail queue earlier hence the proliferation of messages some of which may be duplicates of stuff already seen... enjoy, -- Alan G List moderator. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python new window
On Tue, Sep 11, 2012 at 10:18 PM, zack dunphey wrote: > I have used python a lot at school and am relatively good with it. I just > tried to get it on my mac and i try to open a "new window" and every time I > do it freezes and i have to either do a forced quit or unplug the whole > computer. I have been able to get into a "new window" through programs i > saved on a jump drive at school and brought home but every time i try to do > anything from that window it freezes. i tried re downloading it but that > didn't help. > can some one please help me > zack dunphey > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi Zac, Mac OS X comes with python already installed - just open a 'Terminal' and type python. In a Windows environment you have to install Python (or perhaps run it from a flash drive) but in Mac OS X Python comes as part of the system so you don't need to mess around downloading it and trying to install it. Hope that helps, Tahir ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python for Absolute Beginners
Which edition do you have? My copy mentions nothing about a companion guide, so my guess is that you don't need it. That said, my copy also doesn't send me to any sites for the exercises. Everything I need is right in the book. On Sep 28, 2012 7:30 AM, "Debbie Snowdon" wrote: > ** > Help! I'm into Chapter 2 in the Book by Michael Dawson - I cannot access > the Companion Guide. Do I need it? Do I have to purchase it? How do I get > it? The site he sends me to is very confusing. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
eryksun wrote: > On Fri, Sep 28, 2012 at 8:17 AM, Peter Otten <__pete...@web.de> wrote: >> >> def make_key(keys): >> @total_ordering >> class Key(object): >> def __init__(self, value): >> self._keys = keys(value) >> self._cached = [] > > > Using a generator/iterator to pump the key values into a cache is a > great idea. But I think it would generally be nicer to let "keys" be a > sequence of functions. Then define the generator in make_key() before > you define the class: I should have mentioned that make_key() may be used as a decorator. So it is @make_key def key(value): yield value yield f(value) yield value.attrib items.sorted(key=key) against (assuming the signature make_key(*keyfuncs)) items.sort(key=make_key( lambda value: value, f, operator.itemgetter("attrib")) ) I think the first version looks a bit cleaner, but that's a matter of taste. > Also, as far as I can see in the code, implementing "total_ordering" > is unnecessary for sorting. One only needs to implement __lt__. It's > used by binarysort() to test the pivot via the IFLT/ISLT macros: > > http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 I smell danger. I really don't like having a class lying around that partially implements ordering and may fail where you least expect it. >> if a == b: >> pass >> else: >> return a < b > Or test for "!=": Yes, that was odd indeed. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Lotka-Volterra Model Simulation Questions
Hello folks, I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey relation) simulator. The program basically will basically have a menu that takes user input, collect data, and then create a graph. Currently i've been working on the simulator section; I can't seem to get the lists right. I've assigned the following variables and parameters to the model for the program: x represents prey population y represents predator population dy/dt and dx/dt represents growth rate of the two populations over time t represents time a is the growth rate of prey b is the rate at which predators kill prey g is the death rate of predators d is the rate at which the predators population increases by consuming prey The equation: dx/dt = x(a-by) dy/dt = -y(g-dx) The code I have for this section is: def deltaX(a,b,x,y): dx = x*(a-b*y) def deltaY(g,d,x,y): dy = -y*(g-d*x) The simulation function is where I am having trouble. For the simulation function, I need to ask the user for the number of runs and then save it in a variable, create a list for prey and predator. For each run, i need to calculate the increment of change in prey and predator populations by calling the deltaX and deltaY functions, then save these in a variable, and then update the population information. The newly calculated populations then need to be added to the existing lists. After this is completed, a function for the graph is called. The following is my current simulation function: def simulation(): a=eval(input("Growth rate of prey:")) b=eval(input("Rate at which predators eat prey:")) g=eval(input("Death rate of predators:")) d=eval(input("Rate at which predators increase by consuming prey:")) x=eval(input("Current prey population:")) y=eval(input("Current predator population:")) deltaX(a,b,x,y) deltaY(g,d,x,y) n=eval(input("Number of runs:") r = 0 count=0 yList = [0] while r <= n: r = r + 1 count = count + 1 yList.append(dx + dx) zList= [0] while r <= n: r = r + 1 count = count +1 zList.append(dy + dy) It seems terribly wrong. The following is my graph function: def drawCurve(yList,zList,n): x = pylab.arange(n) pylab.title("Foxes and Rabbits") pylab.ylabel("Number of predator (Foxes)") pylab.xlabel("\nNumber of prey (Rabbits)") pylab.plot(x, yList, 'b') pylab.plot(x, zList, 'r') pylab.legend(('Rabbits','Foxes'),loc='upper left') pylab.show() The issue i'm having is the logic in the lists. How can I create the simulation function using lists and make it perform the expected task of creating a graph? I can't seem to get the logic right. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lazily decorated sort
On Fri, Sep 28, 2012 at 3:34 PM, Peter Otten <__pete...@web.de> wrote: > >> Also, as far as I can see in the code, implementing "total_ordering" >> is unnecessary for sorting. One only needs to implement __lt__. It's >> used by binarysort() to test the pivot via the IFLT/ISLT macros: >> >> http://hg.python.org/cpython/file/70274d53c1dd/Objects/listobject.c#l1023 > > I smell danger. I really don't like having a class lying around that > partially implements ordering and may fail where you least expect it. I don't know; they're just utility objects used for sorting, which only cares about __lt__. On the other hand, Python 3 enforces a sanity check if you implement __eq__ without __hash__. So now you have objects that can't be used in sets or as dict keys. Not that this matters. ;) Anyway, it's not hurting. I just thought I'd make the suggestion to spare you the [small] effort of implementing __eq__ on something like this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
Jim Apto wrote > Hello folks, > > I'm relatively new to python, and was asked to program a lotka-volterra model > (predator and prey relation) > simulator. The program basically will basically have a menu that takes user > input, collect data, and then > create a graph. Currently i've been working on the simulator section; I > can't seem to get the lists right. > I've assigned the following variables and parameters to the model for the > program: > > x represents prey population > y represents predator population > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey > b is the rate at which predators kill prey > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > dx = x*(a-b*y) > > def deltaY(g,d,x,y): > dy = -y*(g-d*x) > > The simulation function is where I am having trouble. > > For the simulation function, I need to ask the user for the number of runs > and then save it in a variable, > create a list for prey and predator. For each run, i need to calculate the > increment of change in prey and > predator populations by calling the deltaX and deltaY functions, then save > these in a variable, and then update > the population information. The newly calculated populations then need to be > added to the existing lists. > After this is completed, a function for the graph is called. > > The following is my current simulation function: > You posted as HTML/rich text while I recommend posting as plain text. HTML/rich text can cause the text spacing to be wrong. My comments may not apply because of incorrect indention levels. > def simulation(): > a=eval(input("Growth rate of prey:")) Usage of eval is dangerous and not recommended except for advanced users. For your purposes, you can replace eval() with either int() or float() as appropriate. > b=eval(input("Rate at which predators eat prey:")) > g=eval(input("Death rate of predators:")) > d=eval(input("Rate at which predators increase by consuming prey:")) > x=eval(input("Current prey population:")) > y=eval(input("Current predator population:")) return a,b,g,d,x,y # need to return the data from simulation() Where do you ever call simulation? > > deltaX(a,b,x,y) > deltaY(g,d,x,y) Simulation does not return anything so this should either cause a NameError or use the incorrect values. > > n=eval(input("Number of runs:") > r = 0 Why did this change indentation levels? > count=0 > yList = [0] > while r <= n: > r = r + 1 > count = count + 1 > yList.append(dx + dx) What is the point of appending dx*2? What is the point of the loop appending the same things over and over? I suspect simulation should be called in between Not to mention that, this loop can be simplified by changing it to a for loop. for _ in xrange(n): yList.append(dx + dx) Or even converted into a list comprehension. yList.extend( [ dx + dx for _ in xrange(n) ] ) count += len(yList - 1) # -1 for the original [0] Shouldn't simulation be called or at least change the values of dx? > > zList= [0] > while r <= n: > r = r + 1 > count = count +1 > zList.append(dy + dy) > > It seems terribly wrong. The following is my graph function: > > def drawCurve(yList,zList,n): > x = pylab.arange(n) > pylab.title("Foxes and Rabbits") > pylab.ylabel("Number of predator (Foxes)") > pylab.xlabel("\nNumber of prey (Rabbits)") > pylab.plot(x, yList, 'b') > pylab.plot(x, zList, 'r') > pylab.legend(('Rabbits','Foxes'),loc='upper left') > pylab.show() > > The issue i'm having is the logic in the lists. How can I create the > simulation function using lists and make > it perform the expected task of creating a graph? I can't seem to get the > logic right. The lack of complete code (or issues with indentation) make it difficult to give you advice on how to solve it. If you can post your code in plain text (or attach it) you will get better help. It would also help if you can create a small sample that has the minimum amount of (functioning even if logically incorrect) code that displays the problem you are facing. This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
On Fri, 28 Sep 2012, Jim Apto wrote: Hello folks, I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey relation) simulator. The program basically will basically have a menu that takes user input, collect data, and then create a graph. Currently i've been working on the simulator section; I can't seem to get the lists right. I've assigned the following variables and parameters to the model for the program: I don't know anything about the Lotka-Volterra model, but I've definitely got some recommendation x represents prey population y represents predator population dy/dt and dx/dt represents growth rate of the two populations over time t represents time a is the growth rate of prey b is the rate at which predators kill prey g is the death rate of predators d is the rate at which the predators population increases by consuming prey The equation: dx/dt = x(a-by) dy/dt = -y(g-dx) The code I have for this section is: def deltaX(a,b,x,y): dx = x*(a-b*y) def deltaY(g,d,x,y): dy = -y*(g-d*x) The simulation function is where I am having trouble. For the simulation function, I need to ask the user for the number of runs and then save it in a variable, create a list for prey and predator. For each run, i need to calculate the increment of change in prey and predator populations by calling the deltaX and deltaY functions, then save these in a variable, and then update the population information. The newly calculated populations then need to be added to the existing lists. After this is completed, a function for the graph is called. The following is my current simulation function: def simulation(): a=eval(input("Growth rate of prey:")) b=eval(input("Rate at which predators eat prey:")) g=eval(input("Death rate of predators:")) d=eval(input("Rate at which predators increase by consuming prey:")) x=eval(input("Current prey population:")) y=eval(input("Current predator population:")) Woah! Stop that right now - eval is an *incredibly* dangerous function. If you want to convert these numbers to integer or float, there's the int() and float() function. Additionally, single letter variables are really horrible. You could do: prey_growth_rate = float(input("Growth rate of prey: ")) predator_consumption_rate = #your code here predator_death_rate = ... predator_growth_rate = ... initial_prey_population = ... initial_predator_population = ... deltaX(a,b,x,y) deltaY(g,d,x,y) I don't see where you defined deltaX or deltaY... n=eval(input("Number of runs:") r = 0 count=0 yList = [0] while r <= n: r = r + 1 count = count + 1 yList.append(dx + dx) zList= [0] while r <= n: r = r + 1 count = count +1 zList.append(dy + dy) It seems terribly wrong. The following is my graph function: def drawCurve(yList,zList,n): x = pylab.arange(n) pylab.title("Foxes and Rabbits") pylab.ylabel("Number of predator (Foxes)") pylab.xlabel("\nNumber of prey (Rabbits)") pylab.plot(x, yList, 'b') pylab.plot(x, zList, 'r') pylab.legend(('Rabbits','Foxes'),loc='upper left') pylab.show() The issue i'm having is the logic in the lists. How can I create the simulation function using lists and make it perform the expected task of creating a graph? I can't seem to get the logic right. Posting an image of what you expect, and what you got instead to imgur or some other free hosting site would be a good thing to do. When asking a question you should always post what you wanted to happen, and what happened instead. HTH, Wayne___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On Fri, Sep 28, 2012 at 9:17 AM, Mark Lawrence wrote: > On 28/09/2012 13:37, Steven D'Aprano wrote: > >> Deprecating and dropping features causes pain to developers who are >> already using them correctly. There is strong opposition on deprecating >> round. > > And there is strong support for deprecating round. Personally I'm staying > out of the blood bath as I've never used it :) That would be an odd back-step since Python 3 generalized the built-in: >>> class Test: ... def __round__(self, ndigits=None): ... return 1 ... >>> round(Test()) 1 Also, float, Decimal, and Fraction in Python 3 return an int when the ndigits argument is omitted. For example, float rounds using the math lib's round function, then rounds that to even, and returns PyLong_FromDouble. Is the discussion just about removing the ndigits aspect but keeping the round-to-int aspect? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On Fri, Sep 28, 2012 at 8:37 AM, Steven D'Aprano wrote: > On 28/09/12 22:15, Mark Lawrence wrote: > >> The Python round function is itself problematic. The idea of deprecating >> it is currently being discussed on Python ideas. This quote from Calvin >> Spealman is typical "Also, I'd be completely in support of dropping >> round() >> and agree it gets misused and leads to too much confusion. We should >> promote the right ways, and sometimes to show the right path you need to >> lock another door and throw away the key.". > > > Isn't that the same Calvin Spealman who wrote the blog post spreading FUD > that > Python was at risk of dying because, well, frankly because he was utterly > ignorant of just how much Python code is written in the places where he > thought no Python was written? > > I'm not impressed. He sprouts off about how you can't use Python on mobile > devices, when you can. What makes you think his opinions on breaking > working code just because he thinks he knows the "right ways" are any less > ignorant? I don't think the newbie mailing list is the right place to show that kind of hostility, if indeed there is a right place. -- Devin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
On 28 September 2012 21:32, Jim Apto wrote: > Hello folks, > > I'm relatively new to python, and was asked to program a lotka-volterra > model (predator and prey relation) simulator. The program basically will > basically have a menu that takes user input, collect data, and then create > a graph. Currently i've been working on the simulator section; I can't > seem to get the lists right. I've assigned the following variables and > parameters to the model for the program: > > x represents prey population > y represents predator population > dy/dt and dx/dt represents growth rate of the two populations over time > t represents time > > a is the growth rate of prey > b is the rate at which predators kill prey > g is the death rate of predators > d is the rate at which the predators population increases by consuming prey > > The equation: > dx/dt = x(a-by) > dy/dt = -y(g-dx) > > The code I have for this section is: > def deltaX(a,b,x,y): > dx = x*(a-b*y) > > def deltaY(g,d,x,y): > dy = -y*(g-d*x) > The normal way to program an ODE solver is to define a function that takes a vector input X and returns a vector dX/dt. The idea is that rather than keeping a separate state for x and y you keep a combined state [x, y]. This makes sense since the state of your system at any time is defined by both values. Keeping that in mind I would write a function like def derivative(Z): x, y = Z dxdt = ... dydt = ... dZdt = [dxdt, dydt] return dZdt This function uses lists of numbers to represent the state vector. You can then plug this into a function that uses a particular ODE solving algorithm: def euler(f, Z1, dt): dZdt = f(Z1) Z2 = [] for i in range(len(Z1)): Z2.append(Z1[i] + dt * dZdt[i]) return Z2 Or a shorter version: def euler(f, Z1, dt): return [z + dt * dz for z, dz in zip(Z, f(Z))] You then get the new state by plugging the old state into the euler function repeatedly, e.g.: dt = .001 Z0 = [0.5, 0.5] # Initial condition Z1 = euler(derivative, Z0, dt) Z2 = euler(derivative, Z1, dt) ... Once you can get all the simulation values you will be in a position to think about how to rearrange the lists so that you can plot them. By the way, this sort of thing is usually done with numpy (that makes a few of these things a bit easier). Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lotka-Volterra Model Simulation Questions
On 28/09/12 21:32, Jim Apto wrote: I'm relatively new to python, and was asked to program a lotka-volterra model (predator and prey relation) simulator. No idea what that means in practice but commenting purely on the code provided... x represents prey population y represents predator population so use names that say so, like preyPop and predatorPop Its only a few extra letters typing but makes things much more readable. dy/dt and dx/dt represents growth rate of the two populations over time t represents time a is the growth rate of prey so call it preyGrowth? b is the rate at which predators kill prey or killRate? you get the idea... g is the death rate of predators d is the rate at which the predators population increases by consuming prey The equation: dx/dt = x(a-by) dy/dt = -y(g-dx) The code I have for this section is: def deltaX(a,b,x,y): dx = x*(a-b*y) Normally you define a function such that it returns a value. Here you simply define a local variable(dx), assign a value then throw it way when the function finishes. You probably want: def deltaX(a,b,x,y): return x*(a-b*y) def deltaY(g,d,x,y): dy = -y*(g-d*x) same here The simulation function is where I am having trouble. possibly because of some of the things above? For the simulation function, I need to ask the user for the number of runs and then save it in a variable, create a list for prey and predator. For each run, i need to calculate the increment of change in prey and predator populations by calling the deltaX and deltaY functions, then save these in a variable, and then update the population information. > The newly calculated populations then need to be added to the existing lists. After this is completed, a function for the graph is called. So three basic blocks of code required? Is your function structured like that? Which blocks work? Which ones don't? Can you test (eg print) each block separately? Hint: Can each block be a function? The following is my current simulation function: def simulation(): a=eval(input("Growth rate of prey:")) b=eval(input("Rate at which predators eat prey:")) g=eval(input("Death rate of predators:")) d=eval(input("Rate at which predators increase by consuming prey:")) x=eval(input("Current prey population:")) y=eval(input("Current predator population:")) Don't use eval convert types directly using int() or float() Convert the above to a standalone function getSimulationData() or somesuch that returns the validated and converted input values. Test it. deltaX(a,b,x,y) deltaY(g,d,x,y) Here are the calls with no return values and so have no effect. They are effectively wasted space. You need something like dx = deltaX(a,b,x,y) dy = deltaY(g,d,x,y) after adding return statements as described above. n=eval(input("Number of runs:") r = 0 The indentation suggests you are missing a loop structure somewhere? count=0 yList = [0] while r <= n: r = r + 1 count = count + 1 yList.append(dx + dx) dx does not exist as you wrote it, you need the changes above... But even then you are adding the same value (2dx) each time, is that right? zList= [0] while r <= n: r = r + 1 count = count +1 zList.append(dy + dy) Same applies for dy. It seems terribly wrong. Yep, I'm pretty sure it is wrong. Also I'd try putting it into a separate function, populateData() maybe? The simulate looks like: def simulate: a,b,g,d,x,y = getSimulationData() xList,YList = populateData(a,b,g,d,x,y) drawCurve(yList,xList) The following is my graph function: def drawCurve(yList,zList,n): x = pylab.arange(n) pylab.title("Foxes and Rabbits") pylab.ylabel("Number of predator (Foxes)") pylab.xlabel("\nNumber of prey (Rabbits)") pylab.plot(x, yList, 'b') pylab.plot(x, zList, 'r') pylab.legend(('Rabbits','Foxes'),loc='upper left') pylab.show() I don't use pyLab so will assume that is all OK... The issue i'm having is the logic in the lists. The biggest issue is the naming and location of your variables and how you assign values to them (via returns from functions). Fix that first and things will start to improve. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 28/09/2012 22:07, eryksun wrote: On Fri, Sep 28, 2012 at 9:17 AM, Mark Lawrence wrote: On 28/09/2012 13:37, Steven D'Aprano wrote: Deprecating and dropping features causes pain to developers who are already using them correctly. There is strong opposition on deprecating round. And there is strong support for deprecating round. Personally I'm staying out of the blood bath as I've never used it :) That would be an odd back-step since Python 3 generalized the built-in: >>> class Test: ... def __round__(self, ndigits=None): ... return 1 ... >>> round(Test()) 1 Also, float, Decimal, and Fraction in Python 3 return an int when the ndigits argument is omitted. For example, float rounds using the math lib's round function, then rounds that to even, and returns PyLong_FromDouble. Is the discussion just about removing the ndigits aspect but keeping the round-to-int aspect? I don't have figures (ouch :) but some people appear to support complete deprecation, some leaving the status quo and some removing the ndigits aspect as you have asked. Also remember that the idea is only being floated (double ouch:) on Python ideas so anything could happen. Don't watch this space!!! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Cheers. Mark Lawrence. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 28/09/12 13:15, Mark Lawrence wrote: from Calvin Spealman is typical "Also, I'd be completely in support of dropping round() and agree it gets misused and leads to too much confusion. We should promote the right ways, and sometimes to show the right path you need to lock another door and throw away the key.". As a matter of interest what is the "right path" that is being proposed? If it takes much more than 7 keypresses then I suspect it will be opposed! (I'm too lazy to look up the thread myself! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Translate PHP to Python
On 9/28/2012 12:52 PM, Fation Beqirllari wrote: This php is for map cache,it reads cache file created,but im creating all the web server to python because it works faster..I use this for openlayers web server. I run Python 3.2.if you want to help me..i will send te php code..thank you! Thanks for the information. Please always reply-all so a copy goes to the list. I will cc this for that purpose. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 29/09/12 11:30, Alan Gauld wrote: On 28/09/12 13:15, Mark Lawrence wrote: from Calvin Spealman is typical "Also, I'd be completely in support of dropping round() and agree it gets misused and leads to too much confusion. We should promote the right ways, and sometimes to show the right path you need to lock another door and throw away the key.". As a matter of interest what is the "right path" that is being proposed? If it takes much more than 7 keypresses then I suspect it will be opposed! (I'm too lazy to look up the thread myself! :-) It is already opposed because it breaks existing, working code unnecessarily. The replacements suggested are: - use Decimal values, and round them instead; - use string formatting Neither suggestion has really thought things through clearly. The first has identified the problem correctly -- it is *binary floats*, not round, which causes the problem, but to round a Decimal you need the round built-in (or at least a replacement): py> from decimal import Decimal as D py> x = D('2.123456') py> x.round Traceback (most recent call last): File "", line 1, in AttributeError: 'Decimal' object has no attribute 'round' py> round(x, 3) Decimal('2.123') The second is, well, poorly thought out. Here is an example of the sort of thing where round can give funny results. You expect that on half-way cases, it should round to the nearest EVEN number: # as expected py> round(1.125, 2) 1.12 py> round(1.135, 2) 1.14 # but unexpected py> round(2.675, 2) 2.67 Why? Because 2.675 is not actually a half-way case, it is actually a binary float a tiny bit under the decimal 2.675: py> print("%.17f" % 2.675) 2.67482 Fair enough. So let's try the recommended solution: py> "%.2f" % 2.675 '2.67' Wait, that gives the same result as rounding. So how is this better? -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floating point rounding inconsistency
On 29/09/12 07:27, Devin Jeanpierre wrote: On Fri, Sep 28, 2012 at 8:37 AM, Steven D'Aprano wrote: [...] I'm not impressed. He sprouts off about how you can't use Python on mobile devices, when you can. What makes you think his opinions on breaking working code just because he thinks he knows the "right ways" are any less ignorant? I don't think the newbie mailing list is the right place to show that kind of hostility, if indeed there is a right place. Did I break some unwritten law? "Thou shall not puncture newbie's illusion that all Python users and developers are part of one great big happy family where everyone agrees with everyone else all the time." I think that Calvin's blog post was FUD. It may have been genuinely held, and not intentionally FUD, but the comments on his blog demonstrate that he was out of touch of the state of Python in at least one of the areas he was most concerned about. I think his argument against round(x, n) is equally ignorant and wrong-headed. I'm sorry that you consider this frank expression of my opinion to be hostility. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor