Re: [Tutor] counting no of words
Sure, What you need are the win32 extensions for python (http://starship.python.net/crew/mhammond/win32/Downloads.html), which contain win32com. Through com, you can access almost anything in windows. Check out http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/html/com/win32com/HTML/QuickStartClientCom.html for a short com tutorial, and http://starship.python.net/crew/pirx/spam7/ for a presentation on com in python. Once you're connected to a word document, you'll have to figure out what the command to count the words in the document is, but that's just a matter of recording a macro in word where you count the words, then repeating it in python. I'd help you with that, but I'm on linux. Peace Bill Mill bill.mill at gmail.com On Thu, 20 Jan 2005 16:37:06 +0530, Gopinath V, ASDC Chennai <[EMAIL PROTECTED]> wrote: > > > hi all, > > Is it possible to write a program in python to calculate the number of > words in a MS-Word document Page > Regards > gopi > ___ > 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] Ooer, OT Lisp
Liam, On Fri, 21 Jan 2005 15:46:19 +1300, Liam Clarke <[EMAIL PROTECTED]> wrote: > Oops, > > and OT ~ Has anyone used Lisp? I've been reading Paul Graham's essays > on how great Lisp is, and how Python is near to implementing features > Lisp had in the 60's. Also found the concept of macros interesting. > > Queries - > > 1) Anyone here familiar with both? I used Lisp at school, so my answers should be taken with a whole bag of salt, but I kind of dug it. > 2) If so, which would you rate as more powerful? Lisp. No question - if it can be done, it can be done in lisp. With that power comes a price, though - lisp is nowhere near as intuitive as Python. Lispers won't agree (of course) but I am really and truly convinced that it's true. At the time I learned lisp, I didn't know too much python, so I don't think I was that biased either. > 3) What's with all those parentheses? They stop bothering you after a while. Use a good editor in a lisp setting, and there's no worries. Many will highlight matching parens, which helps out. > 4) Perhaps the powerful question's a bit vague, how about ease of > use? I like that the simplest Lisp expression is - , but those > brackets Once you wrap your head around lisp, it's not too hard to use. You just have to think in a different way - recursion is good, variable declarations are bad. Every s-expression starts with a function unless you say otherwise. There is no "standard" implementation of lisp, so sockets and os access all vary by implementation. Furthermore, the docs are sketchy and hard to read with all of the lisps I've tried. The one I liked most was allegro common lisp (http://www.franz.com/), but I'm very far from a power user. > 5) Are you able to point me towards a simplified explanation of how > the 'syntaxless' language can write programmes? > Hmmm, not sure what you're getting at here. Lisp isn't syntaxless, it just has a really simple syntax with little sugar. Here's pseudo-lisp (no interpreter handy) for a factorial function: (defun fact (n) (cond ((= n 0) 1) (t (* n (fact (- n 1)) Which translates into the Python: def fact(n): if n == 0: return 1 else: return n * fact(n-1) Unless otherwise specified, everything in lisp takes the form (function arguments); many things that are syntax in python are functions in lisp. Also, you should know that lisp pioneered the interactive interpreter; python got that idea from lisp. This makes it much easer to experiment in lisp. > Sorry to play 20 questions. No worries. I found the site at http://www.lisp.org/alu/home to be very helpful when I was digging around lisp-world. If you have any more questions, I'll try to help you out, but you might want to ask some more knowledgeable persons. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cluster algorithms
Kumar, On Wed, 26 Jan 2005 22:35:59 -0800 (PST), kumar s <[EMAIL PROTECTED]> wrote: > Hi: > > I am still trying to learn the OOPs side of python. > however, things/circumstances dont seems to stop until > I finish my practise and attaing higher understanding. > may be, i am being pushed by circumstances into the > stream and i am being tested if I can swim efficiently > while I struggle with basic steps of swimming. The > 100% analogy my perspective of learning python :-) > > I have a couple of questions to ask tutors: > > Are there any example programs depicting Clustering > algorithms such as agglomerative, complete link, > partional , squared error clustering, k-means or > clustering algos based on Neural networks or genetic > algorithm. although I just learned python, (to major > extent in programming also), I need to apply some of > these algos to my data. Any > suggestions/recommendations? > I wrote a tutorial on using perceptrons, and gave python sample code in the article. You can see the article at http://www.kuro5hin.org/story/2003/11/11/17383/475 . Perceptrons probably aren't *useful* to you in sorting your data, but the code should provide some insight into how you can do classification in python. Python is excellent for data mining and classification, thanks to the excellent numarray module as well as the ipython shell and several visualization libraries. I use it in place of Maple, Mathematica, Matlab, or some other specialized mathematics package. > Do I have to know to code well using OOP methods to > apply these algorithms? > I call some methods on matrix objects in the tutorial, but don't use any OOP. In fact, I often find that strict OOP is not so useful for numerical algorithms, where your code will often have to be optimized for speed. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unique Items in Lists
Srinivas, You can't sort a string, since it's immutable. You can, however, sort a list. To sort your table by the third element, you can do something like this: >>> table = (("apple", "fruit", "denmark"), ... ("mummy", "antique", "egypt"), ... ("taj", "wonder", "india"), ... ("f-16", "fighter", "usa")) >>> sorter = [(elt[2], elt) for elt in table] >>> sorter.sort() >>> tuple([elt[1] for elt in sorter]) (('apple', 'fruit', 'denmark'), ('mummy', 'antique', 'egypt'), ('taj', 'wonder', 'india'), ('f-16', 'fighter', 'usa')) # I edited the table output edited for clarity When you sort a list of tuples, the default is to sort the list by the first element in the tuples. If you make a list where the element you want to sort on is first in all of the tuples (see the 'sorter = ...' line), then sort that list, then remove the element you added (the 'tuple([...])' line), you are left with a list which is ordered the way you want it. Peace Bill Mill bill.mill at gmail.com On Thu, 27 Jan 2005 08:29:10 -0800 (PST), Srinivas Iyyer <[EMAIL PROTECTED]> wrote: > Dear Danny, thank you for ur help. But a basic > question ? > > In a table, more specifically a matrix 3X3, > > AppleFruitDenmark > F-16 Fighter USA > Taj Wonder India > MummyAntique Egypt > > IF I have to sort on country, it should be > > AppleFruitDenmark > MummyAntique Egypt > Taj Wonder India > F-16 Fighter USA > > How can I sort by binding Denmark to fruit and apple > as a string. String does not support sort function. > Sincerly I dont know how to sort to follow your > suggestion. can you please help.. sorry for asking > basic question. > > thank you > > > --- Danny Yoo <[EMAIL PROTECTED]> wrote: > > > > > > > On Wed, 26 Jan 2005, Srinivas Iyyer wrote: > > > > > I have a list with 4 columns and column1 elements > > are unique. I wanted > > > to extract unique elements in column3 and and > > place the other elements > > > of the column along with unique elements in column > > 4 as a tab delim > > > text. > > > > > > Table: > > > > > > col1col2col3 col4 > > > A Apple 5Chennai > > > B Baby 11Delhi > > > I Baby* 1Delhi > > > M Dasheri+ 5Mumbai > > > K Apple 12 Copenhagen > > > > > > [Meta: we seem to be getting a run of similar > > questions this week. Scott > > Melnyk also asked about grouping similar records > > together: > > > http://mail.python.org/pipermail/tutor/2005-January/035185.html.] > > > > > > Hi Srinivas, > > > > I see that you are trying to group records based on > > some criterion. You > > may find the problem easier to do if you fist do a > > sort on that criterion > > column: that will make related records "clump" > > together. > > > > > > For your sample data above, if we sort against the > > second column, the > > records will end up in the following order: > > > > ### > > A Apple 5Chennai > > K Apple 12 Copenhagen > > B Baby 11 Delhi > > I Baby 1Delhi > > M Dasheri 5Mumbai > > ### > > > > > > In this sorting approach, you can then run through > > the sorted list in > > order. Since all the related elements should be > > adjacent, grouping > > related lines together should be much easier, and > > you should be able to > > produce the final output: > > > > ### > > Apple A,K 5,12Chennai,Copenhagen > > Baby B,I 1,11Delhi > > Dasheri M 5 Mumbai > > ### > > > > without too much trouble. You can do this problem > > without dictionaries at > > all, although you may find the dictionary approach a > > little easier to > > implement. > > > > > > > > > > > A dictionary option does not work > > > > A dictionary approach is also very possible. The > > thing you may be stuck > > on is trying to make a key associate with multiple > > values. Most examples > > of dictionaries in tutorials use strings as both the > > keys and valu
Re: [Tutor] Safely buffering user input
Miles, On Thu, 27 Jan 2005 13:08:05 -0500, Miles Stevenson <[EMAIL PROTECTED]> wrote: > Newbie question. > > I'm trying to practice safe coding techniques. I just want to make sure that a > user can't supply a massive argument to my script and cause trouble. I'm just > trying only accept about 256 bytes: > > buffer(sys.argv[1], 0, 256) > searchpath = sys.argv[1] I've never used buffer(); in fact, I didn't even know it existed, and I've been using python for a while now. Instead of using buffer, just do: sys.argv[1] = sys.argv[1][:255] This says "Set the second element of sys.argv equal to its first 256 characters". Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Comparing files, Counting Value
Michiyo, When you ask a question to the list, you should be more careful to highlight your problem so that it doesn't seem like you're asking people to write a script for you. I don't think that's what you were doing, but just try to reduce your problem to a minimal example in the future. I don't know what your script is doing; array[0, 2] is not legal as far as I know in python (it is legal on numarray.array types, but not on regular python lists AFAIK). I also don't know what that "in i" stuff you're doing means. When I run your code, I get a "TypeError: list indices must be integers" on the fields[0, 1] line. You should try to write your code in small bites to make it easier to debug. That said, I dig doing this sort of text processing, so I wrote my own script to do it. Perhaps it'll help clear up some ideas for you; if you have any questions, feel free to ask me about them: ==begin file testprocess.py= one = open('one') two = open('two') out = open('out', 'w') THRESHOLD = .05 #build dict of {(x,y): z} from 'one' pts = {} for line in one: x, y, z = [float(i) for i in line.split()] #convert strings to floats pts[(x,y)] = z #insert point into dictionary #now check to find each pixel in 'two' in the pts dictionary bigpixels = 0 for line in two: x, y = [float(i) for i in line.split()] #convert strings to floats if (x,y) in pts and pts[(x,y)] > THRESHOLD: bigpixels += 1 print "%d pixels over %f" % (bigpixels, THRESHOLD) end file== Peace Bill Mill bill.mill at gmail.com On Mon, 31 Jan 2005 15:27:24 -0800, Michiyo LaBerge <[EMAIL PROTECTED]> wrote: > Hello all, > > I'm very new to Python and have been trying to write a script to > compare data from 2 files and getting a total. One of the two files > contains x, y positions of pixels and a color value(z) of each, so it > has three columns in the file. The other file has two columns; x1, y1. > I'd like to get only x, y positions which match to x1, y1 of the second > file and then look up the z value. If the z value is greater than a > certain number, it counts 1, otherwise it moves on the next x, y > position. Finally, I'm able to get total count of the pixels that are > over the threshold. The script I'm using is below step by step, > however, I haven't been able to figure out the error massage > "IndexError: list index out of range" on z value. Any comments would be > appreciated! > > Regards, > Michiyo > > file 1: file 2: > 299 189 8.543e-02260 > 168 > 300 189 0.000e+00270 > 180 > 301 189 0.000e+00299 > 189 > 302 189 0.000e+00300 > 170 >0188 5.095e-02 301 > 189 >1188 5.108e-02 . > . >.. . > . . >.. . > .. > > #!usr/local/bin/python > > import sys > > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result > > results={} > > line=i.readline() > line=o.readline() > > while line: > fields=line.split() > x1=fields[0, 1] in i#x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 > > if x1 == x2: > read(z) > > if z >= 5.000e-02: >z=1 >count(n=0) >print>>l, count(1) > > i.close() > o.close() > l.close() > > ___ > 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] Re: Are you allowed to shoot camels? [kinda OT]
On Thu, 3 Feb 2005 04:24:06 -0500, Patrick Hall <[EMAIL PROTECTED]> wrote: > > Beware! Overcome the temptation! > > Try this: http://kodos.sourceforge.net/ > > While I have no problem personally with Perl or PHP, I'll second the > recommendation for kodos -- it's very useful for learning to use > regexes in Python. Ok, I have to ask: why? Whenever I write and debug regexes (as I had to do this morning for the first time in a while - I try to avoid them) I always create a function in the interpreter that looks like: def test(regex, line): print re.compile(regex).match(line).groups() and then test my regexes incrementally: >>>l = '8 this is my line to test' >>> test('^\s*(\d)+', l) until I have it right. How is using this tool easier than that? Peace Bill Mill bill.mill at gmail.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] Hex to Str - still an open issue
Tamm, Try searching before you get snippy on a group where people are helping you for free. This question gets asked a lot, and the answer can be found all over the place. A particularly comprehensive thread discussing the issue can be found at http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/bdd85f1d1298a191 . Peace Bill Mill bill.mill at gmail.com On Fri, 4 Feb 2005 15:11:00 +0100, Tamm, Heiko <[EMAIL PROTECTED]> wrote: > > > Ok, thank you. > > Does anybody know how to convert a HEX into a BINARY? > > Best regards > > > Heiko > > -Original Message- > From: Pierre Barbier de Reuille [mailto:[EMAIL PROTECTED] > Sent: Friday, February 04, 2005 2:55 PM > To: Tamm, Heiko > Subject: Re: [Tutor] Hex to Str - still an open issue > > Oh ! You meant the other way around ? > > If you have a string with an Hex number in it it's very easy : > > a = int("F04", 16) > > you can replace "16" with every base you want :) > > After that, to get an octal representation : > > "%o" % a > > But I don't know for binary representation ... nor for any other base :( > That's somthing missing I think ! > > Pierre > > Tamm, Heiko a écrit : > > Thank you, Pierre, > > > > But I'm looking for a solution to convert a Hex number into binary, > > decimal, interger numbers. > > > > E.g.: > > > > What is the the binary value of the hex number 1F4. > > > > Is there a function available, or how can it be done? > > > > > > > > Kind regards and a nice weekend > > > > Heiko > > > > > > > > -Original Message- > > From: Pierre Barbier de Reuille [mailto:[EMAIL PROTECTED] > > Sent: Friday, February 04, 2005 2:35 PM > > To: Tamm, Heiko > > Cc: tutor@python.org > > Subject: Re: [Tutor] Hex to Str > > > > Given you have a number in 'a' : > > > > hex(a) > > > > returns the hexadecimal representation of 'a' as a string ! > > You can also try : > > > > "%x" % a > > > > After that, I don't know if there is some builtin to print a number in any > > base you want ! > > > > Pierre > > > > Tamm, Heiko a écrit : > > > >>Hello, > >> > >>I like to know, if it's possible to convert a Hex number into String > >>or other formats? > >> > >>How can it be done? > >> > >> > >>Kind regards > >> > >> Heiko > >> > >> > >> > >>-- > >>-- > >> > >>___ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > > Pierre Barbier de Reuille > > > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de > > la Lironde > > 34398 MONTPELLIER CEDEX 5, France > > > > tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 > > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la > Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 > ___ > 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] Perl Symbology (was: Are you allowed to shoot camels?)
Jeff, I get the impression that many pythonistas don't like string interpolation. I've never seen a clear definition of why. Anyway, it's easy enough to add with the Itpl [1] module: >>> import Itpl, sys >>> sys.stdout = Itpl.filter() >>> s, n, r = 0, 0, 0 >>> print "$s $n $r" 0 0 0 >>> x = Itpl.itpl("$s $n $r") >>> x '0 0 0' And, of course, you can give Itpl.itpl a nicer name; I usually call it pp(). If you don't need to change the behavior of the "print" statement, then you don't need the Itpl.filter() line. [1] http://lfw.org/python/Itpl.py Peace Bill Mill bill.mill at gmail.com On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote: > To all those who talked about hating the symbology in Perl and the > suggestion that it should be removed from a later version. I just > remembered what you get for that symbology that I really do like about > Perl: variable interpolation in strings: > > C: > sprintf(newstr,"%s %d %f",s,n,r); > > Becomes a little nicer in Python with: > newstr = '%s %d %f' % (s,n,r) > > Although it's worse with: > newstr = s + ' ' + str(n) + ' ' + str(r) > > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; > > for clarity, ease of use, and maintainability. > > Jeff > > ___ > 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] Perl Symbology (was: Are you allowed to shoot camels?)
Sorry for the double post; I forgot one thing: On Thu, 10 Feb 2005 10:43:28 -0500, Bill Mill <[EMAIL PROTECTED]> wrote: > Jeff, > > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. Anyway, it's > easy enough to add with the Itpl [1] module: > > >>> import Itpl, sys > >>> sys.stdout = Itpl.filter() > >>> s, n, r = 0, 0, 0 > >>> print "$s $n $r" > 0 0 0 > >>> x = Itpl.itpl("$s $n $r") > >>> x > '0 0 0' > This works with arbitrary data types too, to be truer to your example: >>> s, n, r = '0', 12, 3.4 >>> x = Itpl.itpl("$s $n $r") >>> x '0 12 3.4' Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Perl Symbology
On Thu, 10 Feb 2005 18:22:30 +0100, Abel Daniel <[EMAIL PROTECTED]> wrote: > Bill Mill writes: > > > I get the impression that many pythonistas don't like string > > interpolation. I've never seen a clear definition of why. > >From "import this": > > Explicit is better than implicit. > > And doesn't perl's method mean that you have to escape _every_ > _single_ '$' in strings? I think having to escape '\' is bad enough. Abel, You've provided me with what is approximately the eleventy-seventh explanation I've gotten as to why string interpolation is bad. I don't think that any of them are "stupid", per se, but neither do I think that any of them are strong enough to be convincing. In my perfect language, string interpolation would be on by default. That said, there are enough reasons to think that it's a bad idea that it is warranted to avoid turning it on by default. I don't mind typing pp("interpolate $mystring"), and although I do wish python standardized it before version 2.4 [1], I hardly even feel that it's a wart in the language. I just wanted to tell the person who wanted string interpolation that it's easy to add into the language and easy to use. One should not take python out of consideration if one feels that string interpolation is a killer feature. Peace Bill Mill bill.mill at gmail.com [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?)
On Thu, 10 Feb 2005 19:28:26 -, Alan Gauld <[EMAIL PROTECTED]> wrote: > > Although it's worse with: > > newstr = s + ' ' + str(n) + ' ' + str(r) > > You could try: > > newstr = s + ' ' + `n` + ' ' + `r` > > if you think thats better. > But `` is different to str() for some types. > > Personally I prefer the formatting approach. > > > But in my mind nothing beats the Perl statement: > > newstr = "$s $n $r"; > > Perl is king of string processing in modern scripting, > without a doubt. But even here the $ prefix could have > been used for that specific purpose without insisting > it be used everywhere else! > > BTW Anyone recall how Ruby does this? I don't know ruby at all, but a quick google and 30 interpreter seconds later: irb(main):001:0> x = 12 => 12 irb(main):002:0> '$x' => "$x" irb(main):003:0> "$x" => "$x" irb(main):004:0> "#{$x}" => "" irb(main):005:0> "#{x}" => "12" irb(main):006:0> '#{x}' => "#{x}" so "#{} . Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Perl Symbology
Kent, On Thu, 10 Feb 2005 13:43:21 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote: > Python 2.4 includes a string.Template class which does much the same thing as > Itpl.itpl(): > > >>> from string import Template > >>> s, n, r = '0', 12, 3.4 > >>> x = Template("$s $n $r") > >>> x.substitute(locals()) > '0 12 3.4' > > If you want to bundle this up in a pp() function you have to do some magic to > get the locals() of > the caller. This seems to work: > > >>> import sys > >>> def pp(s): > ... loc = sys._getframe(1).f_locals > ... print Template(s).substitute(loc) > ... > >>> pp("$s $n $r") > 0 12 3.4 > I just didn't want to give an answer that only works in python 2.4, and one furthermore which I have not tested. You can also find a recipe to make pp() easy to make at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 . This function may or may not be better than yours; I haven't used either. the Itpl module has worked fine for me (and for the author of ipython) for quite a while. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple question on creating a filter
On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff <[EMAIL PROTECTED]> wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > No worries; that's what this list is for. > I want to write a simple line selection filter that could be used like: > > filter < file > > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } > > I've tried what I thought would be the Python equivalent but it doesn't > work: > > for line in sys.stdin: > if line meets selection criteria: > print line > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor > I'm not quite sure how you're getting that "bad file dscriptor" error. My code, also on windows (and cygwin) with python2.4: /d/code/python$ cat test.py import sys for line in sys.stdin: if line.startswith('a'): print line.strip() /d/code/python$ cat test_in aline1 bline2 aline3 cline4 /d/code/python$ python test.py < test_in aline1 aline3 Try to run it like I did, and let me know if it gives you the same thing; that'll give us a common point of reference. Peace Bll Mill bill.mill at gmail.com > This is with Python 2.4 on Windows. > > Jeff > ___ > 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] Might be a silly question!
Jeff, On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland <[EMAIL PROTECTED]> wrote: > > Hello all, > > I am drawing a blank right now and can't seem to find anything on it and I > am sure this issue has been addressed before, so here is the question. > > Can and if you can how do you set a variable as a constant? > > Example of what I mean: (this is loose and not python since variable type > declaration is not needed in python) > > CONST int gamma = 5 > > This would mean in my little mind that the variable gamma which is an > integer of 5 can not be changed in the code and would throw an error if you > tried. Just wondering if there is a way of doing this in Python. There is no real way to guarantee this in Python. > This is > just to clear this up in my mind it means nothing to my code since the way I > write variable names any variable I want to remain unchanged I use caps to > help distinguish easily. Constants are enforced by convention in Python. Any variable with a name in ALL CAPS is considered to be a constant, and it is considered bad programming style to change it. While it sounds like a weak system, and I'm sure there have been problems with it, I've never heard of one. Remember to only import the names you need from the classes you import, and you should be fine. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] count words
Ron, is there a way to do it so > that I get a individual count of each word: > > word1 xxx > word2 xxx > words xxx > > etc. Ron, I'm gonna throw some untested code at you. Let me know if you understand it or not: word_counts = {} for line in f: for word in line.split(): if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 for word in word_counts: print "%s %d" % (word, word_counts[word]) Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] count words
On Tue, 15 Feb 2005 18:03:57 +, Max Noel <[EMAIL PROTECTED]> wrote: > > On Feb 15, 2005, at 17:19, Ron Nixon wrote: > > > Thanks to everyone who replied to my post. All of your > > suggestions seem to work. My thanks > > > > Ron > > Watch out, though, for all of this to work flawlessly you first have > to remove all punctuation (either with regexes or with multiple > foo.replace('[symbol]', '')), and to remove the case of each word > (foo.upper() or foo.lower() will do). To remove all punctuation from the beginning and end of words, at least in 2.4, you can just use: word.strip('.!?\n\t ') plus any other characters that you'd like to strip. In action: >>> word = "?testing..!.\n\t " >>> word.strip('?.!\n\t ') 'testing' Peace Bill Mill bill.mill at gmail.com > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > ___ > 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] count words
Coupla nits: On Tue, 15 Feb 2005 14:39:30 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote: > from string import punctuation > from time import time > > > words = open(r'D:\Personal\Tutor\ArtOfWar.txt').read().split() Another advantage of the first method is that it allows a more elegant word counting algorithm if you choose not to read the entire file into memory. It's a better general practice to consume lines from a file via the "for line in f" idiom. > words = [ word.strip(punctuation) for word in words ] And, be careful with this - punctuation does not include whitespace characters. Although that is no problem in this example, because split() strips its component strings automatically, people should be aware that punctuation won't work on strings that haven't had their whitespace stripped. Otherwise though, good stuff. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic terminology
A remainder is what's left over after a division: 10/3 = 3 remainder 1 12/5 = 2 remainder 2 27/3 = 9 remainder 0 and the modulus operator (which is % in python) gives you that remainder: 10%3 = 1 12%5 = 2 27%3 = 0 See http://mathworld.wolfram.com/Remainder.html and http://mathworld.wolfram.com/Modulus.html for more formal explanations. In particular, it explains some deeper meanings of the word "modulus". Once you get into group theory, it can start to mean some related but different things. Peace Bill Mill bill.mill at gmail.com On Tue, 15 Feb 2005 16:16:44 -0500, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I'm reading a Python book right now (Learning Python, a great book!), and > there > are few terms that come are brought up a few times but without any > explanation. > > So what are: > - "remainders" (in the context of remainders-of-division modulus for numbers) > - "modulus" (in the same context; I have also seen it in different context, > like > 3D graphics programs to perform certain types of calculations). > > Thanks > Bernard > ___ > 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] Basic terminology
On Tue, 15 Feb 2005 14:26:52 -0800 (PST), Da > > Hi Bernard, > > Another familiar example of modulo is checking to see if a number is even > or odd: > Since Danny got it started with the examples, I'll give another canonical example of the use of the modulus operator. Imagine that we're trying to figure out what number the hour hand of a clock will be pointing at x hours from now. If it's one o'clock right now, in 5 hours, the hour hand will be pointing at the six, and in 10 hours, it will be pointing at the 11. However, where will it be pointing in 16 hours? Well, in 12 hours it will be at the one, then four more hours later it will be pointing at the five. This can be represented as: 1 + (16 % 12) = 1 + 4 = 5 In general, the hour at some point in the future will be: (start time) + (hours in the future % 12) Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Basic terminology
On Wed, 16 Feb 2005 11:34:55 +0100, Roel Schroeven <[EMAIL PROTECTED]> wrote: > Bill Mill wrote: > > However, where will it be pointing in 16 hours? Well, in 12 hours it > > will be at the one, then four more hours later it will be pointing at > > the five. This can be represented as: > > > > 1 + (16 % 12) = 1 + 4 = 5 > > Correcter is > > (1 + 16) % 12 = 17 % 12 = 5 d'oh! thanks for the correction. > > > In general, the hour at some point in the future will be: > > > > (start time) + (hours in the future % 12) > > (start time + hours in the future) % 12 > Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help needed with script to batch-create shapefiles
Chris, On Wed, 16 Feb 2005 21:37:10 +, Chris Bromley <[EMAIL PROTECTED]> wrote: > Dear all, > > I have several thousand files in dBaseIV format that I need to convert to > shapefiles for use in ArcGIS. I've written a script (see below) to automate > this process but thus far have been unable to get it to work. I suspect that > there's a simple reason for this, but I'm a complete novice with Python and > have been unable to find it. > > Any help would be greatly appreciated! > > Regards, > > Chris Bromley What you've written translates, in newsgroup-speak, to "Will somebody write this script for me that I need?" Boil your question down into something smaller, and then ask it with the appropriate information. I suggest reading http://www.catb.org/~esr/faqs/smart-questions.html . Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Active Python
On Fri, 18 Feb 2005 17:20:03 -0800 (PST), Terry Carroll <[EMAIL PROTECTED]> wrote: > On Thu, 17 Feb 2005, Jeff Shannon wrote: > > > On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <[EMAIL PROTECTED]> > > wrote: > > > > Interesting -- I prefer the CHM (Windows helpfile), because it's > > internally indexed. I feel that the internal search is more > > convenient than external searches would be. But I suppose that > > there's room for reasonable people to disagree, here. :) > > Sure, and I'd expect I'm in the minority. > > I use Agent Ransack for searching files on my system. I do a search for, > for example, a filename of html$ containing the word "socket" and can get > a pretty good look at what I'm looking for. > > I'll bet that the CHM file can do that at least as well, but since > I use Agent Ransack for all my document searches (Python-related or > otherwise), it's most convenient for me use one consistent mechanism. > > I'll tell you, if Google desktop had a way of limiting searches to > specific directories, I'd be in heaven. > How do you live without cygwin? Just 'cd' to the directory and 'grep -r' to search through it. It's the first thing I install on a windows box, even before python. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] killing a thread
If I recall correctly, there is not a direct way. Instead, you're going to want to have your worker thread check a queue it shares with the parent every so often to see if the supervisor thread has sent a "quit" message to it. Peace Bill Mill bill.mill at gmail.com On Tue, 22 Feb 2005 14:23:17 -0800 (PST), Shitiz Bansal <[EMAIL PROTECTED]> wrote: > Hi, > > Is there a way to terminate a thread from another > thread? > > Shitiz > > __ > 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] Print text position problems when using triple quotes
On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <[EMAIL PROTECTED]> wrote: > Hi all, > > I've tried a lot of experimenting and searching through various > tutorials, and I haven't been able to come up with a solution to this, > ostensibly simple, problem. > > I'm writing a simple game (run in command line) in which narrative > text is printed in response to a user's decisions. The problem I'm > running into is that triple quotes used in an indented block preserves > the indentation when it prints. I'm writing code like this: > > if userInput == 1: > some stuff > print """ > texttexttexttexttexttexttexttext > """ > question within a question > if userInput == 1: > print """ > texttexttexttexttexttexttexttext > texttexttexttexttexttexttexttext > """ > elif userInput == 2: > print """ > owowowowowowowowowowow > """ > > to preserve the text's position at left when I run it in the > command-line. The blocks get distorted and it becomes painful to read. > > Is there a way to preserve the readability of the code and have > printed text from indented blocks, say, nested conditionals, appear > flush at left, not printed exactly where I've written them in the > script? Why not just take them out of the block, and either make them global to the module or create a string module? i.e.: prompt1 = """This is a long string with %s string variables %s scattered all over the place as well as odd indentation %s and funny lines -- """ class foo: def bar(self): print prompt1 % (var1, var2, var3) peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print text position problems when using triple quotes
On Thu, 24 Feb 2005 13:14:13 -0500, Bill Mill <[EMAIL PROTECTED]> wrote: > On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <[EMAIL PROTECTED]> wrote: > > Hi all, > > > > I've tried a lot of experimenting and searching through various > > tutorials, and I haven't been able to come up with a solution to this, > > ostensibly simple, problem. > > > > I'm writing a simple game (run in command line) in which narrative > > text is printed in response to a user's decisions. The problem I'm > > running into is that triple quotes used in an indented block preserves > > the indentation when it prints. I'm writing code like this: > > > > if userInput == 1: > > some stuff > > print """ > > texttexttexttexttexttexttexttext > > """ > > question within a question > > if userInput == 1: > > print """ > > texttexttexttexttexttexttexttext > > texttexttexttexttexttexttexttext > > """ > > elif userInput == 2: > > print """ > > owowowowowowowowowowow > > """ > > > > to preserve the text's position at left when I run it in the > > command-line. The blocks get distorted and it becomes painful to read. > > > > Is there a way to preserve the readability of the code and have > > printed text from indented blocks, say, nested conditionals, appear > > flush at left, not printed exactly where I've written them in the > > script? > > Why not just take them out of the block, and either make them global > to the module or create a string module? i.e.: > > prompt1 = """This is a long string with %s string variables > %s scattered all over the place > as well as odd indentation %s > and funny lines >-- >""" > > class foo: > def bar(self): Sorry, I forgot that if it's in the module, you should declare prompt1 as global by using "global prompt1" right here. > print prompt1 % (var1, var2, var3) > > peace > Bill Mill > bill.mill at gmail.com > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print text position problems when using triple quotes
On Thu, 24 Feb 2005 14:23:28 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote: > Bill Mill wrote: > >>class foo: > >>def bar(self): > > > > > > Sorry, I forgot that if it's in the module, you should declare prompt1 > > as global by using "global prompt1" right here. > > > > > >>print prompt1 % (var1, var2, var3) > > No, you only need the global statement if you want to assign to a global > variable. Read-only > reference will work without the global. This is correct. I do it for myself, just to be as explicit as possible about it, since it's something I don't like to do. Putting the strings into another module is really a much better solution. Thanks for the correction. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] threads
Hi Hugo, > I tried my hands at Stackless too... but still had > problems implementing the concept. > > Can anyone guide me on how to spawn simultaneously( or > pseudo simultaneously) running microthreads using > stackless. > > Here is what i tried.. > > ef gencars(num,origin,dest,speed): > global adjls > global cars > global juncls > for i in range(num): > > cars.append(car(orig,dest,speed) > task=tasklet(cars[i].run()) > task.setup('Bind using Setup') > > Now this is what i copied from somewhere...i dont > claim to understand fully what is happening.Here > car.run() is a process which takes a long time to > execute. > > What happens on execution isOne car is initialised > and then the program waits for its run method to > complete before proceeding. > > I also feel that there is no clear documentation on > stackless. > > Show me the light. > You might want to tighten this question up and ask it on python-list. This is pretty specialized knowledge for the python-tutors list, and I know for a fact that there are several people who have used greenlets on python-list. Just a thought. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Functions Calling Functions
Luke, On Fri, 25 Feb 2005 11:04:11 -0800, Luke Jordan <[EMAIL PROTECTED]> wrote: > Hi - > > I'm working on a command-line game. Is there anything wrong with > having each 'chapter' of the game be a function that links to other > chapters by calling them? I only ask because when a recent traceback > returned about 40 lines worth of error message, I realized that the > functions are all being run 'within each other' (ah-ha!). > for your own debugging sanity, you'll likely want to have a supervisor function which calls the chapter functions in order. There's nothing technically wrong with what you're doing, as long as you don't exceed the maximum recursion depth, but it's a pain to debug and takes up a whole bunch of memory you don't need. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable name based on variables (expansion?)
John, On Mon, 28 Feb 2005 06:05:44 -0800 (PST), John Christian <[EMAIL PROTECTED]> wrote: > a python 2.3 noob asks: > > # I have some lists > GameLogic.varList0=[1,1,1,1] > GameLogic.varList1=[1,1,1,1] > GameLogic.varList3=[1,1,1,1] > > # I want to change specific list elements > GameLogic.varList0[2]=0 > print GameLogic.varList0 > [1,1,0,1] > > # But I want the assignment > # to be based on variables > LIST=1 > POSITION=2 > > GameLogic.varList$LIST[$POSITION]=0 > Most likely you want to have a 2-dimensional list. Like so: #note the lists inside a list GameLogic.varMatrix=[[1,1,1,1], [1,1,1,1], [1,1,1,1]] Then, to get to the second element in the first list, do: GameLogic.varMatrix[0][1] Or the third element of the second list: GameLogic.varMatrix[1][2] In general, using zero-based counting of rows and columns, accessing the array is done with: GameLogic.varMatrix[row][column] so access like you have above is just: GameLogic.varMatrix[LIST][POSITION] Assuming that LIST and POSITION are zero-based counts. Also note that all-CAPS variables in python are traditionally used only for constants. This is a pretty strong tradition which, if you break, will confuse anyone trying to read your code. Variables are traditionally either camel case or all lower-case with underscores. > # But the variable assignment above does not work. > # Python complains of a syntax error. > # I've also tried variations of eval(), single ticks, > # back ticks, quotes, etc... but I just can't seem > # to get the syntax right. > # > # Can someone please provide a working example? > the $ is not a syntactic character in python. Single quotes simply delimit strings in python. Back ticks are equivalent to the str() function which creates strings (or is it repr()? I can't remember; it's generally bad form to use back ticks anyway). Double quotes are the same as single quotes. Please read the tutorial at http://docs.python.org/tut/tut.html . Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] puzzling traceback -- what to do with it?
On Mon, 28 Feb 2005 02:02:22 -0500, Brian van den Broek <[EMAIL PROTECTED]> wrote: > Hi all, > > I just ran a program of mine and got the traceback: > > >>> > Traceback (most recent call last): >File "C:\PYTHON24\lib\idlelib\rpc.py", line 233, in asyncqueue > self.putmessage((seq, request)) >File "C:\PYTHON24\lib\idlelib\rpc.py", line 333, in putmessage > raise IOError > IOError > > This stumps me, as I've almost no idea what rpc.py, putmessage, and > asyncqueue are. (A quick glance at the code made me realize my > code-reading skills and knowledge of IDLE aren't up to tracking this > down on my own.) > > Furthermore, the code that produced this runs just fine via other > methods (running from within SciTe, the python command line, etc.) > And, sometimes, but not always, closing the offending code, running > something else, and then trying again with the code that caused the > traceback makes it work. > > I'm thinking IDLE bug, but also that it would be a good idea to > solicit opinions/expertise here before running off screaming BUG to > the IDLE folks :-) > Looks like an IDLE bug to me. Either it's a bug with them, or you're interfering with something they do; either way it looks like those guys are likely gonna have to help you out. The fact that the errors are in idlelib leads me to this conclusion - unless you're importing idlelib into your program, an error there is an error with idle. Having used IDLE (maybe) once or twice, you should take this with a grain of salt, but asking them about this error seems to be a good bet. > Any suggestions for what the problem might be, or how to narrow it > down before reporting? I would just give them a link to the smallest bit of source code you can get to reproduce this problem, and an exact list of steps for how to repeat it consistently. Also tell them your OS, python version, and IDLE version. I'm also assuming you already googled the traceback and searched their mailing list to see if it's a well-known problem. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Acessing files in Windows 2000
Dave, > >>> > >>> > >>> import os.path > >>> print os.path.expanduser('~/memo.txt') > C:\Documents and Settings\Administrator/memo.txt > >>> f = open(os.path.expanduser('~/memo.txt')) > Traceback (most recent call last): > File "", line 1, in ? > f = open(os.path.expanduser('~/memo.txt')) > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > Settings\\Administrator/memo.txt' > >>> > > Now starting to doubt my sanity I again re-checked C:\Documents and > Settings\Administrator\My Documents > and yes I do have a memo.txt there. > Using all forward slashes works fine for me. Here's a cut-n-paste from the command line (touch creates a blank file, ls lists dirs, in case you didn't know): C:\Documents and Settings\WMill>touch test.txt C:\Documents and Settings\WMill>ls test.txt test.txt C:\Documents and Settings\WMill>C:\Python24\python.exe Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('c:/Documents and Settings/WMill/test.txt') >>> I'm really pretty convinced that the file you're talking about doesn't exist, or you don't have the security permissions to open it. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Acessing files in Windows 2000
> mmm ... I kind of see what you mean. > > Does anyone have like a realy large shovel so I can dig a hole and hide ? No worries, we've all been there before. Sometimes you just can't see what's right in front of your face. Don't let it stop you, or stop you from asking questions. Peace Bill Mill bill.mill at gmail.com > > Thanks > > Dave > > ___ > 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] Accessing List items
On Mon, 21 Mar 2005 11:57:21 +, Matt Williams <[EMAIL PROTECTED]> wrote: > Dear List, > > Thanks for the help with the previous problem - now all solved! > > I have a question about accessing lists. I'm trying to do something to > each item in a list, and then assign it back into the list, overwriting > the old value. However, the first loop here doesn't work, whereas the > second loop does - but is very ugly. > > x = "200% inv_nodes=0-2 node_caps=no" > y=x.split() > > for i in y: > i="z" > print y > > for i in range(len(y)): > y[i]="z" > print y > > Surely there must be a better way than this ? As Max pointed out, listcomps are the best way to do it. Another way, which is useful in more complicated scenarios: for i, elt in enumerate(y): ...do something complex with elt... y[i] = elt *** technical yapping about why your first loop doesn't work is below; read it only if you're interested - don't get scared, you don't really need to know it *** The reason that the first list doesn't work is that a string is an immutable object. Thus, when you change it, you basically just tell python to rebind the local name "i" from one immutable object (a string) to another immutable element (another string). This has no effect on the list. If, however, "i" is a mutable object (such as a list or a dict), then your loop works as expected: >>> y = [[1]] >>> for i in y: i.append(2) ... >>> y [[1, 2]] In this case, modifying the list "i" works in-place by modifying the actual mutable object. The change is reflected in the list "y", because the actual object it encloses has changed. I hope this makes sense, and maybe clears up a little of your confusion about variables in Python. It is a bit confusing, even for experienced pythonistas, so ask questions if you don't get it (and you're interested). If not, you can get away without worrying about it for the most part. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a Pythonic way to pass variable
On Tue, 22 Mar 2005 13:30:09 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote: > C Smith wrote: > > > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > > [EMAIL PROTECTED] wrote: > > > >> I met a similar question. > >> what if one has L = [[1,2],[3,4]], K = [100, 200] > >> How to 'zip' a List like [[1,2,100], [3,4,200]]? > >> > > I would do something like: > > > > ### > > for i in range(len(L)): > > L[i].append(K[i]) > > ### > > Oh, the light goes on :-) Thanks C Smith! > > Here is another way: > >>> L = [[1,2],[3,4]] > >>> K = [100, 200] > >>> [ x+[y] for x, y in zip(L, K) ] > [[1, 2, 100], [3, 4, 200]] > > Note C Smith's approach modifies L to include the items in K; my approach > makes a new list. Just for kicks - if you don't mind if the 100 and 200 appear first instead of last, and conversion of your inner lists to tuples, then: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> zip(K, *L) [(100, 1, 3), (200, 2, 4)] works, and looks a little nicer. Also, to modify the list in-place with a listcomp, you could use: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> [x.append(y) for x, y in zip(L, K)] [None, None] >>> L [[1, 2, 100], [3, 4, 200]] And, to create a new list in the format you originally asked for, we can modify the first trick I showed you: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> [[b,c,a] for a,b,c in zip(K, *L)] [[1, 3, 100], [2, 4, 200]] which I think is pretty cool, if a little obtuse. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with dictionary
On Wed, 23 Mar 2005 20:49:11 -, Igor Riabtchuk <[EMAIL PROTECTED]> wrote: > > Hi, > was wondering whether you can help? > > Say I got a dictionary of keys:values : > > And what I want to do is depending on what key (a,b,c) the person presses, I > want to output the value (tom, dic, harry). > > So I program like this: > > import Tkinter > > > D={a:"tom", b:"dick", c:"harry"} > > > text.bind('', self.Conv) > > def Conv(self,event): > if D.has_key(event.keysym): > str="The name is"+str > self.text.insert(END,str) > return 'break' > In line 3 of the Conv function, you write "str="The name is" + str . However, str has yet to be defined, from what I can tell. Thus, Python should throw a NameError. Unforutnately, you haven't included the exception that Python gives you with this email, so I can't really help you much more than that. To get a value from a dictionary D, simply do: >>> D = {1:'test', 2:'monkey', 3:'apple'} >>> D[2] 'monkey' You should read the Python Tutorial at http://docs.python.org/tut/tut.html . > (If I had to do each one (i.e. without the dictionary) I would do as > follows: > > def Conv(self,event): > if event.keysym==a: > str="tom" > self.text(END, str) > return 'break' > ) > > There is clearly a mistake in the first function, only thing is I cannot > spot it and thus the thing does not work. Send us the exception python gives you and we may be able to help you more. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How and where to use pass and continue
On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <[EMAIL PROTECTED]> wrote: > I am having lot of trouble learning where and when to use pass and > continue. The two books that I use don't explian these very good. Is > there a website the explains these is great detail? > I have also looked at the python tutorial as well. Kevin, I'll try to help you out - pass and continue are pretty simple concepts. Consider the following code snippet which I will try to use to explain both: command = None while command != '3': command = raw_input("Press 1 to pass, 2 to continue, or 3 to exit ") if command == '1': print "passing" pass elif command == '2': print "continuing" continue else: print "othering" print "end of loop reached" print "exiting" PASS The 'pass' statement simply means 'do nothing'. In the example above, when the python interpreter encounters the pass statement, it simply continues with its execution as it normally would. It is usually used as the only statement in the body of an if statement to denote explicitly that nothing is to be done. I will often use it as a placeholder so that a program compiles correctly, like: if 'a': do_something() elif 'b': #TODO: implement do_something_else() pass elif 'c': quit_foo() Without the pass statement, there are no statements in the second block, and python will raise a SyntaxError. In the first example above, Python sees the pass, exits the series of 'If...elif..." conditions, advances to the final statement of the while loop, prints "end of loop reached", and resumes execution at the top of the loop. CONTINUE The continue statement means what it says - continue with the loop, but resume execution at the top of the loop. In the case of a while loop, the exit condition will be evaluated again, and execution resumes from the top. In the case of a for loop, the item being iterated over will move to its next element. Thus, for i in (1,2): print i continue print "we never get here" Will print 1, hit the continue, update i to the value 2, print 2, hit the continue, and exit because there are no more iterations for i. In the first example I gave, after python reaches the continue, 'command' is again evaluated to see if its value is 3, then the loop proceeds from the top down. If you run the example, you should be able to figure out what's going on. There are a couple more wrinkles - for example, continue only works on the innermost loop in its execution context - but generally, they work as you expect. The longer you work with python, the more you'll find this to be the case, but I'm biased. Hope this helps, and feel free to ask questions about what you don't understand. Peace Bill Mill bill.mill at gmail.com > > Thanks > > Kevin > ___ > 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] flatten
On Apr 7, 2005 8:00 AM, C Smith <[EMAIL PROTECTED]> wrote: > After posting the suggestion about splitting a string that contained a > quoted string, I looked back at my (at least I think it's mine) flatten > routine and didn't see anything like it at ASPN. Before I would post it > there, does anyone see any problems with this non-recursive approach? > > I know that there are iterator approaches, but since the list already > exists is there any problem with flattening the whole thing? Or is part > of the problem that there may be iterable things that don't need to be > completely "iterated to completion" before being able to yield the next > element? (Does that make sense?) > > After searching for "Tim Peters flatten" I was able to find a similar > routine at > > http://sourceforge.net/project/ > showfiles.php?group_id=87034&package_id=90541&release_id=288585 > > (It is in the basictypes folder in the latebind.py script by Mike C. > Fletcher.) It's so short, I post it for comparison. I'm not really sure > why there is a run through all possible indices rather than the ones > that exist in the given "inlist", though. > 1) you should special-case dictionaries: >>> x = [1, 2, [3, 4, 5, [[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}] >>> flatten(x) >>> x [1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test'] 2) What's different about your flatten than those ASPN entries? Just that it flattens in-place? I see a general-purpose flattener and a flattening generator. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pass By Reference
On Apr 12, 2005 12:20 PM, Gooch, John <[EMAIL PROTECTED]> wrote: > > I have a class named 'Dir' that I want to be put into another class > 'DirList' ( essential a linked list of Dir objects ) using the 'insert()' > method. The syntax is 'DirList.insert( Dir )' which works, but then I try to > access the 'getSize()' function of the 'Dir' class from *inside* of the > DirList class, it gives me this -> > 'I added a node for dir d:/ with size <__main__.Dir instance at 0x00E18CD8>>' > > Any ideas on what I am doing wrong? > 1) Linked lists are almost always worthless in python. Why not use a list instead? 2) what's being printed is a function reference - i.e. you're doing: self.a_dir_instance.getSize instead of: self.a_dir_instance.getSize() which actually calls the function, instead of just returning a pointer to it. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to calculate pi with another formula?
On 4/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote: > Dick Moores wrote: > > Now to my new question. I have an artist friend who knows an artist who > > needs pi expressed in base 12. I don't know how many digits he needs, > > but I think he'll take what he can get. Is there a way to use > > math.log(x, base) with the decimal module to accomplish this? Or is > > there another way? Or is there no way? > > I think I would try to write a program that converts base-10 decimal > fractions to base 12. Then feed > it the output of a pi-generating program. > I just thought I would reference the fascinating thread that ensued from this request on comp.lang.python : http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/1839b7d733ae37d0/3b5f7138f0e5fbd1?q=pi+base+12&rnum=1#3b5f7138f0e5fbd1 Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor