Re: [Tutor] Find and test a device by MAC address
Quick and dirty: As root: from scapy import * arping(192.168.0.1/24) # or whatever fits to your network and then filter the answers; or build your own arp packets with ARP(). -- Freedom, Freedom, Freedom, Oi! -- Zoidberg Der GMX SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen! Ideal für Modem und ISDN: http://www.gmx.net/de/go/smartsurfer ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to know if a file exists
Hi, import os if os.path.exists('/path/to/file'): # File exists else: # File doesn't exist It works for files as well as directories. Regards, Vikram U Shenoy ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Embedding strings in a python script
Tony Cappellini wrote: What I'd like to know, is there a way I can embed/endcode the cvs string above in the python script, so that when that script is modified and checked into cvs, that the cvs header string above will not be modified by cvs? Try using \x24 instead of $: cvs_header=''' ### # # \x24Header:\x24 # # \x24Revision:\x24 # \x24Author:\x24 # \x24Date:\x24 # Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Any Good book for python
Hi Folks, I am new in Python area and want to know Python concepts with more deatils. Please suggest some good books on python. Thanks in Advance -Deepak __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Patches
Hello. I need to access SMTP with SSL and found this patch: https://sourceforge.net/tracker/?func=detailatid=305470aid=1567274group_id=5470 But, I cannot find anything with Google or in the Python documentation about how to apply a patch. Ok, one slight modification. I did find something: 5.2 How do I apply a patch? For the general case, to apply a patch go to the directory that the patch was created from (usually /dist/src/) and run: patch -p0 name_of_the_patch.diff The -p option specifies the number of directory separators (/ in the case of UNIX) to remove from the paths of the files in the patch. -p0 leaves the paths alone. from http://www.python.org/dev/faq/#how-do-i-apply-a-patch But, that didn't tell me anything. I am using Windows, and tried both to enter that command in the CMD-window, as well as in the Python-IDLE. No avail. Is patch a program I have to download somewhere? Or can only patches be used in Linux? Thanks in advance. -- This email has been scanned for viruses spam by Domenebutikken - www.domenebutikken.no Denne e-posten er sjekket for virus spam av Domenebutikken - www.domenebutikken.no ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any Good book for python
Python in a nutshell is a good one. Also Python docs are the all time favorite. On 1/4/07, deepak shingan [EMAIL PROTECTED] wrote: Hi Folks, I am new in Python area and want to know Python concepts with more deatils. Please suggest some good books on python. Thanks in Advance -Deepak ** __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ 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] Patches
Øyvind wrote: Hello. I need to access SMTP with SSL and found this patch: https://sourceforge.net/tracker/?func=detailatid=305470aid=1567274group_id=5470 But, I cannot find anything with Google or in the Python documentation about how to apply a patch. Is patch a program I have to download somewhere? Or can only patches be used in Linux? There is a patch program for windows here: http://gnuwin32.sourceforge.net/packages/patch.htm The patch you reference modifies two files, a .tex file and a .py file. The .tex file is the source for the module documentation, you probably won't have that, so you may have to edit it out of the patch file. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do i access object
Hi As suggested by Alan, I wrote a method getcenter as follows *** def getcenter(self): xy=self.canvas.coords(self.id) xcenter=(xy[2]-xy[0])/2 ycenter=(xy[3]-xy[1])/2 return xcenter, ycenter *** However, when I call this method from the instance of Circle class I get error: call ... print items[1].getcenter() error ... AttributeError: 'function' object has no attribute 'getcenter' What is happening here? Thanks ketan. PS full code follows ... from Tkinter import * import time import random class Circle: def __init__(self, canvas, xy, ink, delta): self.canvas = canvas self.id = self.canvas.create_oval( -15, -15, 15, 15, fill=ink ) self.canvas.move(self.id, xy[0], xy[1]) self.delta = delta self.start = self.move def __call__(self): return self.start # get things going def move(self): rand=random.randint(1,4) if rand==1: xy = self.canvas.coords(self.id) #print xy if xy[2] = self.canvas.winfo_width(): self.canvas.move(self.id,-self.delta,0) self.canvas.move(self.id,self.delta,0) elif rand==2: xy = self.canvas.coords(self.id) if xy[0] = 0: self.canvas.move(self.id,self.delta,0) self.canvas.move(self.id,-self.delta,0) elif rand==3: xy = self.canvas.coords(self.id) if xy[1] = 0: self.canvas.move(self.id,0,self.delta) self.canvas.move(self.id,0,-self.delta) else: xy = self.canvas.coords(self.id) if xy[3] = self.canvas.winfo_height(): self.canvas.move(self.id,0,-self.delta) self.canvas.move(self.id,0,self.delta) return self.move def getcenter(self): xy=self.canvas.coords(self.id) xcenter=(xy[2]-xy[0])/2 ycenter=(xy[3]-xy[1])/2 return xcenter, ycenter root = Tk() root.title(Circles) root.resizable(0, 0) frame = Frame(root, bd=5, relief=SUNKEN) frame.pack() canvas = Canvas(frame, width=200, height=200, bd=0, highlightthickness=0) canvas.pack() items = [ Circle(canvas, (60, 70), blue, 1), Circle(canvas, (100, 120), green, 1), ] root.update() # fix geometry # loop over items try: while 1: for i in range(len(items)): items[i] = items[i]() root.update_idletasks() # redraw root.update() # process events print items[1].getcenter() time.sleep(0.02) except TclError: pass # to avoid errors when the window is closed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Any Good book for python
I am new in Python area and want to know Python concepts with more deatils. Please suggest some good books on python. Beginning Python, by Hetland is excellent for almost any level (I think someone who has really mastered one language, and is currently working as a programmer, can simply read Guido's tutorial use the online docs). Hetland doesn't talk down to beginner, non-programmer types, nor does he hide hard stuff; he makes it accessible. It also talks about how to program in general, how to attack problems, test, have fun.It's well indexed and organized, so it's a good reference for the noob, but as yo gain experience with Python you will migrate to the on-line docs. I have to say, however, that in the first weeks I used the book as a reference more than I used the on-line docs. Diving into Python, by Pilgrim has a lot of respect. It's available on-line http://diveintopython.org/index.html It is a Python book for experienced programmers. Which, I assume, means experienced non-Python programmers. I learn via immersion research doing, I've read a lot of computer books, and Hetland's is really quite good. I'll read Pilgrim's book in the near future. In general (with the notable exception of the Plone book) I've found the Apress materials excellent. (Both books happen to be Apress, no I'm not affiliated in any way). --stv ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to stop a thread
hello there all, i have a python reference book that got me started knowing how to use threads, i can declare one as a class, and start it like this class SomeThread(threading.Thread): run_process = SomeThread() run_process.start() but how do i kill it ? This part is not in my book. Basically the thread works, and runs in a while loop. Is there a way to destroy the instance of it after creation ? thanks all shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] farey() often gives incorrect result
farey() is at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317 Here's a script of mine that compares the results of farey() with bestFracForMaxDenom(), from my frac.py (at http://www.rcblue.com/Python/fracForWeb.py): The maxDenom (the lim of farey()) is set at 100. The dec, or decimal, or value, or v of farey(), is generated for each case by random.uniform(0.1, 1). == #compareFracAndFarey.py from __future__ import division import random def bestFracForMaxDenom(decimal, maxDenom): leastError = 1 for denom in xrange(1, maxDenom + 1): num = round(decimal * denom) error = abs((num / denom - decimal) / decimal) if error leastError: leastError = error bestDenom = denom bestNum = int(num) # leastError is a float; should I have this if statement? if leastError == 0: break return bestNum, bestDenom, leastError def farey(v, lim): '''Named after James Farey, an English surveyor. No error checking on args -- lim = max denominator, results are (numerator, denominator), (1,0) is infinity ''' if v 0: n,d = farey(-v, lim) return -n,d z = lim-lim # get 0 of right type for denominator lower, upper = (z,z+1), (z+1,z) #print lower, upper while True: mediant = (lower[0] + upper[0]), (lower[1]+upper[1]) if v * mediant[1] mediant[0]: if lim mediant[1]: return upper lower = mediant elif v * mediant[1] == mediant[0]: if lim = mediant[1]: return mediant if lower[1] upper[1]: return lower return upper else: if lim mediant[1]: return lower upper = mediant maxDenom = 100 count = 0 for x in range(10): dec = random.uniform(0.1, 1) num1, denom1, leastError = bestFracForMaxDenom(dec, maxDenom) num2, denom2 = farey(dec, maxDenom) if (num1 != num2) or (denom1 != denom2): count += 1 print Case, count print When value is, dec, and lim is, maxDenom print frac.py fraction is %d/%d % (num1, denom1) print frac.py error is, num1/denom1 - dec print farey.py fraction is %d/%d % (num2, denom2) print farey.py error is, num2/denom2 - dec print =end of compareFracAndFarey.py== (compareFracAndFarey.py is also on the web, at http://www.rcblue.com/Python/compareFracAndFarey_ForWeb.py) Here's the result of one run, that notes the 3 of 10 pairs of results in which the farey() fraction is different from the bestFracForMaxDenom() fraction. Of course, I believe that the bestFracForMaxDenom() fractions are correct, but check them out for yourselves. Case 1 When value is 0.834489320423 and lim is 100 frac.py fraction is 81/97 frac.py error is 0.000562225968725 farey.py fraction is 5/6 farey.py error is -0.00115598708969 Case 2 When value is 0.584115140346 and lim is 100 frac.py fraction is 52/89 frac.py error is 0.000154522575557 farey.py fraction is 7/12 farey.py error is -0.000781807012458 Case 3 When value is 0.946959063604 and lim is 100 frac.py fraction is 89/94 frac.py error is -0.000150552966002 farey.py fraction is 18/19 farey.py error is 0.000409357448332 Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Testing the status of NFS mounts
Hi everyone, We have several NFS mounts that are in use. Occasionally, the NFS mounts seem to go out to lunch. The mounts appear active but are no longer functional. Is there a Python module specific to NFS that I might use to periodically check its status? I imagine I could make a script to attempt a write on the share and clean up after itself but I am hoping for a more elegant solution. Any insight anyone can provide on this would be greatly appreciated. -- Thank you, Andrew Robert Senior MQ Engineer Information Technologies Massachussetts Financial Services Phone: 617-954-5882 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing the status of NFS mounts
Andrew Robert wrote: Hi everyone, We have several NFS mounts that are in use. Occasionally, the NFS mounts seem to go out to lunch. The mounts appear active but are no longer functional. Is there a Python module specific to NFS that I might use to periodically check its status? I imagine I could make a script to attempt a write on the share and clean up after itself but I am hoping for a more elegant solution. Any insight anyone can provide on this would be greatly appreciated. If the share is mounted on the test machine, seems to me a simple os.path.isdir(path to NFS root) might do the trick. Otherwise, a quick Google turns up http://www.citi.umich.edu/projects/nfsv4/pynfs/ HTH Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] python web dev
hi pythonistas! this is my first post. please could you tell me which is the best lightweight python web framework? also, which is the best templating language for python? (which can handle other data formats in addition to text). so far im lured by Cheetah, although i havent done any web dev with python yet. i absolutely love python syntax, but web dev in python is murky water. it seems unneccesarily hard, even compared to php and asp.net thanks, Shortash ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with rewriting script to use Decimal module
On Wed, 3 Jan 2007, Dick Moores wrote: Terry, I just noticed that farey(0.36, 10) returns (1, 3), a pretty big miss, IMO. The correct fraction with smallest error and maximum denominator of 10 is 3/8, which I'm proud to say my klunky frac.py (http://www.rcblue.com/Python/fracForWeb.py) produces. Dick, good catch. Consider adding a comment to the Cookbook page pointing out that the method sometimes does not produce the incorrect answer, including for that input. I note that the web page for the recipe says only that its produces a rational, not necessarily the closest rational, but the description in the book says it's the closest: You have a number v (of almost any type) and need to find a rational number (in reduced form) that is as close to v as possible but with a denominator no larger than a prescribed value. (Recipe 18.13) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python web dev
On 1/4/07, OkaMthembo [EMAIL PROTECTED] wrote: this is my first post. Welcome! please could you tell me which is the best lightweight python web framework? Best? That's a potentially contensious one. But I can tell you that if you were to look at either Django or TurboGears you wouldn't be going too far wrong. (I use Django, but I know that both are good.) also, which is the best templating language for python? (which can handle other data formats in addition to text). so far im lured by Cheetah, although i havent done any web dev with python yet. Cheetah's good, but if you go with Django, it has its own which is pretty good too. (I use both at times.) -- Cheers, Simon B [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python web dev
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of OkaMthembo Sent: Thursday, January 04, 2007 9:12 AM To: tutor@python.org Subject: [Tutor] python web dev hi pythonistas! this is my first post. please could you tell me which is the best lightweight python web framework? also, which is the best templating language for python? (which can handle other data formats in addition to text). so far im lured by Cheetah, although i havent done any web dev with python yet. i absolutely love python syntax, but web dev in python is murky water. it seems unneccesarily hard, even compared to php and asp.net thanks, Shortash I'm using Cheetah on a current project. I really like it. I like that you can compile the template and then use it as a module to populate it. I want to check out Django next. Mike - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with rewriting script to use Decimal module
At 08:20 AM 1/4/2007, Terry Carroll wrote: On Wed, 3 Jan 2007, Dick Moores wrote: Terry, I just noticed that farey(0.36, 10) returns (1, 3), a pretty big miss, IMO. The correct fraction with smallest error and maximum denominator of 10 is 3/8, which I'm proud to say my klunky frac.py (http://www.rcblue.com/Python/fracForWeb.py) produces. Dick, good catch. Consider adding a comment to the Cookbook page pointing out that the method sometimes does not produce the incorrect answer, including for that input. Done. Dick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python web dev
OkaMthembo schrieb: this is my first post. please could you tell me which is the best lightweight python web framework? Web framework and lightweight don't really go well together. There are so many things about web programming that you don't realise you need when you start, but *will* come across eventually that a framework that addresses all these, will not be lightweight any more. If you are referring to the learning curve, Django is probably better suited then TurboGears. If you have strong opinions about how certain things should be solved, I'd go with TurboGears, because it's parts are not so tightly coupled as Django's and can be replaced more easily. The usual advice is: go through the tutorials that are available on the homepages of both projects and then decide for your self. If the tutorials seem to confusing, do a general (advanced) Python tutorial first. I can't say much about other Python web frameworks, unfortunately. i absolutely love python syntax, but web dev in python is murky water. it seems unneccesarily hard, even compared to php and asp.net http://asp.net Web development requires that you know about a lot of things. PHP just leaves you to discover most of these (and build solutions for them) on your own. Which is why so many PHP programs are crap ;-) Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python web dev
OkaMthembo wrote: hi pythonistas! this is my first post. please could you tell me which is the best lightweight python web framework? also, which is the best templating language for python? (which can handle other data formats in addition to text). so far im lured by Cheetah, although i havent done any web dev with python yet. I use clearsilver for templating and like it quite a bit. I've tried Turbogears and kid (which comes with it is very nice too). -- ~noufal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Assigning a variable stored in a dictionary
I can't see the forest through the trees. I have stored 3 global variables in a dictionary, and associated each variable with a filename. Ideally, I want to read the contents of the text files, and store the contents in the global variables. The globals will be used by another function. However, when I do the assignment to varname = fh.readlines(), a new variable is created, and the reference to the global variable is overwritten, because the contents of the files are strings, and strings are immutable. I see the problem, but not a good solution. var1= var2= var3= def initGlobals(): global var1, var2, var3 fileDict = {'var1.txt':var1, 'var2.txt':var2, 'var3.txt':var3} for fn, varname in fileDict.iteritems(): try: try: fh=open(fn, 'r') #id(varname) # at this point, this id matches the id of the global variable varname = fh.readlines() # this creates a new variable, but I want to store the file contents in the global var #id(varname) # this is a new id, the global var is not updated fh.close() except IOError: print \nFATAL ERROR occurred reading %s\n % fn finally: fh.close() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] coin toss program without using the for/range loop
How to write the coin toss program without using the for/range loop program. Program flips a coin 100 times and then tells you the number of heads and tails. I can only solve it using the for/range loop Import random Heads=0 For 1 in range (100): Heads+=random.randrange(2) print Hit heads+ +str(heads)+ +times+ + hit tails + +str(100-heads)+ + times I don't see how you solve this program just using the while loop program and if/else statement. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] coin toss program without using the for/range loop
David wrote: How to write the coin toss program without using the for/range loop program. Program flips a coin 100 times and then tells you the number of heads and tails. I can only solve it using the for/range loop Import random Heads=0 For 1 in range (100): Heads+=random.randrange(2) print “Hit heads”+” “+str(heads)+” “+”times”+” “ + “hit tails” + “ “+str(100-heads)+” “ + “times” I don’t see how you solve this program just using the while loop program and if/else statement. This sounds a lot like homework so I won't give you the whole answer, but you can write a for loop using while and a counter variable. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] coin toss program without using the for/range loop
Kent Johnson wrote: David wrote: How to write the coin toss program without using the for/range loop program. Program flips a coin 100 times and then tells you the number of heads and tails. I can only solve it using the for/range loop Import random Heads=0 For 1 in range (100): Heads+=random.randrange(2) print “Hit heads”+” “+str(heads)+” “+”times”+” “ + “hit tails” + “ “+str(100-heads)+” “ + “times” I don’t see how you solve this program just using the while loop program and if/else statement. This sounds a lot like homework so I won't give you the whole answer, but you can write a for loop using while and a counter variable. In fact, in most languages a for loop and a while loop are very similar: for(int i =0; i 100; i++) { //do something } is the same as int i = 0 while (i 100) { // do something i++; } The difference in Python comes from the fact that the 'for' loop iterates over a list of objects, rather than incrementing a variable. If you're using a for-range loop in Python you're using it in the old-style that C and C++ programs use (other languages too) in which case you could easily use a while loop as well. But if you're indexing into a specific list, it becomes much more clear why we use python's 'for', to index directly into that list without having to deal with an index variable. for x in some_list: // do something with x rather than index = 0 while index len(some_list): x = some_list[index] // do something with x index += 1 HTH, -Luke Kent ___ 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] coin toss program without using the for/range loop
Kent Johnson schrieb: David wrote: print “Hit heads”+” “+str(heads)+” “+”times”+” “ + “hit tails” + “ “+str(100-heads)+” “ + “times” This sounds a lot like homework [...] An if you want to get extra marks for pythonicity ;-), read about string formatting here: http://www.python.org/doc/current/lib/typesseq-strings.html Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding parsing HTML with BeautifulSoup
Hi, Wow, thats much more elegant than the idea I thought of. Thank you very much Kent! Marshall On 1/3/07, Kent Johnson [EMAIL PROTECTED] wrote: Shuai Jiang (Runiteking1) wrote: Hello, I'm working on a program that need to parse a financial document on the internet using BeautifulSoup. Because of the nature of the information, it is all grouped as a table. I needed to get 3 types of info and have succeeded quite well using BeautifulSoup, but encountered problems on the third one. My question is that is there any easy way to parse an HTML tables column easily using BeautifulSoup. I copied the table here and I need to extract the EPS. The numbers are every sixth one from the tr tag ex 2.27, 1.86, 1.61... Here is one way, found with a little experimenting at the command prompt: In [1]: data = '''table id=INCS style=width:580px class=f10y cellspacing=0 snip the rest of your data ...: /table''' In [3]: from BeautifulSoup import BeautifulSoup as BS In [4]: soup=BS(data) In [11]: for tr in soup.table.findAll('tr'): : print tr.contents[11].string : : EPS 2.27 1.86 1.61 1.27 1.18 0.84 0.73 0.46 0.2 0.0 Kent -- I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. Sir Winston Churchill ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SPE - Stani's Python Editor ?
I found eclipse+pydev to be as good as/better than komodo or wingware. also eclipse has other plugins which makes it a powerful IDEs for php/ruby/perl etc. Regards, Shanmu. On 1/4/07, Mike Hansen [EMAIL PROTECTED] wrote: -Original Message- From: OkaMthembo [mailto:[EMAIL PROTECTED] Sent: Thursday, January 04, 2007 9:18 AM To: Mike Hansen Subject: Re: [Tutor] SPE - Stani's Python Editor ? have you tried Komodo from ActiveState or Wingware? might be great, comeercial though. I convinced my company to purchase Komodo. I use it off an on. I mostly gravitate toward VIM. I'm looking forward to the next version of Komodo since it will have vi keybindings. The nice thing about Komodo is that you can use it for other languages like Perl and Ruby where I believe that Wingware is Python only. Mike - NOTICE: This e-mail transmission and any documents or files attached to it contain information for the sole use of the above-identified individual or entity. Its contents may be privileged, confidential, and exempt from disclosure under the law. Any dissemination, distribution, or copying of this communication is strictly prohibited. Please notify the sender immediately if you are not the intended recipient. FGNS ___ 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] Need help with rewriting script to use Decimal module
On Wed, 3 Jan 2007, Dick Moores wrote: Be that as it may, farey() is an amazing program. Not to beat this subject to death, but the comment at the bottom of http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52317 about continued fractions piqued my interest. I'm no mathematician, but I encountered continued fractions a long time ago and was fascinated by them. So I read the URL pointed to, http://mathworld.wolfram.com/ContinuedFraction.html , and came up with the following: # def cf(x, tol=0.0001, Trace=False): Calculate rational approximation of x to within tolerance of tol; returns a tuple consisting of numerator and denominator p/q Trace=True causes iterated results to be shown a, r, p, q = [], [], [], [] Done = False n = 0 if Trace: print x:%f tol:%f % (x, tol) while not Done: a.append(None) r.append(None) p.append(None) q.append(None) if n == 0: r[n] = x else: r[n] = 1/(r[n-1]-a[n-1]) a[n] = int(r[n]) if n == 0: p[n] = a[0] q[n] = 1 elif n ==1: p[n] = a[n]*p[n-1] + 1 q[n] = a[n] else: p[n] = a[n]*p[n-1] + p[n-2] q[n] = a[n]*q[n-1] + q[n-2] if Trace: print n:%d a:%d p:%d q:%d approx:%f % \ (n, a[n], p[n], q[n], float(p[n])/q[n]) if abs(float(p[n])/q[n] - x) tol: Done = True num = p[n]; denom = q[n] n += 1 return (num, denom) # Here's a result for pi: print cf(3.14159265357989,0.001, Trace=True) x:3.141593 tol:0.00 n:0 a:3 p:3 q:1 approx:3.00 n:1 a:7 p:22 q:7 approx:3.142857 n:2 a:15 p:333 q:106 approx:3.141509 n:3 a:1 p:355 q:113 approx:3.141593 n:4 a:292 p:103993 q:33102 approx:3.141593 (103993, 33102) i.e., the first 5 approximations it came up with were 3/1, 22/7, 333/106, 355/113 and a whopping 103993/33102. For the 0.36 example you used earlier: print cf(0.36, .01, Trace= True) x:0.36 tol:0.01 n:0 a:0 p:0 q:1 approx:0.00 n:1 a:2 p:1 q:2 approx:0.50 n:2 a:1 p:1 q:3 approx:0.33 n:3 a:3 p:4 q:11 approx:0.363636 (4, 11) it went right from 1/3 to 4/11 (0.363636), skipping the 3/8 (0.375) option from the farey series. But this continued fraction algorithm is ill-suited to answer the question what's the closest fraction with a denominator N, because it doesn't try to find that, it jumps further ahead with each iteration. Anyway, I thought you might find it interesting based on our discussion. (Yeah, I know, I didn't choose the formats well on those print statements.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor