Re: [Tutor] superscript with easydialogs
"Tiger12506" <[EMAIL PROTECTED]> wrote >> It turns out, no, Unicode won't work, but using x\99 for the TM >> character >> does, at least on my system (no idea if this will be universal): > > That's strange. Windows is Unicode based! Unicode is effective at the font level. You need to have a font that supports the extended characters. The standard System font, which I think is what easyDialogs uses is a relic of the original Windows 3.0 and predates unicode. You can see which characters are supported by which font using the character map application found in Accessories. Arial for example does not appear to have the TM symbol as a character. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Large Scale Python websites
Hi all, Is anyone aware of any large scale web apps developed in Python? Please let me know of any that you know of... Kind Regards, -- Sithembewena Lloyd Dube "The Stupidry Foundry" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Losing the expressiveness of C's for-statement?
Hi all, As the Python doc says: "The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string)." This is much poorer than C/C++, and does not allow for the step action to be multiple actions, fn calls etc. - not straightforwardly anyway. (don't take that as a challenge) - I know how to migrate to a while-loop, but I lament losing the very compact expressiveness of: for (node=start; valuenext) { ... } - I figure the straightforward answer will be "use a while-loop, put the iteration step at the end". - the fancy showoff answer will probably involve a funky iterator with side-effects, or returning tuples. - what if the loop iteration step involves variables from within the loop-body (e.g. as in quicksort stepsize); - what I'm trying to drive at here is the general solution of least idiomaticity, not of greatest language-specific cleverness Any comments or article links? Also, it would be useful to improve the Python tutorial on this. Since this is one area where Python is (syntactically) inferior to C/C++/Java. Thanks, Stephen _ More photos, more messages, more storageget 2GB with Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_2G_0507 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Losing the expressiveness of C's for-statement?/ RESEND with example
(Question as below) Sorry I meant to pick a tangible example to focus the discussion: This one cannot be (easily) translated to use Python's range() operator for (i=3; i>0; i=i/2) { ... } So do you need to know a whole armory of other functions to use to generate iterators, or just translate to a while-loop already? Stephen From: "Stephen McInerney" <[EMAIL PROTECTED]> To: tutor@python.org Subject: Losing the expressiveness of C's for-statement? Date: Tue, 07 Aug 2007 02:18:16 -0700 Hi all, As the Python doc says: "The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string)." This is much poorer than C/C++, and does not allow for the step action to be multiple actions, fn calls etc. - not straightforwardly anyway. (don't take that as a challenge) - I know how to migrate to a while-loop, but I lament losing the very compact expressiveness of: for (node=start; valuenext) { ... } - I figure the straightforward answer will be "use a while-loop, put the iteration step at the end". - the fancy showoff answer will probably involve a funky iterator with side-effects, or returning tuples. - what if the loop iteration step involves variables from within the loop-body (e.g. as in quicksort stepsize); - what I'm trying to drive at here is the general solution of least idiomaticity, not of greatest language-specific cleverness Any comments or article links? Also, it would be useful to improve the Python tutorial on this. Since this is one area where Python is (syntactically) inferior to C/C++/Java. Thanks, Stephen _ Find a local pizza place, movie theater, and more .then map the best route! http://maps.live.com/default.aspx?v=2&ss=yp.bars~yp.pizza~yp.movie%20theater&cp=42.358996~-71.056691&style=r&lvl=13&tilt=-90&dir=0&alt=-1000&scene=950607&encType=1&FORM=MGAC01 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C's for-statement?/ RESENDwith example
"Stephen McInerney" <[EMAIL PROTECTED]> wrote > Sorry I meant to pick a tangible example to focus the discussion: > > This one cannot be (easily) translated to use Python's range() > operator for (i=3; i>0; i=i/2) { ... } You have to remember that C's for loop is mostly syntactic sugar over a while loop: expression1 while test action expression2 becomes for (expression1, test, expression2) action Pythons for loop is a much more powerful foreach construct intended to deal with collections. C's for loop is simply an extension of assembler syntax and deals with indices, memory addresses, numbers, whatever low level construct you want. The loop used for that kind of low level detail in Python is, as you say, the while loop. > So do you need to know a whole armory of other functions to use > to generate iterators, or just translate to a while-loop already? It's very rare that you need to do those kinds of tricks in Python, usually you avoid the issue entirely by using higher level data structures. You don't give us any reason why you want to generate a set of numbers from 30,000 down to zero decreasing by half each time: 30,000, 15,000, 7500, 3750, etc To understand the Pythonic solution to the problem we would need to know what those numbers were required for so that we could determine if another python data structure might be more appropriate. One of the challenges for C/C++ programmers in moving to higher order languages like Python (or Lisp, prolog, Smalltalk etc) is to stop thinking at the machine level and start thinking at the problem level. Of course sometimes you need to work at the lower levels and for those cases the while loop can be used, but it tends to be the exception rather than the rule. As to your particular case one non while option would be a generateor: def half(n): while int(n) > 0: n = n/2 yield n for x in half(300): print x, But without a context for x its impossible to know ewheher that is a sensible solution. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example
Hi Alan, I don't deny the superiority of the underlying language design, I'm just pointing out the very real mindjolting effect of Python not supporting the universal syntax. Java is closer to C than Python is. I'm bringing this up as one hurdle to migration, not a fundamental flaw. Don't you agree that the Python tutorial should say something simple and accessible to beginners like: "For all for-loop constructs where the iteration can't be written as a simple range object, you probably want to transform it to a while-loop, (or the more advanced option being a generator)"? I think the tutorial is lacking on this (should I email Fred Drake?) Instead of leaving C and Java people cold scratching their heads about why they think the language is hopelessly quirky and not (syntactically) fully-featured? One of our aims should be to write code which is at least understandable to programmers of other languages. >Sorry I meant to pick a tangible example to focus the discussion: >This one cannot be (easily) translated to use Python's range() >operator for (i=3; i>0; i=i/2) { ... } >You don't give us any reason why you want to generate a set >of numbers from 30,000 down to zero decreasing by half each >time: 30,000, 15,000, 7500, 3750, etc >To understand the Pythonic solution to the problem we would >need to know what those numbers were required for so that we >could determine if another python data structure might be more >appropriate. Yes I did: it occurs in a quicksort as we halve the stepsize each time, on an array of size 6. Can you please give me your answer on this? We have to transform it to a while-loop? (or write a custom iterator?) It would nice to compare the most straightforward solution (while-loop?) the fastest solution, the last-memory solution and the most elegant solution. >You have to remember that C's for loop is mostly syntactic sugar >over a while loop: expression1 while test action expression2 Yes I know how to transform it. >Pythons for loop is a much more powerful foreach construct >intended to deal with collections. C's for loop is simply an extension >of assembler syntax and deals with indices, memory addresses, numbers, >whatever low level construct you want. The loop used for that kind >of low level detail in Python is, as you say, the while loop. >As to your particular case one non while option would be a generateor: > >def half(n): > while int(n) > 0: >n = n/2 >yield n > >for x in half(300): print x, It's ok but it's visually clunky. while-loop wins for clarity. lambda would also be too quirky. I know the generator is more runtime-efficient. It's regrettable we have to choose between the clear and the efficient, in this situation. Regards, Stephen _ Learn.Laugh.Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] executing file properly
Dear All, I am a newbie in Python and I would like to create command line interface for executing different softwares, either local or remotely. I begin with a very simple case in which I have an executable file called "TestCases" and this file requires Des.in as an the input. Both files are located in the same local folder. The TestCases executable works properly when I run it from the shell prompt. Then I try to run it from the Python command prompt by the following script: >>> import os >>> os.system("home/.../.../.../TestCases") I used "..." to type it short. Then it gives the following error output: cannot open Des.in Well in this case tbe os.system command is typed correctly already since this the error message given out is written in the code itself. So the executable run already only when running from Python prompt it cannot open this file. Could anyone suggest me what would be the cause of this problem? And how should I handle it ? Thank you in advance. Vivian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Books with exercises and problems to solve
Hello all, so long i have been learning python with two books 1) Official tutorial by Guido Van Rossum and 2) Pythong Programming: An Introduction to Computer Science by John M. Zelle and like them a lot as the first one gives a lot of explanations but without any exercises, but the second one has a lot of exercises to do which I like. I would like to know if anyone can recommend a book like the second one with a lot of exercises to do and problems to solve, not just the explanations for concurrent and also further study. Thanks a lot. P.S.= I am new both to Python and Programming too. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] executing file properly
* Vivian Tini (Tue, 7 Aug 2007 12:20:29 +0200) > The TestCases executable works properly when I run it from the shell prompt. > > Then I try to run it from the Python command prompt by the following script: > >>> import os > >>> os.system("home/.../.../.../TestCases") > > I used "..." to type it short. > > Then it gives the following error output: > cannot open Des.in > > Well in this case tbe os.system command is typed correctly already since this > the error message given out is written in the code itself. So the executable > run already only when running from Python prompt it cannot open this file. > > Could anyone suggest me what would be the cause of this problem? You said it yourself: "I used "..." to type it short." > And how should I handle it ? Even simpler: don't use "..." ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] comparing two numpy arrays
Hi people, If I've two numpy arrays, is there a non-looping way of finding common values. (the example below has identical shapes for the arrays but this may not be the case in my scenario) e.g a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) answer = array([ 5,6,7,8,9]) Thanks Andy ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
OkaMthembo wrote: > Hi all, > > Is anyone aware of any large scale web apps developed in Python? Please > let me know of any that you know of... http://www.davidcramer.net/other/43/rapid-development-serving-50-pageshour.html http://www.davidcramer.net/curse/44/what-powers-curse.html http://www.cogitooptimus.com/2007/03/21/deploying-trenchmice/ http://immike.net/blog/2007/07/06/interview-with-leah-culver-the-making-of-pownce/ Note that none of these are *just* Python, they all combine Python / Django with caching, load balancing and front-end servers. Don't know if any of these are large-scale... http://code.djangoproject.com/wiki/DjangoPoweredSites Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example
Stephen McInerney wrote: > I think the tutorial is lacking on this (should I email Fred Drake?) > Instead of leaving C and Java people cold scratching their heads about > why they think the language is hopelessly quirky and not (syntactically) > fully-featured? The "About this document" link at the bottom of every page of the Python docs tells how to make suggestions. I have found that specific suggestions for changes to the docs (i.e., include the suggested text) filed in the bug tracker are often accepted and incorporated. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] executing file properly
Vivian Tini wrote: > Dear All, > > I am a newbie in Python and I would like to create command line interface for > executing different softwares, either local or remotely. > > I begin with a very simple case in which I have an executable file called > "TestCases" and this file requires Des.in as an the input. Both files are > located in the same local folder. > > The TestCases executable works properly when I run it from the shell prompt. > > Then I try to run it from the Python command prompt by the following script: import os os.system("home/.../.../.../TestCases") > > I used "..." to type it short. > > Then it gives the following error output: > cannot open Des.in > > Well in this case tbe os.system command is typed correctly already since this > the error message given out is written in the code itself. So the executable > run already only when running from Python prompt it cannot open this file. > > Could anyone suggest me what would be the cause of this problem? And how > should I handle it ? I guess the working directory is not set to the dir containing TestCases so it doesn't find the file. I don't know if it will help to call os.chdir() before os.system(); you could use subprocess.Popen() instead of os.system(), it takes an explicit parameter of the cwd for the subprocess. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Books with exercises and problems to solve
Khamid Nurdiev wrote: > Hello all, > so long i have been learning python with two books 1) Official tutorial > by Guido Van Rossum and 2) Pythong Programming: An Introduction to > Computer Science by John M. Zelle and like them a lot as the first one > gives a lot of explanations but without any exercises, but the second > one has a lot of exercises to do which I like. I would like to know if > anyone can recommend a book like the second one with a lot of exercises > to do and problems to solve, not just the explanations for concurrent > and also further study. "Python Programming for the absolute beginner" is written for people with no prior programming experience and includes exercises. Wesley Chun's "Core Python Programming" includes exercises. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Books with exercises and problems to solve
thanks a lot for your help On 8/7/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > Khamid Nurdiev wrote: > > Hello all, > > so long i have been learning python with two books 1) Official tutorial > > by Guido Van Rossum and 2) Pythong Programming: An Introduction to > > Computer Science by John M. Zelle and like them a lot as the first one > > gives a lot of explanations but without any exercises, but the second > > one has a lot of exercises to do which I like. I would like to know if > > anyone can recommend a book like the second one with a lot of exercises > > to do and problems to solve, not just the explanations for concurrent > > and also further study. > > "Python Programming for the absolute beginner" is written for people > with no prior programming experience and includes exercises. > > Wesley Chun's "Core Python Programming" includes exercises. > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C'sfor-statement?/RESENDwith example
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Stephen McInerney From: [EMAIL PROTECTED]; tutor@python.org >>As to your particular case one non while option would be a generateor: >> >>def half(n): >> while int(n) > 0: >>n = n/2 >>yield n >> >>for x in half(300): print x, >It's ok but it's visually clunky. while-loop wins for clarity. lambda would also be too quirky. >I know the generator is more runtime-efficient. >It's regrettable we have to choose between the clear and the efficient, in this situation. I would have to disagree completely. Knowing both C and Python intimately now, I find this Pythonic expression far easier to read than the overly-verbose C statement. The nice thing about python is that it makes chunking much easier than C which increases readability. Remember that these lines would be visually separated. In the algorithmic part of the quicksort all you would have is fox x in decrement_by_halves(300): do stuff Note that I changed the name of the generator to be more explicit. The loop now tells exactly what is being generated. No more tearing apart an ugly C for construct which forces implementation of the generator at a place where you don't really need to know about it. Jeff ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C'sfor-statement?/RESENDwith example
"Stephen McInerney" <[EMAIL PROTECTED]> wrote > I don't deny the superiority of the underlying language design, > I'm just pointing out the very real mindjolting effect of Python not > supporting the universal syntax. An interesting term. The C syntax is extremely odd to most programmers who haven't been trained in it but in more traditional languages like Lisp, Cobol, Fortran, Pascal, ADA, etc. It is also highly error prone and a source of many bugs in C programs (I know I spent several years running a C maintenance project and for loop side-effects were right up there with uninitialised variables and memory leaks in the common error lists!). > Java is closer to C than Python is. True, Java deliberately set out to be a simple subset of C++ so it has a similar syntax. Python is closer to Lisp than C is but nobody would suggest that C should change its semantics to suit the tastes of Lisp programmers who are converting. Languages are different and learning the new idioms both positives and negatives) is part of the process. > Don't you agree that the Python tutorial should say something simple > and accessible to beginners like: "For all for-loop constructs where > the > iteration can't be written as a simple range object, In fact the range version of a for loop is only one style and probably not the most common. You should iterate over a collection not a range in most cases: ie someList = [1,2,3,4,5] for item in someList: print item and never for index in range(len(somelist)): print somelist[index] # bad bad bad! It is Pythons "foreach" effect that makes it so powerful. > I think the tutorial is lacking on this (should I email Fred Drake?) You could try it but that would imply that the tutorial should flag up where Python varies from the syntax of COBOL too - after all there are many more COBOL porogrammers than any other language! So explaining x = y + z we would need a note: Notice that Python uses a math symbol for addition instead of the more common COBOL usage ADD Y, Z TO X And explain to Smalltalk, ADA and Pascal programmers that = is assignment instead of := Where do you stop? > Instead of leaving C and Java people cold scratching their heads > about > why they think the language is hopelessly quirky and not > (syntactically) > fully-featured? A language is syntactically fully featured if it supports the 3 elements of structured programming (sequences, loops and branches) , or even more starkly if it is Turing complete. No language should try to encompass all styntax structures of all languages (that way lies PL/1!) > One of our aims should be to write code which is at least > understandable to > programmers of other languages. Yes, but that doesn't mean a similar syntax, it means an easy comprehension of the syntax as written. ie one that reads as much as possible like a natural language - a test that C fails miserably! >>You don't give us any reason why you want to generate a set >>of numbers from 30,000 down to zero decreasing by half each >>time: 30,000, 15,000, 7500, 3750, etc > Yes I did: it occurs in a quicksort as we halve the stepsize each > time, > on an array of size 6. OK so use Pythons built in sort method. It uses quick sort I believe. But if it doesn't still use it and see if its fast enough. If it isn't consider refactoring your data structures to improve it. If that doesn't work then, as a last resort, consider writing your own sort function. When using high level languages leverage the language. > Can you please give me your answer on this? We have to transform it > to > a while-loop? (or write a custom iterator?) > It would nice to compare the most straightforward solution > (while-loop?) The most straightforward solution is to use the standard sort function. > the fastest solution, the last-memory solution and the most elegant > solution. Yes it's almost certainly all of those. >>def half(n): >> while int(n) > 0: >>n = n/2 >>yield n >> >>for x in half(300): print x, > > It's ok but it's visually clunky. while-loop wins for clarity. I disagree, the while lop is a distraction from what you are trying to achieve, which is use a specific list on numbers to performs some action, in your case a sort. The more you can hide the generation of the numbers the clearer your code becomes. (PS I agree the name "half" is not great but it was short in the interpreter! :-) > lambda would also be too quirky. lambda is no good here because Python's lambda only allows a single expression not loops - I originally thought a lambda might work. (The limitations of Python's lambda are another copmmon complaint for programmers moving from languages which better support functional programming, but that still doesn't mean Python should change its lambda to match) > I know the generator is more runtime-efficient. You know more than me in that case, I didn't even think about that, I simply tried to solve the problem. If
Re: [Tutor] comparing two numpy arrays
> From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of Andy Cheesman > > Hi people, > > If I've two numpy arrays, is there a non-looping way of finding common > values. (the example below has identical shapes for the > arrays but this > may not be the case in my scenario) > > e.g > a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) > > answer = array([ 5,6,7,8,9]) > > Thanks > > Andy You might try sets. http://docs.python.org/lib/types-set.html I'm guessing that you'd need to convert the arrays to sets. Maybe convert the arrays to lists or tuples then to sets? Maybe you might be able to directly convert the numpy arrays to sets? I haven't used numpy, so you'll need to experiment. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
"OkaMthembo" <[EMAIL PROTECTED]> wrote > Is anyone aware of any large scale web apps developed in Python? > Please let > me know of any that you know of... The Zope web site has many examples. But it depends how you define large scale. Most of the really big ones (Google, Yahoo, IBM, BBC etc - anything with several million hits a day) use Java or C++ in my experience. But a lot of large and busy sites do exist using one or other of the Pyhon web frameworks, check the frameworks and you will find case histories. And even the biggest sites often use languages like Python etc for experimental features or occasional access areas or for administration or test duties. One of the good things abourt web developments is that its pretty easy to mix frameworks and have it appear seamless to the user. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing two numpy arrays
Andy Cheesman wrote: > Hi people, > > If I've two numpy arrays, is there a non-looping way of finding common > values. (the example below has identical shapes for the arrays but this > may not be the case in my scenario) > > e.g > a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) > > answer = array([ 5,6,7,8,9]) Set union? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking for custom error codes
Hi all, I am new to Python programming and this list, looks like a great place so far! Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Thanks for any assistance! -Sam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking for custom error codes
Hi all, I am new to Python programming and this list, looks like a great place so far! Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Thanks for any assistance! -Sam ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
http://www.python.org/Quotes.html Google "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc. -- bhaaluu at gmail dot com On 8/7/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > "OkaMthembo" <[EMAIL PROTECTED]> wrote > > > Is anyone aware of any large scale web apps developed in Python? > > Please let > > me know of any that you know of... > > The Zope web site has many examples. > > But it depends how you define large scale. Most of the really big ones > (Google, > Yahoo, IBM, BBC etc - anything with several million hits a day) use > Java or C++ > in my experience. But a lot of large and busy sites do exist using one > or other > of the Pyhon web frameworks, check the frameworks and you will find > case > histories. > > And even the biggest sites often use languages like Python etc for > experimental features or occasional access areas or for administration > or test duties. One of the good things abourt web developments is that > its pretty easy to mix frameworks and have it appear seamless to the > user. > > Alan G. > > > ___ > 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] Losing the expressiveness of C'sfor-statement?/RESENDwith example
Alan Gauld wrote: > OK so use Pythons built in sort method. It uses quick sort I believe. No, it uses 'timsort', an "adaptive, stable, natural mergesort [with] supernatural performance on many kinds of partially ordered arrays." Read about it here: http://svn.python.org/view/python/trunk/Objects/listsort.txt?rev=51013&view=auto > But if it doesn't still use it and see if its fast enough. If it isn't > consider > refactoring your data structures to improve it. If that doesn't work > then, > as a last resort, consider writing your own sort function. Hmmm...IMO there is vanishingly small chance that a sort written in Python will be faster than the built-in sort and slim chance that a sort written in C will be faster. timsort is at least the third sort algorithm to be used in Python - some smart people have been tweaking it for a long time. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
wormwood_3 wrote: > Hi all, > > I am new to Python programming and this list, looks like a great place so far! > > Recently I was trying to do a "try: X except Y: Z" statement, checking for a > custom error code that the rwhois.py module throws. Some details on the > exercise and the full code can be found on this post ( > http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html > ). So, here is what I tried: > > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > self.totalchecked+=1 > > If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Probably you need to import NoSuchDomain from rwhois: from rwhois import WhoisRecord, NoSuchDomain then use except NoSuchDomain: In general, when you ask a question here, "I tried X and it did not work" is not very informative and makes it difficult to give a good answer. It is very helpful to show the actual code you tried and the actual error message, including the full traceback. The error message and traceback include a lot of very helpful information; including them will greatly improve your chance of a correct answer. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Books with exercises and problems to solve
On Tue, Aug 07, 2007 at 03:04:55PM +0400, Khamid Nurdiev wrote: > Hello all, > so long i have been learning python with two books 1) Official tutorial by > Guido Van Rossum and 2) Pythong Programming: An Introduction to Computer > Science by John M. Zelle and like them a lot as the first one gives a lot of > explanations but without any exercises, but the second one has a lot of > exercises to do which I like. I would like to know if anyone can recommend a > book like the second one with a lot of exercises to do and problems to > solve, not just the explanations for concurrent and also further study. > You might look at "Python Cookbook", by Alex Martelli. Each section (and there are many) gives a problem, a solution, and a discussion. So, you could read a problem section, write your own solution, then compare your solution with the solution in the book. And, as a bonus, the discussion section will help to understand how the solution works and why it's a good way to solve the problem. There is also an on-line version, which is definitely worth looking at, but does not have the problem-solution-discussion format: http://aspn.activestate.com/ASPN/Cookbook/Python/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
wormwood_3 wrote: > Hi all, > > I am new to Python programming and this list, looks like a great place so far! > > Recently I was trying to do a "try: X except Y: Z" statement, checking for a > custom error code that the rwhois.py module throws. Some details on the > exercise and the full code can be found on this post ( > http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html > ). So, here is what I tried: > > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > self.totalchecked+=1 > > If you need more context, the whole program is here ( > http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code > ). I first tried simply "except NoSuchDomain", since that was what I saw > rwhois throw when I sent it a domain that was not registered. That did not > work, so I quoted it. I got a warning that throwing a string exception is > deprecated, but the check did not work anyway. Am I trying to check for this > custom error wrongly? How should it be done? > Examining rwhois.py reveals raise 'NoSuchDomain' which is a string exception. Which should work even tho deprecated. When you say it did not work what is the evidence? > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing two numpy arrays
Bob Gailer wrote: > Andy Cheesman wrote: > >> Hi people, >> >> If I've two numpy arrays, is there a non-looping way of finding common >> values. (the example below has identical shapes for the arrays but this >> may not be the case in my scenario) >> >> e.g >> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >> b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >> >> answer = array([ 5,6,7,8,9]) >> > Set union? > > Did you mean Set intersection? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
>>Probably you need to import NoSuchDomain from rwhois: >>from rwhois import WhoisRecord, NoSuchDomain >> >>then use >> except NoSuchDomain: That sounds right, I will give it a shot soon. >>In general, when you ask a question here, "I tried X and it did not >>work" is not very informative and makes it difficult to give a good >>answer. It is very helpful to show the actual code you tried and the >>actual error message, including the full traceback. The error message >>and traceback include a lot of very helpful information; including them >>will greatly improve your chance of a correct answer. Sorry about that, I knew the code would be helpful, that's why I linked to my blog post that included the full code. I will post the traceback tonight when I can run it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing two numpy arrays
Eric Brunson wrote: > Bob Gailer wrote: >> Andy Cheesman wrote: >> >>> Hi people, >>> >>> If I've two numpy arrays, is there a non-looping way of finding common >>> values. (the example below has identical shapes for the arrays but this >>> may not be the case in my scenario) >>> >>> e.g >>> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> >>> answer = array([ 5,6,7,8,9]) >>> >> Set union? >> >> > Did you mean Set intersection? Yes. Sigh. > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
"bhaaluu" <[EMAIL PROTECTED]> wrote > Google > "Python has been an important part of Google since the beginning, > and remains so as the system grows and evolves. Very true but they don't write the main Google web site/search engine in Python they use it to test and to administer the underlying data etc. ISTR from an interview, with Guido vanRossum of all people, that the core Google code is written in C++. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
"wormwood_3" <[EMAIL PROTECTED]> wrote > Recently I was trying to do a "try: X except Y: Z" statement, > checking for a custom error code >for potdomain in self.potdomains: >try: >who.whois(potdomain) >self.availdomains.append(potdomain) >except 'NoSuchDomain': >pass >self.totalchecked+=1 > > got a warning that throwing a string exception is deprecated, > but the check did not work anyway. So what did happen? Your code simply ignores the error so, for it not to work, I assume you are still getting an error report and traceback? If so what does it say? Python error messages may look arcane to start with but they usually contain enough information to identify a problem without any further debugging - but only if we can see them! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
Alan Gauld wrote: > "OkaMthembo" <[EMAIL PROTECTED]> wrote > > >> Is anyone aware of any large scale web apps developed in Python? >> Please let >> me know of any that you know of... >> > > The Zope web site has many examples. > > But it depends how you define large scale. Most of the really big ones > (Google, > Yahoo, IBM, BBC etc - anything with several million hits a day) use > Java or C++ > in my experience. But a lot of large and busy sites do exist using one > or other > of the Pyhon web frameworks, check the frameworks and you will find > case > histories. > > And even the biggest sites often use languages like Python etc for > experimental features or occasional access areas or for administration > or test duties. One of the good things abourt web developments is that > its pretty easy to mix frameworks and have it appear seamless to the > user. > YouTube runs primarily on Python with critical code sections compiled using psyco. http://highscalability.com/youtube-architecture Akamai is also a big python shop, from what I understand (no citation available). Those big enough for you? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Large Scale Python websites
> >> Is anyone aware of any large scale web apps developed in Python? > >> Please let > >> me know of any that you know of... I think that reddit.com switched from LISP to Python a while back. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess and signals
Hello everyone, I've come across a situation which is somewhat confusing to me. I googled for some details and came across another email thread on this very list but couldn't really glean a solution out of it. I have a program (a compiled binary) for which I need to write a wrapper (in python). The wrapper will construct some sane command line defaults for this binary and then execute it while storing some statistics like who launched it, where and when. Now this program will continuously print output (it's a parallel version of make). It it receives a SIGINT (via a Ctrl-C), it will print some statistics and go on with the build. If it receives a Ctrl-\ (SIGQUIT I think), it will terminate. I want my wrapper to be able to read the output of this program and print it while allowing these two signals to be passed to it. My wrapper (let's call it wrapper.py) has something like this -- def createSignalDelegator(p): def sighandler(signal,frame,pmake = p): os.kill(pmake.pid,signal) return sighandler pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) signal.signal(signal.SIGINT,createSignalDelegator(pmake)) signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) for op in pmake.stdout: print "-- %s"%str(op).strip() -- I've substituted my actual binary with a simple python script that continuously prints a string and which traps sigint and sigquit to appear like the binary. It seems to be receiving the signals fine (since I log it's activity into a separate file) but the problems I get are like so 1. I don't see any output (from my 'build') on screen when I run my wrapper. 2. When I send a ^C to the wrapper, I don't see the output from the build script. 3. I sometimes get a pipe error and the whole wrapper dies leaving the other program running. I'd appreciate any insights into the problem. I'm not sure where to start looking. Thanks. -- ~noufal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess and signals
Noufal Ibrahim wrote: > Hello everyone, >I've come across a situation which is somewhat confusing to me. >I googled for some details and came across another email thread on > this very list but couldn't really glean a solution out of it. > >I have a program (a compiled binary) for which I need to write a > wrapper (in python). The wrapper will construct some sane command line > defaults for this binary and then execute it while storing some > statistics like who launched it, where and when. > >Now this program will continuously print output (it's a parallel > version of make). It it receives a SIGINT (via a Ctrl-C), it will print > some statistics and go on with the build. If it receives a Ctrl-\ > (SIGQUIT I think), it will terminate. I want my wrapper to be able to > read the output of this program and print it while allowing these two > signals to be passed to it. > >My wrapper (let's call it wrapper.py) has something like this > > -- > def createSignalDelegator(p): > def sighandler(signal,frame,pmake = p): > os.kill(pmake.pid,signal) > return sighandler > > pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = > subprocess.PIPE, stderr = subprocess.STDOUT) > > signal.signal(signal.SIGINT,createSignalDelegator(pmake)) > signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) > for op in pmake.stdout: > print "-- %s"%str(op).strip() > -- > > I've substituted my actual binary with a simple python script that > continuously prints a string and which traps sigint and sigquit to > appear like the binary. It seems to be receiving the signals fine (since > I log it's activity into a separate file) but the problems I get are like so > I'm not an expert on the subprocess module, but I've used it a bit and I'm referring to the docs as I write this. > 1. I don't see any output (from my 'build') on screen when I run my > wrapper. > Why do you think you should? You've asked subprocess to pipe its output you your parent process, I believe you would need to use the communicate() method to get the output generated by the subprocess. > 2. When I send a ^C to the wrapper, I don't see the output from the > build script. > Fix #1 first and then this should fall into place. > 3. I sometimes get a pipe error and the whole wrapper dies leaving the > other program running. > Exact error messages help a lot. :-) > I'd appreciate any insights into the problem. I'm not sure where to > start looking. > > Thanks. > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Random module.. or?
As always, thanks all for the ongoing help and suggestions... the learning continues. I've successfully made a number of programs, making use of various random code. Using random.choice etc #--- import randomletters = ('a', 'b', 'c', 'd')a = random.choice(letters)print 'your random letter is %s' %(a) #or # import randomletters = ('a', 'a', 'b', 'b', 'c', 'd')a = random.choice(letters)print 'your random letter is %s' %(a) #--- In the first random... , each abcd, has a equal chance of coming out. In the 2nd random,... a b,.. have an extra chance vs c/d to come out, making them more likely. What i would like to experiment now with is,... How can you control randomness... lets say for fish. CatfishBreedA Can be say, 4inches, to 24inches long Most fish caught are say 7-14inches long Maybe 1 in 1000 catfish caught are say, 16-20 inches long Maybe 1 in 1 catfish caught are say, 20inches + How.. can you program that kind of randomness? Or another way to look at it. BasketballerA Can score 4-45pts a game. Most games, he scores 15-25 pts Maybe 1 in 1000 games he scores 30 plus pts Maybe 1 in 1 he scores 45 pts. The actual %'s, lengths, and pts are irrelevent,.. they are just used to as an example. Any guidance would be appreciated. Tony Noyeaux _ Learn. Laugh. Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess and signals
Eric Brunson wrote: > Noufal Ibrahim wrote: [..] >> def createSignalDelegator(p): >> def sighandler(signal,frame,pmake = p): >> os.kill(pmake.pid,signal) >> return sighandler >> >> pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = >> subprocess.PIPE, stderr = subprocess.STDOUT) >> >> signal.signal(signal.SIGINT,createSignalDelegator(pmake)) >> signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) >> for op in pmake.stdout: >> print "-- %s"%str(op).strip() >> -- >> [..] > I'm not an expert on the subprocess module, but I've used it a bit and > I'm referring to the docs as I write this. > >> 1. I don't see any output (from my 'build') on screen when I run my >> wrapper. >> > > Why do you think you should? You've asked subprocess to pipe its output > you your parent process, I believe you would need to use the > communicate() method to get the output generated by the subprocess. If I read from the stdout attribute of the Popen object, I should get the output of the pipe. Shouldn't I? That's what I'm trying to do. I think the code above is broken though so I've changed the last two lines of the snippet to look like this line = pmake.stdout.readline() while line: print "-- %s"%str(line).strip() line = pmake.stdout.readline() That sounds more sensible. The docs for communicate warn against using it when the data size is large and that's the case here. I did however try it like so (stdout,dummy) = pmake.communicate() line = stdout.readline() while line: print "-- %s"%str(line).strip() line = stdout.readline() and I get similar behaviour. >> 3. I sometimes get a pipe error and the whole wrapper dies leaving the >> other program running. >> > > Exact error messages help a lot. :-) Yeah I know. I didn't have access to the machine where I got the original error so I thought I'd slur around there a bit. :) But I got it now (this is with the original snippet). Traceback (most recent call last): File "./build_wrapper.py", line 246, in main() File "./build_wrapper.py", line 231, in main run_pmake(target,options,extra_flags,pmake_options) File "./build_wrapper.py", line 209, in run_pmake line = pmake.stdout.readline() IOError: [Errno 4] Interrupted system call This is with python2.4 (if that's useful). Also, the output of the actual program will be a bit slow (since it's doing compiles and stuff). Will some intermediate buffering create any trouble? Thanks. -- ~noufal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or?
Tony Noyeaux wrote: > As always, thanks all for the ongoing help and suggestions... the > learning continues. > > I've successfully made a number of programs, making use of various > random code. > > Using random.choice etc > #--- > import random > letters = ('a', 'b', 'c', 'd') > a = random.choice(letters) > print 'your random letter is %s' %(a) > # > or > # > import random > letters = ('a', 'a', 'b', 'b', 'c', 'd') > a = random.choice(letters) > print 'your random letter is %s' %(a) > #--- > > In the first random... , each abcd, has a equal chance of coming out. > In the 2nd random,... a b,.. have an extra chance vs c/d to come out, > making them more likely. > > What i would like to experiment now with is,... > > How can you control randomness... lets say for fish. > > CatfishBreedA > Can be say, 4inches, to 24inches long > Most fish caught are say 7-14inches long > Maybe 1 in 1000 catfish caught are say, 16-20 inches long > Maybe 1 in 1 catfish caught are say, 20inches + > > How.. can you program that kind of randomness? > > Or another way to look at it. > > BasketballerA > Can score 4-45pts a game. > Most games, he scores 15-25 pts > Maybe 1 in 1000 games he scores 30 plus pts > Maybe 1 in 1 he scores 45 pts. > > The actual %'s, lengths, and pts are irrelevent,.. they are just used > to as an example. > > > Any guidance would be appreciated. 1 games would be distributed thus: 1 = 45 pts 10 = 30+ pts 99989 = 15-25 pts so generate a random integer between 1 and 1. if it is <= 1 then 45 else if it is <= 11 then 30+ else 15-25 Enough to get you going? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] send os.system() output to tarfile?
Hi all, I've been lurking on this list for some time. It's great. Thanks for all the help. I'm a sysadmin by trade, and have slowly started using Python more and more in my work. However, this is my first experience with using the tarfile module. I'm currently writing a script to backup a mysql database. On the cli, I'd do something like this: 'mysqldump dbname | gzip -9 > dbname-date.gz' Note that "gzip -9" could just as easily be "tar cvzf" for example. Anyway, what I'm trying to do is figure out the right way to redirect the output generated by "os.system(mysqldump dbname)" to my tarfile object for compressing. What I tried were a few variations on this: == #!/usr/bin/env python import os import time import tarfile import sys filename = time.strftime("%Y%m%d") + ".tgz" tarball = tarfile.open(filename, "w|gz", fileobj = sys.stdout) os.system( "ls -alrt" ) tarball.close() == I also played around with redirecting stdout to the tarfile object, and some other things that are probably stuff you'd expect from a python n00b. What's the right way to do this? I was hoping to not be forced down the road of creating temp files, compressing *those*, and then blowing them away at the end. Any help greatly appreciated. brian. -- Brian K. Jones Python Magazine http://www.pythonmagazine.com My Blog http://m0j0.wordpress.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or? CORRECTION
Bob Gailer wrote: > Tony Noyeaux wrote: > >> As always, thanks all for the ongoing help and suggestions... the >> learning continues. >> >> I've successfully made a number of programs, making use of various >> random code. >> >> Using random.choice etc >> #--- >> import random >> letters = ('a', 'b', 'c', 'd') >> a = random.choice(letters) >> print 'your random letter is %s' %(a) >> # >> or >> # >> import random >> letters = ('a', 'a', 'b', 'b', 'c', 'd') >> a = random.choice(letters) >> print 'your random letter is %s' %(a) >> #--- >> >> In the first random... , each abcd, has a equal chance of coming out. >> In the 2nd random,... a b,.. have an extra chance vs c/d to come out, >> making them more likely. >> >> What i would like to experiment now with is,... >> >> How can you control randomness... lets say for fish. >> >> CatfishBreedA >> Can be say, 4inches, to 24inches long >> Most fish caught are say 7-14inches long >> Maybe 1 in 1000 catfish caught are say, 16-20 inches long >> Maybe 1 in 1 catfish caught are say, 20inches + >> >> How.. can you program that kind of randomness? >> >> Or another way to look at it. >> >> BasketballerA >> Can score 4-45pts a game. >> Most games, he scores 15-25 pts >> Maybe 1 in 1000 games he scores 30 plus pts >> Maybe 1 in 1 he scores 45 pts. >> >> The actual %'s, lengths, and pts are irrelevent,.. they are just used >> to as an example. >> >> >> Any guidance would be appreciated. >> > 1 games would be distributed thus: > 1 = 45 pts >10 = 30+ pts > 9989 = 15-25 pts CORRECTED > so generate a random integer between 1 and 1. > if it is <= 1 then 45 > else if it is <= 11 then 30+ > else 15-25 > > Enough to get you going? > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] variable * raw_input
Hello, So i am new to Python, and really to programming. I picked up book and so far I like it. right now I am trying to figure out a problem that I cant. It is a tipping program and I have assigned certain words to be a certain % and then I ask the user to type raw input of one of those names. After which I am trying to mutiply the Bill by the Service quality. But I dont understand something below is code. Thanks D # Tip Calulator - Ver # Challenges Ch2 - Question 3 # Developed by, Dewight # Developed on, 8/7/2007 # establish variables bill = float(0.0) bad = float (0.0) ok = float(0.10) good = float (0.15) great = float (0.20) service="nothing" tip = float () total = float () print "This is a tipping calculator." bill = raw_input ("\nWhat was the total bill amount? ") service = raw_input("Please input one of the following to"+ " discribe the service:"+"\nbad\nok\ngood\ngreat \n") tip = bill * service total = bill + tip print "Then you should leave a" + tip + "tip. This will bring the total to" + total +"." raw_input("\n\nPlease press enter to exit.") ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or?
"Bob Gailer" <[EMAIL PROTECTED]> wrote > 1 games would be distributed thus: > 1 = 45 pts > 10 = 30+ pts > 99989 = 15-25 pts > so generate a random integer between 1 and 1. > if it is <= 1 then 45 > else if it is <= 11 then 30+ > else 15-25 Bob's approach is typical for large data sets, for small data sets it can be easier to create a statistically representative sample population then pick on from the population. Thus if there are 3 possible outcomes and 1 is twice as likely as 2 which is 4 times as likely as 3 we can create a sample like: pop = [3,2,2,2,2,1,1,1,1,1,1,1,1] (List comprehensions, zip and other list building functions can help generate the population sample.) Now selecting a single entry from pop will give the right randomness. This technique has the advantage of a single random selection but it quickly runs out of steam for complex data. In that case Bob's approach is better but requires two random functions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or? CORRECTION
Greetings, I just had to play with Bob's probabilities... The standard disclaimer applies: This Python source code has been written by a Noob, so use it at your own risk. =) #!/usr/bin/env python # randy.py # 2007-08-07 # b h a a l u u at g m a i l dot c o m import random def randy(): a=[] for i in range(1,10001): a.append(i) #print a[0] #print a[] b = random.choice(a) print b if b <= 1: print "45 points scored!" elif b > 1 and b <= 11: print "30 points scored!" else: c=[] for i in range(26): c.append(i) d = random.choice(c) print d,"points scored!" randy() -- bhaaluu at gmail dot com On 8/7/07, Bob Gailer <[EMAIL PROTECTED]> wrote: > Bob Gailer wrote: > > Tony Noyeaux wrote: > > > >> As always, thanks all for the ongoing help and suggestions... the > >> learning continues. > >> > >> I've successfully made a number of programs, making use of various > >> random code. > >> > >> Using random.choice etc > >> #--- > >> import random > >> letters = ('a', 'b', 'c', 'd') > >> a = random.choice(letters) > >> print 'your random letter is %s' %(a) > >> # > >> or > >> # > >> import random > >> letters = ('a', 'a', 'b', 'b', 'c', 'd') > >> a = random.choice(letters) > >> print 'your random letter is %s' %(a) > >> #--- > >> > >> In the first random... , each abcd, has a equal chance of coming out. > >> In the 2nd random,... a b,.. have an extra chance vs c/d to come out, > >> making them more likely. > >> > >> What i would like to experiment now with is,... > >> > >> How can you control randomness... lets say for fish. > >> > >> CatfishBreedA > >> Can be say, 4inches, to 24inches long > >> Most fish caught are say 7-14inches long > >> Maybe 1 in 1000 catfish caught are say, 16-20 inches long > >> Maybe 1 in 1 catfish caught are say, 20inches + > >> > >> How.. can you program that kind of randomness? > >> > >> Or another way to look at it. > >> > >> BasketballerA > >> Can score 4-45pts a game. > >> Most games, he scores 15-25 pts > >> Maybe 1 in 1000 games he scores 30 plus pts > >> Maybe 1 in 1 he scores 45 pts. > >> > >> The actual %'s, lengths, and pts are irrelevent,.. they are just used > >> to as an example. > >> > >> > >> Any guidance would be appreciated. > >> > > 1 games would be distributed thus: > > 1 = 45 pts > >10 = 30+ pts > > 9989 = 15-25 pts CORRECTED > > so generate a random integer between 1 and 1. > > if it is <= 1 then 45 > > else if it is <= 11 then 30+ > > else 15-25 > > > > Enough to get you going? > > > > > > > -- > Bob Gailer > 510-978-4454 Oakland, CA > 919-636-4239 Chapel Hill, NC > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- bhaaluu at gmail dot com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable * raw_input
"Dewight Kramer" <[EMAIL PROTECTED]> wrote > quality. But I dont understand something below is code. Since you don't tell us what exactly you don't undertand I'll make some general comments on the code... > # establish variables > bill = float(0.0) > bad = float (0.0) > ok = float(0.10) > good = float (0.15) > great = float (0.20) You don;t need the float() call because the values are already floats by dint of having a decimal point in them. float is really for converting non float values(integer or string) to floats. > service="nothing" > tip = float () > total = float () these lsat two will be the same as tip = 0.0 total = 0.0 > print "This is a tipping calculator." > > bill = raw_input ("\nWhat was the total bill amount? ") raw_input returns a string, you probably want to convert that to a float, so here you do want to use float(), like so: > bill = float(raw_input ("\nWhat was the total bill amount? ")) > service = raw_input("Please input one of the following to"+ > " describe the service:"+"\nbad\nok\ngood\ngreat > \n") You could use a triple quoted string here for clearer layout: service = raw_input( """Please input one of the following to describe the service: bad ok good great """) > tip = bill * service But now you are trying to multiply a number(bill) by a string ('ok', 'bad' etc) Thsat won;t work, instead you need to convert the string into some kind of number. The common way to do that would be using a dictionary: serviceVal = {'bad': 0, 'ok': 0.1, 'good': 0.15, 'great':0.2} and now the tip line looks like: tip = bill * serviceVal[service] > total = bill + tip > print "Then you should leave a" + tip + "tip. This will bring the > total to" + total +"." You might find this easier using string formatting print "Then you should leave a $%.2f tip. This will bring the total to $%.2f." % (tip, total) Notice how that lets you control what the output looks like more precisely. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or?
On 8/7/07, Alan Gauld <[EMAIL PROTECTED]> wrote: > > > "Bob Gailer" <[EMAIL PROTECTED]> wrote > > > 1 games would be distributed thus: > > 1 = 45 pts > > 10 = 30+ pts > > 99989 = 15-25 pts > > so generate a random integer between 1 and 1. > > if it is <= 1 then 45 > > else if it is <= 11 then 30+ > > else 15-25 > > Bob's approach is typical for large data sets, for small data sets > it can be easier to create a statistically representative sample > population then pick on from the population. > > Thus if there are 3 possible outcomes and 1 is twice as likely > as 2 which is 4 times as likely as 3 we can create a sample like: > > pop = [3,2,2,2,2,1,1,1,1,1,1,1,1] > > (List comprehensions, zip and other list building functions can > help generate the population sample.) > > Now selecting a single entry from pop will give the right > randomness. This technique has the advantage of a single > random selection but it quickly runs out of steam for complex > data. In that case Bob's approach is better but requires two > random functions. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Python provides you with a pseudo random number generator whose output values are uniformly distributed between the input parameters. What you are dealing with in fish weights or test scores or other natural phenomena is most likely a normal distribution. Yes, it's the bell-shaped curve that your professors use to give you a letter grade from your numeric score on a test. There is an average score or weight called the mean and a measure of the pointedness of the curve called the standard deviation so that two thirds of all the scores are going to be within a standard deviation of that mean. In your catfish example suitable values might be mean = 10 inches with a standard deviation of 4 inches. There are several numerical algorithms that massage a uniformly distributed random value (or several uniformly distributed random values) into a normally distributed random value. Check out Wikipedia's normal distribution entry. The math is really juicy. You may end up with a recipe for the Python Cookbook. Have fun. Steve ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or? CORRECTION
"bhaaluu" <[EMAIL PROTECTED]> wrote > source code has been written by a Noob, so > use it at your own risk. =) Just a few comments... > def randy(): > a=[] > for i in range(1,10001): >a.append(i) a = range(1,10001) # range returns a list... > b = random.choice(a) > print b > if b <= 1: Can never be less than 1 so == would be more appropriate. In fact, more accurate too, since only one value out of 1 can give 45. >print "45 points scored!" > elif b > 1 and b <= 11: >print "30 points scored!" But here you need to get a value between 30 and 45 so another call to choice would be appropriate. Otherwise players can only score a very limited set of scores! > else: >c=[] >for i in range(26): > c.append(i) c = range(26) >d = random.choice(c) d = random.choice(range(26)) replaces all of it! >print d,"points scored!" And for consistency I'd make the print statements above into assignments to d and then this final print statement can be dedented and covers all cases. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] send os.system() output to tarfile?
On Tue, Aug 07, 2007 at 03:55:03PM -0400, Brian Jones wrote: > > I'm currently writing a script to backup a mysql database. On the cli, I'd > do something like this: > 'mysqldump dbname | gzip -9 > dbname-date.gz' > > Note that "gzip -9" could just as easily be "tar cvzf" for example. > > Anyway, what I'm trying to do is figure out the right way to redirect the > output generated by "os.system(mysqldump dbname)" to my tarfile object for > compressing. What I tried were a few variations on this: > == > #!/usr/bin/env python > > import os > import time > import tarfile > import sys > > filename = time.strftime("%Y%m%d") + ".tgz" > tarball = tarfile.open(filename, "w|gz", fileobj = sys.stdout) > os.system( "ls -alrt" ) > tarball.close() > > == I'm not sure why you are are not doing something like this: cmd = 'mysqldump %s | gzip -9 > %s-%s.gz' % (dbname, dbname, date, ) os.system(cmd) But, if you want more control, then look at these functions/modules in the Pyhon standard library: - popen, popen2, etc -- http://docs.python.org/lib/os-process.html - tarfile -- http://docs.python.org/lib/module-tarfile.html popen will enable you to capture the output from your command. Use one of the other popenX functions if you need to capture both stdout and stderr. tarfile will enable you to stuff that captured output into a tar.gz file. Also, see the zipfile module if you want to save into a zip file. With tarfile, you may have to write data to a temp file and then archive that. With zipfile, you can write content directly into a zipfile. Is there a way around this? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to parse and extract data from a log file?
I'm a newbie to programming and am trying to learn Python. Maybe I'm wrong, but I thought a practical way of learning it would be to create a script. I want to automate the gathering of mailbox statistics for users in a post office. There are two lines containing this information for each user. I want to find the two lines for each user and place the information in a different file. I can't figure out how to find the information I'm after. Can you provide me an example or refer me to some place that has it? _ Messenger Café open for fun 24/7. Hot games, cool activities served daily. Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example
Stephen McInerney wrote: > Hi Alan, > > I don't deny the superiority of the underlying language design, > I'm just pointing out the very real mindjolting effect of Python not > supporting the universal syntax. Java is closer to C than Python is. > I'm bringing this up as one hurdle to migration, not a fundamental flaw. > > Don't you agree that the Python tutorial should say something simple > and accessible to beginners like: "For all for-loop constructs where the > iteration can't be written as a simple range object, you probably want to > transform it to a while-loop, (or the more advanced option being a > generator)"? > I think the tutorial is lacking on this (should I email Fred Drake?) > Instead of leaving C and Java people cold scratching their heads about > why they think the language is hopelessly quirky and not (syntactically) > fully-featured? > One of our aims should be to write code which is at least understandable to > programmers of other languages. > > > >> Sorry I meant to pick a tangible example to focus the discussion: >> This one cannot be (easily) translated to use Python's range() >> operator for (i=3; i>0; i=i/2) { ... } >> You don't give us any reason why you want to generate a set >> of numbers from 30,000 down to zero decreasing by half each >> time: 30,000, 15,000, 7500, 3750, etc >> To understand the Pythonic solution to the problem we would >> need to know what those numbers were required for so that we >> could determine if another python data structure might be more >> appropriate. > > Yes I did: it occurs in a quicksort as we halve the stepsize each time, > on an array of size 6. > Can you please give me your answer on this? We have to transform it to > a while-loop? (or write a custom iterator?) Or just the usual? A recursive function? Elegant, succinct. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to parse and extract data from a log file?
On 08/08/07, Tim Finley <[EMAIL PROTECTED]> wrote: > I'm a newbie to programming and am trying to learn Python. Maybe I'm wrong, > but I thought a practical way of learning it would be to create a script. I > want to automate the gathering of mailbox statistics for users in a post > office. There are two lines containing this information for each user. I > want to find the two lines for each user and place the information in a > different file. I can't figure out how to find the information I'm after. > Can you provide me an example or refer me to some place that has it? Hi Tim, My first step in approaching a problem like this would probably be to parse the data. "parsing" means taking text data and adding structure to it. For example, suppose I had a data file "employees.csv" that looks like this: 1,joe,smith,ceo 2,fred,dagg,cio 3,karl,marx,cfo where the data format is: id, first name, surname, job I might proceed like this: #- employees = {}# This is a dictionary. I will use this to store the parsed information. infile = open('employees.csv') # open the file for reading for line in infile: # go through the input file, one line at a time line = line.strip() # remove the newline character at the end of each line id, first, last, job = line.split(',') # split up line around comma characters employees[int(id)] = { 'first':first, 'last':last, 'job':job } # store data in dictionary #- Once we get to here, we can do things like this: # What is employee 3's name? print employees[3]['first'], employees[3]['last'] # What is employee 1's job? print employees[1]['job'] This might not be the best data structure for you; it depends on what your data looks like and what you want to do with it. Python also has lists and tuples. I encourage you to go through the tutorial :-) -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or? CORRECTION
Alan Gauld wrote: > d = random.choice(range(26)) > > replaces all of it! or d = random.randrange(26) no need to creat the list at all. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or?
steve reighard wrote: > Python provides you with a pseudo random number generator whose output > values are uniformly distributed between the input parameters. What you > are dealing with in fish weights or test scores or other natural > phenomena is most likely a normal distribution. Check out Wikipedia's > normal distribution entry. The math is really juicy. You may end up > with a recipe for the Python Cookbook. No need for all that, use random.gauss() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] send os.system() output to tarfile?
"Dave Kuhlman" <[EMAIL PROTECTED]> wrote > But, if you want more control, then look at these functions/modules > in the Pyhon standard library: > > - popen, popen2, etc -- http://docs.python.org/lib/os-process.html Or the new(ish) subprocess module which supercedes system(), popenX(), commands, spawn(), execX() etc But yes, to read the output of your command you need more than system() which only returns the exit code of the command, usually zero. > - tarfile -- http://docs.python.org/lib/module-tarfile.html He is already using this one :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random module.. or?
Tony Noyeaux wrote: > How can you control randomness... lets say for fish. > > CatfishBreedA > Can be say, 4inches, to 24inches long > Most fish caught are say 7-14inches long > Maybe 1 in 1000 catfish caught are say, 16-20 inches long > Maybe 1 in 1 catfish caught are say, 20inches + > > How.. can you program that kind of randomness? > > Or another way to look at it. > > BasketballerA > Can score 4-45pts a game. > Most games, he scores 15-25 pts > Maybe 1 in 1000 games he scores 30 plus pts > Maybe 1 in 1 he scores 45 pts. This sounds a lot like a normal distribution. http://en.wikipedia.org/wiki/Normal_distribution You can generate normally distributed random variables with random.gauss() Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to parse and extract data from a log file?
"Tim Finley" <[EMAIL PROTECTED]> wrote > but I thought a practical way of learning it would be to create a > script. Yep, its a good start once you've been through the language basics in a tutorial. > There are two lines containing this information for each user. > I > want to find the two lines for each user and place the information > in a > different file. I can't figure out how to find the information I'm > after. Look at the Handling Files and Handling Text topics in my tutorial. You may need to look at the Regular Expressions topic too if the patterns are complex. In particular look at the "Practical example" in the regex topic. Once you have a specific question or an error merssage come back here and we'll take it from there... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] executing file properly
Thorsten Kampe wrote: > * Vivian Tini (Tue, 7 Aug 2007 12:20:29 +0200) > >> The TestCases executable works properly when I run it from the shell prompt. >> >> Then I try to run it from the Python command prompt by the following script: >> > import os > os.system("home/.../.../.../TestCases") > >> I used "..." to type it short. >> >> Then it gives the following error output: >> cannot open Des.in >> >> Well in this case tbe os.system command is typed correctly already since >> this >> the error message given out is written in the code itself. So the executable >> run already only when running from Python prompt it cannot open this file. >> >> Could anyone suggest me what would be the cause of this problem? >> > > You said it yourself: "I used "..." to type it short." > > >> And how should I handle it ? >> > > Even simpler: don't use "..." > I'm pretty sure he meant "I didn't type out the whole path in this e-mail so it wouldn't be > 80 characters and cause formatting issues" not that he didn't type the whole path in his original code. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example
Stephen McInerney wrote: > Hi Alan, > > > [ snipage ] >> As to your particular case one non while option would be a generateor: >> >> def half(n): >> while int(n) > 0: >>n = n/2 >>yield n >> >> for x in half(300): print x, >> > > It's ok but it's visually clunky. while-loop wins for clarity. lambda would > also be too quirky. > I know the generator is more runtime-efficient. > It's regrettable we have to choose between the clear and the efficient, in > this situation. > That statement seems to be founded on the assumption that the C syntax is clear, which has not been established. It is clear to you because it is what you're used to seeing. Slap it down in front of a programmer that has never seen the idiom and see what they make of it. Any time you change languages you have to accustom yourself to it's nuances. C is probably one of the hardest languages I ever learned, I can't remember how many times I read and re-read the K&R chapter on pointer syntax. e. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
>>Examining rwhois.py reveals >>raise 'NoSuchDomain' >>>which is a string exception. Which should work even tho deprecated. >>>When you say it did not work what is the evidence? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC ___ I did speak too soon on this. When I run the script using the code at the end, I get: rwhois.py:327: DeprecationWarning: raising a string exception is deprecated raise 'NoSuchDomain', self.domain === def lookup(self): """ Looks up each word in our list with whois """ """ Using rwhois, which is either broken or lacks most data: """ from rwhois import WhoisRecord who = WhoisRecord() self.totalchecked = 0 self.availdomains = [] for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 def printresults(self): """ Prints the ones that do not seem to be taken, with some stats. """ print "Results are in! " print "%s total words checked, as .com and .net domains." % (self.totalchecked / 2) print "--" print "Domains that seem to be available: \n" for availdomain in self.availdomains: print availdomain print "\n" print "--" Then, I get back items in the list such as: Domains that seem to be available: AA.com AARP.com AARP.net I confirmed in spotchecking that some of these are taken, such as with whois -H AARP.com: Domain Name: AARP.COM Registrar: NETWORK SOLUTIONS, LLC. Whois Server: whois.networksolutions.com This may, however, be something else wrong with my code, or the rwhois module, not the try, except check. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
>>Probably you need to import NoSuchDomain from rwhois: >>from rwhois import WhoisRecord, NoSuchDomain >> >>then use >> except NoSuchDomain: I tried adding: from rwhois import WhoisRecord, NoSuchDomain who = WhoisRecord() self.totalchecked = 0 self.availdomains = [] for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except NoSuchDomain: pass self.totalchecked+=1 But I get back: Traceback (most recent call last): File "domainspotter.py", line 150, in runMainParser() File "domainspotter.py", line 147, in runMainParser td.run() File "domainspotter.py", line 71, in run checkdomains.lookup() File "domainspotter.py", line 108, in lookup from rwhois import WhoisRecord, NoSuchDomain ImportError: cannot import name NoSuchDomain Maybe I need to import something else to be able to throw it. I think if someone can explain a more general form of this I would be on better footing: To use a custom error code (from a module) in a loop or anywhere else, do I need to import the code itself? I had assumed that once I imported the module that defined the error code, I could catch it just like a core Python error code. >>In general, when you ask a question here, "I tried X and it did not >>work" is not very informative and makes it difficult to give a good >>answer. It is very helpful to show the actual code you tried and the >>actual error message, including the full traceback. The error message >>and traceback include a lot of very helpful information; including them >>will greatly improve your chance of a correct answer. Commented on this with the warning text in last response. Will endeavour to do better:-) ___ 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] Checking for custom error codes
> Traceback (most recent call last): > File "domainspotter.py", line 150, in >runMainParser() > File "domainspotter.py", line 147, in runMainParser >td.run() > File "domainspotter.py", line 71, in run >checkdomains.lookup() > File "domainspotter.py", line 108, in lookup >from rwhois import WhoisRecord, NoSuchDomain > ImportError: cannot import name NoSuchDomain > > Maybe I need to import something else to be able to throw it. > > I think if someone can explain a more general form of this I would be on > better footing: To use a custom error code (from a module) in a loop or > anywhere else, do I need to import the code itself? I had assumed that > once I imported the module that defined the error code, I could catch it > just like a core Python error code. The problem is evident. The name NoSuchDomain is not defined. It is not a variable. It is just a string. When you call an error like this raise 'NoSuchDomain', it's called something - don't know what (string exception?) - but as you found out, that method of raising errors is now frowned upon (deprecated). The way you are supposed to raise errors is to create a new class, subclassing Exception. Then you would be able to catch it by variable name as you are trying to do with the import. But you certainly can't import a constant string! It's like trying to import the contents of a string variable, instead of the variable itself. Again, the problem is deprecation, the rwhois will eventually have to be re-written so that it uses exception classes, instead of just raising string errors. JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
> Traceback (most recent call last): > File "domainspotter.py", line 150, in >runMainParser() > File "domainspotter.py", line 147, in runMainParser >td.run() > File "domainspotter.py", line 71, in run >checkdomains.lookup() > File "domainspotter.py", line 108, in lookup >from rwhois import WhoisRecord, NoSuchDomain > ImportError: cannot import name NoSuchDomain > > Maybe I need to import something else to be able to throw it. > > I think if someone can explain a more general form of this I would be on > better footing: To use a custom error code (from a module) in a loop or > anywhere else, do I need to import the code itself? I had assumed that > once I imported the module that defined the error code, I could catch it > just like a core Python error code. >>The problem is evident. The name NoSuchDomain is not defined. It is not a >>variable. It is just a string. When you call an error like this raise >>'NoSuchDomain', it's called something - don't know what (string >>exception?) - but as you found out, that method of raising errors is now >>frowned upon (deprecated). The way you are supposed to raise errors is to >>create a new class, subclassing Exception. Then you would be able to catch >>it by variable name as you are trying to do with the import. This is exactly what I needed, awesome! Looks like this is what you were saying to do?: http://docs.python.org/tut/node10.html#SECTION001050 >>But you certainly can't import a constant string! It's like trying to import >>the >>contents of a string variable, instead of the variable itself. Again, the >>problem is deprecation, the rwhois will eventually have to be re-written so >>that it uses exception classes, instead of just raising string errors. That would seem best. I will see if they have this in the works. Thanks again! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for custom error codes
> This is exactly what I needed, awesome! Looks like this is what you were > saying to do?: > http://docs.python.org/tut/node10.html#SECTION001050 Why ~ exactly! A link tells a thousand words. (Or maybe more.) So does that mean that a link is inherently more valuable than a picture? ;-) JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to sort a dictionary by values
hello there all, i am wondering how to sort a dictionary that i have by values. And i also need to sort them from greatest to least like if i have a dictionary d = {'a':21.3, 'b':32.8, 'c': 12.92} how could i sort these from least to greatest so that the order would turn out b,a,c thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
>>hello there all, >>i am wondering how to sort a dictionary that i have by values. >>And i also need to sort them from greatest to least >>like if i have a dictionary >> >>d = {'a':21.3, 'b':32.8, 'c': 12.92} >> >>how could i sort these from least to greatest >>so that the order would turn out >>b,a,c Hi Shawn, I was not sure how to do this either, but some digging revealed a very handing cookbook recipe on just this! (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304440) So, here is an example of it working in the Python interpreter: == Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'a':21.3, 'b':32.8, 'c':12.92} >>> from operator import itemgetter >>> # This will print the dict, sorted by value: ... >>> print sorted(dict.items(), key=itemgetter(1)) [('c', 12.92), ('a', 21.301), ('b', 32.797)] == So just add that import, and use sorted() as I showed above, and you should be good to go. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
shawn bright wrote: > hello there all, > i am wondering how to sort a dictionary that i have by values. > And i also need to sort them from greatest to least > like if i have a dictionary > > d = {'a':21.3, 'b':32.8, 'c': 12.92} > > how could i sort these from least to greatest > so that the order would turn out > b,a,c You can use d.__getitem__ as the key function for a sort of the keys. __getitem__() is the special method that is called for indexing a dictionary (or a list). In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) Out[26]: ['b', 'a', 'c'] More on sorting here: http://personalpages.tds.net/~kent37/kk/7.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
>>You can use d.__getitem__ as the key function for a sort of the keys. >>__getitem__() is the special method that is called for indexing a >>dictionary (or a list). Just curious: Is there a reason to use __getitem__() over itemgetter (used in the example in my reply)? >>In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} >>In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) I think Shawn would want to leave off "reverse=True". The default is least to greatest, which is what he wanted, I think. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
> Just curious: Is there a reason to use __getitem__() over itemgetter (used > in the example in my reply)? __getitem__ is a method builtin to a dict object. itemgetter 1) has to be imported 2) is more generically used, therefore probably using a more generic/slower algorithm JS ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to sort a dictionary by values
wormwood_3 wrote: >>> You can use d.__getitem__ as the key function for a sort of the keys. >>> __getitem__() is the special method that is called for indexing a >>> dictionary (or a list). >>> > > Just curious: Is there a reason to use __getitem__() over itemgetter (used in > the example in my reply)? > > >>> In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} >>> In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) >>> > > I think Shawn would want to leave off "reverse=True". The default is least to > greatest, which is what he wanted, I think. > It wouldn't have taken you very long to check to see what he wanted :) To save you time ;) he did want them in decreasing order. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor