Re: [Tutor] Help me with two dimensional arrays in Python
Asrarahmed, How about something like this: >>> arr = [] >>> arr.append(['Blue', 'Yellow', 'Green', 'Brown', 'White']) >>> arr[0][0] 'Blue' >>> arr.append(['Up', 'Down', 'Left', 'Right', 'Center']) >>> arr[1][4] 'Center' Is this what you were thinking of? -mtw On Wed, Oct 04, 2006 at 06:38:09PM +0100, Asrarahmed Kadri ([EMAIL PROTECTED]) wrote: > I am looking for something like this: > > int arr[5][5]; // C statement; declaring an array of 5 * 5 size > > Is there an easy and clean way to achieve this in python??? > > Thanks > > > > On 10/4/06, Kent Johnson <[EMAIL PROTECTED]> wrote: > > > >Asrarahmed Kadri wrote: > >> > >> Hi folks, > >> > >> I am stuck.. Please help me with implementing two dimensional array in > >> Python. > > > >Nested lists are the simplest way though beware the gotcha shown here: > > > >http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list > > > >You can also use a dict with tuple indices, e.g. > >d[1,2] = 3 > > > >Numpy is an extension designed for high-performance numerical work, it > >includes a multidimensional array type: > >http://numpy.scipy.org// > > > >Kent > > > > > > > -- > To HIM you shall return. > ___ > 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] Splitting text
Hello Appu, You can use the count() method to find the number of occurances of a substring within a string: >>> a = 'TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' >>> a.count('ATTTA') 2 -mtw On Thu, Jun 29, 2006 at 12:45:06PM -0700, Apparao Anakapalli ([EMAIL PROTECTED]) wrote: > hello all: > > I have a question and I do not know how I can work it > out. > > > I have a file of sequences > >a > TCCCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACATTTA' > >b > CCTGCGGCGCATGAGTGACTGGCGTATTTAGCCCGTCACAATTTAA' > > > (10 K) > > > pattern = 'ATTTA' > > I want to find the pattern in the sequence and count. > > For instance in 'a' there are two 'ATTTA's. > > How can I do that. > > One approach tried: > import re > > pat = 'ATTTA' > if re.search(pat,a): > print 'yes' > > By counting number of yeses I thought I can answer the > question. However, the above approach only looks for > the first instance of pat and says yes and moves to > next. > > > The other way: > a.find(pat) > > This also looks for first one and reports the position > of chracter. > > > Could any one suggest the best way to cound the number > of patterns. > > > Thank you > appu > > > __ > 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] File compression
Hi Magnus, I would check out the python tarfile module: http://docs.python.org/lib/module-tarfile.html Looks like it will compress with bzip too! -mtw On Wed, Jun 28, 2006 at 12:19:19AM +0200, Magnus Wirström ([EMAIL PROTECTED]) wrote: > Hi Everyone > > I'm starting to python and i need to write a program that are able to > compress a high amount of files and directories into a single file that > is later going to be transfered with ftp to a backup storage server. > The data is a quite big amount (over 1.5 gb in 4 files and 1300 > directories) so i would like to have high compression like RAR or bz2. > What way is the best to approach this? I have looked a bit on zlib but i > didn't find a good example that uses it to compress files and > directories in one file from python. or perhaps it's simpler to execute > a external program, doing the work. I would prefer to use python as much > as i can without external apps. > > Does anyone have a idea how this can be made with python. > > Thanks > Magnus Wirström > ___ > 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] Delete directories recursively
You must change the directory and file permissions before attempting to remove them; even if you are using a python script. Take a look at os.chmod() -mtw On Fri, Jun 16, 2006 at 10:26:34AM -0500, Amresh Kulkarni ([EMAIL PROTECTED]) wrote: > Hi, > > I need to delete a directory and its sub directories. However all dir's, sub > dir;s and files have read only access. How do i do this efficeintly using > the os.walk command. > I cannot run this command on the dir as it gives me an error due to the read > only attribute. Is there any other way to do this? > > -- > ~~AMRESH~~ > ___ > 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] ossaudiodev, pygtk, and flushing buffers
Michael, Calling .reset() did the trick. The code now waits for the user to press play before opening the audio device and closes it when paused or EOF is reached. Thanks for your help! -mtw On Thu, May 11, 2006 at 07:15:52PM +0200, Michael Lange ([EMAIL PROTECTED]) wrote: > On Wed, 10 May 2006 09:59:14 -0700 > Matthew White <[EMAIL PROTECTED]> wrote: > > > Hello All, > > > > I'm writing a little audio player that plays voicemail files. (I realize > > I'm reinventing the wheel, but it's still fun.) > > > > The problem I'm experiencing is that I'm hearing the last fraction of > > the sound clip twice, either when the clip is done playing or when the > > program exits. > > > > I've tried a few things and none of them have worked. The bit of code > > that does the playing is here: > > > > def play(self): > > if self.data_written < self.file_length: > > buf = self.data.read(self.buf_size) > > self.data_written += self.dsp.write(buf) > > self.percent_done = self.data_written / self.file_length > > > > if self.data_written == self.file_length: > > self._reopen_audio_device() > > > > This causes the second playing of the "last little bit" when the end of > > the file is reached. When I don't include the second if statement, the > > "last little bit" gets played when the program exits. > > > > According to the documentaiton, closing the audio device will flush any > > data in the sound card buffer. I guess what I'm hearing is that buffered > > clip being flushed. I've thought about using the mixer device to put the > > volume to zero, flush the buffer, then turning the volume back up again, > > but that seems like a hack. > > > > Hi Matthew, > > you never explicitely close the audio device, except when calling > self._reopen_audio_device(). > According to the OSS programmer's guide > (http://www.opensound.com/pguide/index.html ) this is generally considered > bad practice, > because no other application will be able to access the audio device. > Probably it is not guaranteed that the device's > buffers will be flushed until calling close(), too (maybe calling reset() > also flushes the buffers, but after reset() you > should close and reopen the device anyway). > I have not tried it, but I think the effect you describe may depend on the > driver in use. > > Does it help if you change your play() method like this: > > def play(self): > if self.data_written < self.file_length: > buf = self.data.read(self.buf_size) > self.data_written += self.dsp.write(buf) > self.percent_done = self.data_written / self.file_length > if self.data_written == self.file_length: > self.dsp.close() > # then reopen the device right before starting playback, probably from > player.PlayerWindow.play() > > ? > > There may be a short delay between the call to self.dsp.close() and the > actual stopping of playback, > (which can be avoided by calling self.dsp.reset() before self.dsp.close()), > however this should not be a problem if you > play the file to the end, I think. > > I hope this helps > > Michael > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] ossaudiodev, pygtk, and flushing buffers
Hello All, I'm writing a little audio player that plays voicemail files. (I realize I'm reinventing the wheel, but it's still fun.) The problem I'm experiencing is that I'm hearing the last fraction of the sound clip twice, either when the clip is done playing or when the program exits. I've tried a few things and none of them have worked. The bit of code that does the playing is here: def play(self): if self.data_written < self.file_length: buf = self.data.read(self.buf_size) self.data_written += self.dsp.write(buf) self.percent_done = self.data_written / self.file_length if self.data_written == self.file_length: self._reopen_audio_device() This causes the second playing of the "last little bit" when the end of the file is reached. When I don't include the second if statement, the "last little bit" gets played when the program exits. According to the documentaiton, closing the audio device will flush any data in the sound card buffer. I guess what I'm hearing is that buffered clip being flushed. I've thought about using the mixer device to put the volume to zero, flush the buffer, then turning the volume back up again, but that seems like a hack. If anyone decides to use this program, you'll need to use a .wav file and change the value of self.sample_rate in vmPlayer.py from 8000 to 44100 (or whatever rate your file is encoded in) (Also, I plan on auto-detecting the sample rate in the future. I hard coded 8000 because that's the rate the voice mail system uses.) See attached files for the code. -mtw player_py.RENAMED_BY_TTSD-0 Description: application/renamed_by_ttsd-0 vmPlayer_py.RENAMED_BY_TTSD-2 Description: application/renamed_by_ttsd-2 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Halting execution
Matthew, sys.exit() is one way to do it. Or you could use a conditional to toggle printing the output. -mtw On Wed, May 03, 2006 at 05:35:04PM +0100, Matthew Webber ([EMAIL PROTECTED]) wrote: > This has got to be trivial, but I can't find the answer ... I want to stop > execution of my main script half way through. This is just for debugging - > the code in the bottom half of the script generates a whole lot of output > that I don't want. Inserting "break" or "return" doesn't work, but something > like that is what I had in mind. > > I'm running under ipython on windows, FWIW. > > Thanks > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Linux] open a file in any home "~" ?
os.getenv('HOME') will return the user's home directory as long as that environment variable is set. you can also use the pwd module: >>> pwd.getpwnam('mtw') ('mtw', 'x', 1000, 1000, ',,,', '/home/mtw', '/bin/bash') -mtw On Wed, Apr 19, 2006 at 07:55:14PM +0200, learner404 ([EMAIL PROTECTED]) wrote: > Hello, > > I want to read a configuration file from a small python app (user > preferences). > > The ".myapp.conf" is in the home folder of the user. > > if I do: > > f=open("/home/user1/.myapp.conf","r") #it works > > obviously I won't know the home user folder name then I wanted to use: > > f=open("~/.myapp.conf","r") # but it returns a IOError: [Errno 2] No such > file or directory: > > How can I do to access this file whatever the user is ? > > Thanks for your help. > > --- > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOPs Concept
On Wed, Apr 19, 2006 at 09:10:41PM +0530, Kaushal Shriyan ([EMAIL PROTECTED]) wrote: > Thanks Matthew > Just wanted to know > x.count('l') -> 2 Here 2 means what I didnot understood this > and also does x is a object and capitalize(), swapcase() and > count('l') are methods, is that correct what i understand yes, count(), capitalize(), and swapcase() are called methods. The count() method counts the number of the given string in the object. x = 'hello' x.count('l') -> 2 x.count('h') -> 1 y = 'good morning' y.count('o') -> 3 y.count('oo')-> 1 you can find out which methods belong to an object using the dir() function and can get help for a method by using the help() function: % python Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 'hello' >>> dir(x) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> help(x.swapcase) Help on built-in function swapcase: swapcase(...) S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. >>> -mtw -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOPs Concept
Even though I am still new to python, I've recently had an insight as to what makes OOP different from procedural programming. Let's take perl for example. A variable in perl is like a bowl. It's an empty vessel you can put things in. You can change the contents of the bowl, you can empty the bowl but it doesn't really *do* anything. It has no real attributes aside from the fact that it's a container. So when I create a variable in perl it looks like this: $x = 'hello' If I want to make the first letter of the value of $x a capital letter, I have to use a function to do it: $y = ucfirst($x) now $y contains the value 'Hello' In python one doesn't really create variables, one creates objects. Sring objects, list objects, etc. And objects are cool because they can do things. They are more than just merely bowls, they are like swiss army knives. So in python, if I say: x = 'hello' Then I can do all sorts of things with x: x.capitalize() -> 'Hello' x.swapcase() -> 'HELLO' x.count('l') -> 2 This is just a very small example but I hope that my example can help you understand what objects are what makes OOP different from procedural programming. -mtw On Wed, Apr 19, 2006 at 06:07:27PM +0530, Kaushal Shriyan ([EMAIL PROTECTED]) wrote: > Hi All > > I wanted to understand about OOPs Concept in Python in a easy way, > Please explain me with an example > > I have been reading http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm > but at the moment still the concept is not clear > > Thanks in Advance > > Regards > > Kaushal > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about list
Hi Hoffman, It is often useful to use the "for" construct to process items in a list. e.g.: >>> list1 = [ 'spam!', 2, ['Ted', 'Rock']] >>> for item in list: ...print item spam! 2 ['Ted', 'Rock'] If you pass a list to the len() function, it will return the number of elenents in the list. e.g.: >>> x = ['a', 'b', 'c'] >>> len(x) 3 Now if you pass len() a string it will return the length of a string: >>> y = 'hello' >>> len(y) 5 Given your list below, len() will return what you're looking for when it encounters the third element of the list, but won't for the first and second elements. One way to solve this problem is to use the type() function to figure out if your item is a string or list and use len() as appropriate. I hope this provides enough of a hint. -mtw On Mon, Apr 10, 2006 at 03:29:23PM -0700, Hoffmann ([EMAIL PROTECTED]) wrote: > Hello, > > I have a list: list1 = [ 'spam!', 2, ['Ted', 'Rock'] > ] > and I wrote the script below: > > i = 0 > while i < len(list1): > print list1[i] > i += 1 > > Ok. This script will generate as the output each > element of the original list, one per line: > > spam! > 2 > ['Ted', 'Rock'] > > I also would like to print the length of each element > of that list: > > spam! = 1 element > 2 = 1 element > ['Ted', 'Rock'] = 2 elements > > Could anyone, please, give me some hints? > Thanks, > Hoffmann > > > __ > 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 -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Space the final frontier!
Hi John, It would be easier to do all of your whitespace elimination before you append the string to your list(s). Something like this I should get you started: for line in input.readlines(): line = re.sub('[\s]+', '', line) listy.append(line) print listy bonus points for appending the return from re.sub to your list. :) -mtw On Tue, Apr 04, 2006 at 10:33:18PM +0100, John Corry ([EMAIL PROTECTED]) wrote: > Dear All, > > I am having difficulty removing white spaces from my file. The file is 999 > lines long and looks like the sample below: > > 001, new field,dial= 028 90 79 0154, dial= > 002, borfiled, dial= 02890 618521, dial= > 003, newcomp, dial=02890419689, dial= > > The program, I am using to import the file does not like the spaces around > the numbers. The number should look like the "dial=02890419689" in the > third line. Thus the sample above should look like: > > 001,newfield,dial=02890790154,dial= > 002,borfiled,dial=02890618521,dial= > 003,newcomp,dial=02890419689,dial= > > I have searched the tutor mailbag already and have picked up some good tips > on join, split and re but I can't seem to get it to work. > > I am using the following code. > > filename = "c:/test.txt" > import string > import os > import re > listy = [] > input = open( filename, 'r') #read access > for line in input.readlines(): > y = line > listy.append(y) > print listy > x = listy.pop() > > re.sub(r'\s', '', x) > print y,x > > del input > > It produces the output: > > ['001, new field,dial= 028 90 79 0154, dial=\n'] > 001, new field,dial= 028 90 79 0154, dial= > 001, new field,dial= 028 90 79 0154, dial= > > ['002, borfiled, dial= 02890 618521, dial=\n'] > 002, borfiled, dial= 02890 618521, dial= > 002, borfiled, dial= 02890 618521, dial= > > ['003, newcomp, dial=02890419689, dial='] > 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial= > > Any help would be greatly appreciated. > > Regards, > > John. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] for loops and exceptions
Hello, >From a general style and/or programmatic perspective, which is a "better" way to write this bit of code? try: (dn, attrs) = conn.search_s(search_base, search_scope, search_filter, search_attrs): except Exception, e: warn_the_user(e) do_something_useful() for (name, data) in (dn, attrs): print '%s' % (name) for key, value in data.iteritems(): print '%s => %s' % (key, value) OR try: for dn, attrs in conn.search_s(search_base, search_scope, search_filter, search_attrs): print dn for key, value in attrs.iteritems(): print '\t%s => %s' % (key, value) print except Exception, e: warn_the_user(e) do_something_useful Personally I like the second method more. To my eyes it is compact and efficient. Coming from a perl background I tend to like to get very compact, which can be an impediment to code readability. As I get started with python I want to make sure that I don't repeat the same mistakes and let too many perl-isms creep into my python code. -mtw -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is wrong my code?
Hi Hoffman, Include the definition for hypotenuse() before it is called in your script. Also, please include the full output from the error next time. It helps with figuring out the exact problem. :) -mtw On Fri, Mar 24, 2006 at 01:02:45PM -0800, Hoffmann ([EMAIL PROTECTED]) wrote: > Hello: > > Could anyone, please, let me know what is wrong with > my code (shown below)? I am getting a runtime error. > Thanks! > Hoffmann > ps: The code: > > #!/usr/bin/python > > import math > > print '''This program calculates the lenght of the > hypotenuse of a right triangle > given the lenghts of the two legs as > parameters.\n''' > > leg1 = raw_input('Enter the first leg of the triangle: > ') > leg2 = raw_input('Enter the second leg of the > triangle: ') > > result = hypotenuse(leg1, leg2) > > print 'The hypotenuse of the triangle is', result > > def hypotenuse(x, y): > result = math.sqrt(x**2 + y**2) > return result > > __ > 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 -- Matthew White - District Systems Administrator Tigard/Tualatin School District 503.431.4128 "The greatest thing in this world is not so much where we are, but in what direction we are moving." -Oliver Wendell Holmes ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor