Python app setup
Hi, I've installed latest version of Python 3.9.5 and downloaded for Windows. Once I click on the Python app, I'm getting command screen and not sure on the next action. could you please help me to fix this issue. Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Thanks, Murali PA Disclaimer: The information in this email is the property of IBM and may be IBM Confidential and privileged. It is intended solely for the addressee. Access to this email by anyone else is unauthorized. If you are not the intended recipient, any disclosure, copying, distribution or any action taken in reliance on it is prohibited. If you receive this message in error please notify the sender immediately and delete all copies of this message. -- https://mail.python.org/mailman/listinfo/python-list
[issue9305] Don't use east/west of UTC in date/time documentation
Change by Murali Ravipudi : -- nosy: +Murali Ravipudi ___ Python tracker <https://bugs.python.org/issue9305> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39111] Misleading documentation
Murali Ganapathy added the comment: === # python3 class Base: def __eq__(self, other): print("base called") return super().__eq__(other) class Foo(Base): def __eq__(self, other): print("foo called") return NotImplemented Foo() == Foo() # foo called # foo called False Base.__eq__ is not called here. Is calling of object.__eq__ special cased? -- ___ Python tracker <https://bugs.python.org/issue39111> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue39111] Misleading documentation
New submission from Murali Ganapathy : The documentation at https://docs.python.org/3.6/library/constants.html#NotImplemented states If all attempts return NotImplemented, the interpreter will raise an appropriate exception. However this is not true for __eq__. === class Foo: def __eq__(self, other): return NotImplemented Foo() == Foo() # returns False, does not throw an exception -- assignee: docs@python components: Documentation messages: 358719 nosy: docs@python, murali priority: normal severity: normal status: open title: Misleading documentation versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8, Python 3.9 ___ Python tracker <https://bugs.python.org/issue39111> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
help for documentation and license
hi all.. I finished my application using python 2.6 and wxpython 2.8.9 I want to generate documentation for my application.. please suggest me and provide links to generate documents in easy way.. I want to host my product as open source.. I'dont know about licensing.. help me for this also.. Advanced Thanks .. -- http://mail.python.org/mailman/listinfo/python-list
problem in with keyword
hi all.. my application runs fine in windows xp using python 2.6 and wxpython 2.8.9 but in ubuntu 8.10 following error appears.. using python 2.5.2 and wxpython 2.8.9 /home/murali/Desktop/mathdemo-configfinal/manageprofile.py:63: Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File test.py, line 8, in module import manageprofile as managepf File /home/murali/Desktop/mathdemo-configfinal/manageprofile.py, line 63 with open(self.profile, 'wb') as configfile: ^ SyntaxError: invalid syntax help for this problem.. Advanced thanks.. -- http://mail.python.org/mailman/listinfo/python-list
communication between objects - help
thanks a lot.. I think passing the main object only by reference.. so, this does not causes any overhead.. am i correct..? On Fri, Apr 10, 2009 at 4:02 PM, Dave Angel da...@ieee.org wrote: Murali kumar wrote: hi all.. I'm posted in a word doc becoz to add a image to explain my problem.. also I think gmail automatically scans for attachments.. anyway.. here's my problem...( see the image) http://www.2shared.com/file/5299759/45e4c614/load.html Using : Python 2.6 , wxPython 2.8.9 snip... * I don’t know how to return config file or data to mainApp object when pressing load button. * * Is it easy to return filename only and load the file’s data into mainApp object in menu handler itself? * Please suggest me right direction.. and tell me how to do it? Usually where I can get these informations.. (suggest links and books..) Thanks for any advice Most of the widget classes in your code should be derived classes, so they can hold extra instance data event handlers and such. So that means you can have extra parameters on the constructor, besides the ones the base class requires. Use one or more of those extra parameters to store your own information about the hierarchy. Simplest example is to add the app instance to each constructor. Then each widget object would know how to call back into the app to do some work, or to load data into a common place. DaveA -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: communication between objects - help
Thanks a lot for help.. On Sat, Apr 11, 2009 at 6:27 PM, Dave Angel da...@dejaviewphoto.com wrote: Murali kumar wrote: thanks a lot.. I think passing the main object only by reference.. so, this does not causes any overhead.. am i correct..? On Fri, Apr 10, 2009 at 4:02 PM, Dave Angel da...@ieee.org wrote: Murali kumar wrote: hi all.. I'm posted in a word doc becoz to add a image to explain my problem.. also I think gmail automatically scans for attachments.. anyway.. here's my problem...( see the image) http://www.2shared.com/file/5299759/45e4c614/load.html Using : Python 2.6 , wxPython 2.8.9 snip... * I don’t know how to return config file or data to mainApp object when pressing load button. * * Is it easy to return filename only and load the file’s data into mainApp object in menu handler itself? * Please suggest me right direction.. and tell me how to do it? Usually where I can get these informations.. (suggest links and books..) Thanks for any advice Most of the widget classes in your code should be derived classes, so they can hold extra instance data event handlers and such. So that means you can have extra parameters on the constructor, besides the ones the base class requires. Use one or more of those extra parameters to store your own information about the hierarchy. Simplest example is to add the app instance to each constructor. Then each widget object would know how to call back into the app to do some work, or to load data into a common place. DaveA -- http://mail.python.org/mailman/listinfo/python-list All objects are passed by reference in python. And storing it in each widget costs very little. Note that you can choose what object or objects should be used; I just mention the app as a choice that everyone will subclass, and that will generally have direct or indirect access to all widgets. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
communication between objects - help
hi all.. I'm posted in a word doc becoz to add a image to explain my problem.. also I think gmail automatically scans for attachments.. anyway.. here's my problem...( see the image) http://www.2shared.com/file/5299759/45e4c614/load.html Using : Python 2.6 , wxPython 2.8.9 *Scenario: *In my application , a menu invoking a frame class. It’s having a wx.notebook control like above. Each notebook page is also a class. In loadprofile class i'm tried to load a configuration file already created by application. (when pressing load button, current selected config filename in a listbox must be loaded for application.) config file data must to be applied to my application object. mainApp object --- Frame object ( wx.notebook ) | Load profile class | (return config file or data to mainApp object in load button Event handler function..) * I don’t know how to return config file or data to mainApp object when pressing load button. * * Is it easy to return filename only and load the file’s data into mainApp object in menu handler itself? * Please suggest me right direction.. and tell me how to do it? Usually where I can get these informations.. (suggest links and books..) Thanks for any advice -- http://mail.python.org/mailman/listinfo/python-list
config parser -help
hi all, i want to all my configuration file names in current/user/home directory.. for that i came across following function in configparser class.. Is it must to specify file names? or only directories enough.. if there anyway to read conf filenames in current/user directory... config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: config parser -help
Is there anyway to read all my configuration filenames with extension (.cfg)? Advanced thanks.. On Fri, Apr 3, 2009 at 3:15 PM, Murali kumar murali...@gmail.com wrote: hi all, i want to all my configuration file names in current/user/home directory.. for that i came across following function in configparser class.. Is it must to specify file names? or only directories enough.. if there anyway to read conf filenames in current/user directory... config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: config parser -help - anybody please immediately help for me...
On Fri, Apr 3, 2009 at 3:59 PM, Murali kumar murali...@gmail.com wrote: Is there anyway to read all my configuration filenames with extension (.cfg)? Advanced thanks.. On Fri, Apr 3, 2009 at 3:15 PM, Murali kumar murali...@gmail.com wrote: hi all, i want to all my configuration file names in current/user/home directory.. for that i came across following function in configparser class.. Is it must to specify file names? or only directories enough.. if there anyway to read conf filenames in current/user directory... config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: speech recognition help
hi all.. I tried following tools by ur advice.. 1. cmu sphinx: tried and managed run the demo programs.. but the accuracy is so bad. for that i tried for how to train the grammer. but for that i had no guidance.. docs give me the headache.. after 2 weeks.. i concluded that it will not be commercially useful for distributed application. 2. Naturally speaking: downloads only provided for cost. so no try. 3. windows sapi: windows provides redistributeable copies. also there are some python bindings available for to connect this engine. training with each user is easy in windows sapi ( for that i choosed this.) only limitation is usage within windows. so , concluded that using windows sapi.. am i correct? if u know any best articles/links for using windows sapi from python.. kindly give me that.. On Sat, Mar 21, 2009 at 8:40 PM, Stef Mientki stef.mien...@gmail.comwrote: Tim Chase wrote: do u know which one 1. cmu sphinx 2. natural speaking 3. windows sapi is best ( in accuray and speed ) for predefined vocabulary.. and worth for learning as well.? For a pre-defined vocabulary, they should all be pretty good. In general (for non-predefined vocabularies), I've heard that NS beats both Sphinx and SAPI in terms of recognition quality. +1 I haven't seen any comparisons between Sphinx and SAPI. Other considerations may also come into play: - do you expect all your users to have a copy of NS? Then you might have to look into something other than NS if they won't. Or perhaps NS has a developers' toolkit that allows for redistribution when built into your app. - do you expect all your users to run Windows (as I type this from my Linux box...)? If not, then SAPI won't be available to your Mac/Linux/BSD/BeOS/Amiga/whatever users. - do you need TTS (text-to-speech) capabilities as well? SAPI includes them. (there are other TTS libraries available such as mbrola/festival that are available for this if needed) - how easy is it to bind to Python? Sphinx has Python bindings detailed on the website. I can't speak for NS or SAPI. both are covered by DragonFly Stef -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
python installer
hi all.. To distribute my application.. what will be the best..? python installer.. or py2exe..? using : python 2.6 , wxpython 2.8.9 -- http://mail.python.org/mailman/listinfo/python-list
Re: speech recognition help
thanks for the reply.. now working on cmu sphinx project.. do u know which one 1. cmu sphinx 2. natural speaking 3. windows sapi is best ( in accuray and speed ) for predefined vocabulary.. and worth for learning as well.? -- http://mail.python.org/mailman/listinfo/python-list
speech recognition help
hi all.. I want* to add speech recognition *to my application for *disabled persons*. (running in python 2.6 with wxpython 2.8.9..) *problem:* actually i have some buttons scanned one by one.. button name is 'add' and if i tell 'add' then add button click event must be performed.. For that i need the conversion of *speech to text.* Tell me the right advice and necessary links to implement this... Advanced thanks...! -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with special characters in filename
Try this: import shutil,os file1 = open('a.dat','r') #opens file for reading for line in file1: print line ##old_name = line[0:len(line)-1] #gets rid of \n suffix ##print old_name line.strip() #gets rid of \n suffix print line os.rename('b.dat',line) #renames file file1.close() From: fizzo...@gmail.com fizzo...@gmail.com To: python-list@python.org Sent: Friday, January 23, 2009 2:43:24 PM Subject: problem with special characters in filename using: Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Hello I have two files (let's assume they are all in the same directory): 1) a.dat containing the single line Sébastien.dat 2) Sébastien.dat containing arbitraty data I want to: open a.dat read in the single line (Sébastien.dat) copy the file described by the single line (Sébastien.dat) to another location with name b.dat This is what I have started with: import shutil file = open('a.dat','r') #opens file for reading for line in file: print line old_name = line[0:len(line)-1] #gets rid of \n suffix print old_name shutil.copy(old_name, 'b.dat') #copies file However I get the following error: IOError: [Errno 2] No such file or directory: 'S\xc3\xa9bastien.dat' I'm sure this has something to do with encoding and decoding UTF-8 and Unicode or something like that, but everything I've tried has yet to produce any favourable results. Thanks Dino -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Need script to download file from a server using python script
Hi, I am fairly new to python and i am looking for a python script to download file(latest build) from the server. But, the build name changes daily. For Ex: today the build URL will be http://mybuilds/myapp_1234.exe; and tomorrow it will be http://myserver/mybuilds/myapp_3456.exe;. So i need a script which downloads the latest build without any knowledge of build number. Can anyone help me? Advance thanks, This is my start: ### import os,sys,httplib,time, Server=myserver Build2Download=mybuilds/myapp_3456.exe installer=myapp_3456.exe print Downloading Installer... from the site:%s%Server connection=httplib.HTTPConnection(Server) connection.request(GET,Build2Download) resp = connection.getresponse() if resp.status != 200: print Error getting installer. GET response : %d %s % (resp.status, resp.reason) sys.exit(-1) try: open(Installer, 'wb').write(resp.read()) time.sleep(15) except: pass ### The build number keeps changing. So how can i use wildchars(?) or something else to handle change in the build no.? Advance Thanks, Murali. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interprocess communication woes
On Jul 19, 4:30 am, Nick Craig-Wood [EMAIL PROTECTED] wrote: Murali [EMAIL PROTECTED] wrote: After some investigation, I found out that this problem had nothing to do with my GUI app not getting refreshed and I was able to reproduce this problem with normal python scripts. Here is one such script #File test.py from subprocess import Popen from subprocess import PIPE import sys if __name__ == '__main__': prog = sys.argv[1] proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0) out = proc.stdout while proc.poll() is None: print out.readline() Run this program as follows $ test.py ping -c 10www.google.com Now, you would see the responses as if you just launched ping on the command line. Now, lets look at another program. Here is a simple C++ program that prints numbers 1 to 10 at the passage of every second (sort of a stopwatch) #include stdio.h #include stdlib.h #include sys/time.h main ( ) { timeval t1, t2; gettimeofday(t1, NULL); int prev = -1; int cur = 0; while (true) { gettimeofday(t2,NULL); if(t2.tv_sec - t1.tv_sec 10) break; else { cur = t2.tv_sec-t1.tv_sec; if (cur != prev) { printf(%d\r\n,cur); prev = cur; } } } } if you would build this program and call it lets say timer ($ g++ -o timer timer.cpp) and run it with our python script like this $python test.py ./timer you would see that every time you run the program your results vary and on top of this the stdout of the timer program gets displayed all at once presumably when the timer program has completed execution. Why this discrepancy between the ping and timer programs? Is my test.py script correct? Is there a better or a preferred method for doing interprocess communication in Python. Buffering is your problem. If you add a fflush(stdout); after the printf(...); you'll find the c++ program works as you expect. It is just a fact of life of the C stdio system. If it is connected to a terminal then it will turn off buffering. If it is connected anything else (eg a pipe via subprocess) then it will buffer stuff as you've seen. So you can Thanks Nick. fflush fixed it. Thanks for your pointers on pexpect and pty module too. Murali. a) modify the c++ prog to add fflush() in or use setvbuf() b) use the pexpect module -http://pexpect.sourceforge.net/ c) use the pty module (unix only) The pexpect module will connect to the subprogram with pseudo-ttys, fooling the program, and the C library, into thinking that it is speaking to a terminal and turn off buffering. Pexpect doesn't work on windows. The fact that ping works is because it uses fflush() - you can see this if you ltrace it. -- Nick Craig-Wood [EMAIL PROTECTED] --http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Interprocess communication
Hi Python Gurus, I am writing a GUI app (on linux) using pygtk which would launch some external applications and display their stdout and stderr inside the output window of my application synchronously. I am using the subprocess module's Popen to launch the external programs and to capture their stdout and stderr. The problem is that, for some external programs that I launch inside my interface, I am not able to capture and display the stdout as the program *runs*. After some investigation, I found out that this problem had nothing to do with my GUI app not getting refreshed and I was able to reproduce this problem with normal python scripts. Here is one such script #File test.py from subprocess import Popen from subprocess import PIPE import sys if __name__ == '__main__': prog = sys.argv[1] proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0) out = proc.stdout while proc.poll() is None: print out.readline() Run this program as follows $ test.py ping -c 10 www.google.com Now, you would see the responses as if you just launched ping on the command line. Now, lets look at another program. Here is a simple C++ program that prints numbers 1 to 10 at the passage of every second (sort of a stopwatch) #include stdio.h #include stdlib.h #include sys/time.h main ( ) { timeval t1, t2; gettimeofday(t1, NULL); int prev = -1; int cur = 0; while (true) { gettimeofday(t2,NULL); if(t2.tv_sec - t1.tv_sec 10) break; else { cur = t2.tv_sec-t1.tv_sec; if (cur != prev) { printf(%d\r\n,cur); prev = cur; } } } } if you would build this program and call it lets say timer ($ g++ -o timer timer.cpp) and run it with our python script like this $python test.py ./timer you would see that every time you run the program your results vary and on top of this the stdout of the timer program gets displayed all at once presumably when the timer program has completed execution. Why this discrepancy between the ping and timer programs? Is my test.py script correct? Is there a better or a preferred method for doing interprocess communication in Python. Thanks! Murali. -- http://mail.python.org/mailman/listinfo/python-list
Interprocess communication woes
Hi Python Gurus, I am writing a GUI app (on linux) using pygtk which would launch some external applications and display their stdout and stderr inside the output window of my application synchronously. I am using the subprocess module's Popen to launch the external programs and to capture their stdout and stderr. The problem is that, for some external programs that I launch inside my interface, I am not able to capture and display the stdout as the program *runs*. After some investigation, I found out that this problem had nothing to do with my GUI app not getting refreshed and I was able to reproduce this problem with normal python scripts. Here is one such script #File test.py from subprocess import Popen from subprocess import PIPE import sys if __name__ == '__main__': prog = sys.argv[1] proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0) out = proc.stdout while proc.poll() is None: print out.readline() Run this program as follows $ test.py ping -c 10 www.google.com Now, you would see the responses as if you just launched ping on the command line. Now, lets look at another program. Here is a simple C++ program that prints numbers 1 to 10 at the passage of every second (sort of a stopwatch) #include stdio.h #include stdlib.h #include sys/time.h main ( ) { timeval t1, t2; gettimeofday(t1, NULL); int prev = -1; int cur = 0; while (true) { gettimeofday(t2,NULL); if(t2.tv_sec - t1.tv_sec 10) break; else { cur = t2.tv_sec-t1.tv_sec; if (cur != prev) { printf(%d\r\n,cur); prev = cur; } } } } if you would build this program and call it lets say timer ($ g++ -o timer timer.cpp) and run it with our python script like this $python test.py ./timer you would see that every time you run the program your results vary and on top of this the stdout of the timer program gets displayed all at once presumably when the timer program has completed execution. Why this discrepancy between the ping and timer programs? Is my test.py script correct? Is there a better or a preferred method for doing interprocess communication in Python. Thanks! Murali. -- http://mail.python.org/mailman/listinfo/python-list
Reading stdout and stderr of an external program
Hi Python programmers, I need to be able to read the stdout and stderr streams of an external program that I launch from my python script. os.system( 'my_prog' + ' err.log' ) and was planning on monitoring err.log and to display its contents. Is this the best way to do this? Thanks, Murali. -- http://mail.python.org/mailman/listinfo/python-list
message handling in Python / wxPython
hi, i have basic knowledge of python and wxPython... now i need to know about message handling in python/wxPython? could anybody pls help me by giving some info on how to handle (in Python), 'the user defined messages' posted from VC++, i dont know how to handle messaes in python. Thanks and Regards, Murali M.S -- http://mail.python.org/mailman/listinfo/python-list
Re: how to delete matplotlib data between ploting
pylab.clf() or some such thing clears the current canvas. [EMAIL PROTECTED] wrote: I want to make few plots from CSV files. I have the code below - it works - the first plot is ok, the second one has the first and the current data set and so on - I can't delete the plot data between plots. ## # -*- coding: utf-8 -*- from pylab import * from os import listdir i = listdir('dane/') # list folders with CSV files for di in i: # list files in folders csv = listdir('dane/' + di + '/') for datafile in csv: # open each CSV file file = open('dane/' + di + '/' + datafile, 'r').readlines() x = [] y = [] # get the data for row in file: if row.find(',') != -1: r = row.split(',') if len(r[0]) 0 and len(r[1]) 0: x.append(float(r[0])) y.append(float(r[1])) xlabel('czas') ylabel('Moc') title(di.replace('.', ' ')) #plot plot(x, y) savefig('dane/' + di + '/' + datafile + '.png') del x del y del file -- http://mail.python.org/mailman/listinfo/python-list
Re: Reverse function python? How to use?
Something like this? [code] foo = [x1,x2,x3,x4,x5] bar = [math.sqrt(math.fabs(x))+5*math.pow(x,3) for x in foo] bar.reverse() print bar [/code] frankie_85 wrote: Ok I'm really lost (I'm new to python) how to use the reverse function. I made a little program which basically the a, b, c, d, e which I have listed below and basically I want it th result to be printed reverse so instead doing print e, d, c, b, a, I'd like to use the reverse function Can someone give pointersguidelines / on how to do it? [code] a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3 b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3 c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3 d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3 e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3 [/code] Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: reusing parts of a string in RE matches?
John Salerno wrote: So my question is, how can find all occurrences of a pattern in a string, including overlapping matches? I figure it has something to do with look-ahead and look-behind, but I've only gotten this far: import re string = 'abababababababab' pattern = re.compile(r'ab(?=a)') m = pattern.findall(string) Why not something like import re string = 'abababababababab' pattern = re.compile(r^aba) ans = [] for x in xrange(len(string)): m = pattern.match(string[x:]) if m: ans.append( (x+m.start(),x+m.end())) # now ans is a list of pairs (p,q) where the substring string[p:q] matches pattern - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: reusing parts of a string in RE matches?
Yes, and no extra for loops are needed! You can define groups inside the lookahead assertion: import re re.findall(r'(?=(aba))', 'abababababababab') ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] Wonderful and this works with any regexp, so import re def all_occurences(pat,str): return re.findall(r'(?=(%s))'%pat,str) all_occurences(a.a,abacadabcda) returns [aba,aca,ada] as required. - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: append function problem?
A typo here? seed v/s seed1. Instead of print(seed.append(5)), try seed.append(5) followed by print seed -- print(seed) also works. The append method does not return the appended value (like many C functions). - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: Make staticmethod objects callable?
You have a text-database, each record has some header info and some data (text-blob). e.g. HEADER name = Tom phone = 312-996- /HEADER I last met tom in 1998. He was still single then. blah blah HEADER name = John birthday = 1976-Mar-12 /HEADER I need to ask him his email when I see him next. -- I use this format for a file to keep track of tit bits of information. Lets say the file has several hundred records. I know want to say generate a birthday list of people and their birthdays. Ofcourse along with that I also need the text-blob (because I dont want to send a birthday card to a person I dont like). In order to do this I execute a script ./filter --input=database.txt --condn='similar(name,tom)'. The way it is implemented is simple. Have a class which has dict as its base class. For each record the text between hEADER and /HEADER is executed with the class instance as locals(). Now that I have a list of class instances, I just exec the condition and those instances where it evaluates True comprise the output text file. To make the user, not have to know too much python, one would like to define functions which can be used. For eg. similar would have the following definition @staticmethod def similar(regexp,str): return re.match((?i)^.*%s.*$ % regexp, str) != None This way the locals() dictionary in the exec'ed environment has access to the function similar (if similar was callable). At the same time, I can enclose all these functions in their own name space (as static methods of a class). Right now, I declare all these helper functions in a different module, and attach the helper functions as keys into the dictionary. If only staticmethods were callable. For some reason (I dont recall why) the idea of converting the staticmethod into a callable still did not work, e.g. class Callable: def __init__(self,method): self.__call__ = method class Record(dict): @staticmethod def similar(regexp,string): self['similar'] = Callable(similar) The above did not work. The error message was still related to a staticmethod not being a callable. - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient Find and Replace
Thanks for the replies. I always thought that Python lists were actually lists under the hood. If they are implemented as arrays of pointers things should be a lot more efficient. In particular what I thought was a Linear-time operation is actually an O(1) operation. Since python allows you to replace single items with lists e.g. L[x:x+1]= [a,b,c], It has to be a little more clever. But with good data structure design I beleive that this overhead can be amortized to O(1). The optional argument to lst.index also makes that an linear time code. Thanks for all the help. - Murali PS: Slowly python is becoming my more favourite language than even C (except in cases you just cannot use anything but C, e.g. writing a boot loader) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python String Substitution
No. I dont have a real life example. I was explaining % substitution to somebody and realized that I have only used it in the form where the keys are strings. Was wondering if there is some special syntax already part of python with which I can lookup the dictionary using a tuple as a key. - Murali -- http://mail.python.org/mailman/listinfo/python-list
Efficient Find and Replace
Given: L = list of integers. X and Y are integers. Problem: find every occurence of X and replace with Y Solution1: def check(s): if s==X: return Y else return s newL = [ check(s) for s in L] Now I dont want to create another list but just modify it in place. SolutionA: for x in range(len(L)): if L[x] == X: L[x:x] = Y SolutionB: p = L.index(X) while p = 0: L[p:p] = Y p = L.index(X) Problem with both solutions is the efficiency. Both methods require time O(N^2) in the worst case, where N is the length of the list. Because L.index() and L[x:x] both take O(N) time in the worst case. But clearly one should be able to do it in time O(N). Atleast there is a C solution which does it in O(N) time. p = head(L) while (p) { if (p-data == X) p-data = Y; } Is there a python equivalent of this? using iterators or something which will allow me efficient serial access to the list elements. - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient Find and Replace
I did not actually run the code, so there may be syntax errors and so forth. But how is L[x] = Y an O(1) operation. Given x finding L[x] would require to traverse x nodes in the list. So finding L[x] requires O(x) time. Once you find L[x] setting it to Y is O(1) I agree. In Solution B: By L.index(X), I mean search for X and then replace it with Y. Here every time the search starts from the beginning of the list. Hence the inefficiency. - Murali -- http://mail.python.org/mailman/listinfo/python-list
Python String Substitution
In Python, dictionaries can have any hashable value as a string. In particular I can say d = {} d[(1,2)] = Right d[(1,2)] = Wrong d[key] = test In order to print test using % substitution I can say print %(key)s % d Is there a way to print Right using % substitution? print %((1,2))s % d gives me Wrong. Is there any syntax which will allow me to get Right using % substitution? - Murali -- http://mail.python.org/mailman/listinfo/python-list
Re: generating method names 'dynamically'
import inspect x = ABC() # create an instance of class ABC print inspect.getmembers(x,inspect.ismethod) Most of any introspection stuff can be done using the module inspect. -- http://mail.python.org/mailman/listinfo/python-list
Re: generating method names 'dynamically'
x.__class__.__dict__[mname](x,*args,**kwargs) here x is an instance of a class FOO FOO has a method bar (if the value of mname is bar) args is a tuple whose length is the number of positional arguments accepted by bar kwargs is a dictionary corresponding to the keyword arguments accepted by bar. Hope this answers your questions. - Murali -- http://mail.python.org/mailman/listinfo/python-list