Re: [Tutor] Wrong module name and line number in logging package.
Noufal Ibrahim noufal at airtelbroadband.in writes: Greetings everyone, I'm using the python standard logging package for a personal project of mine and have initialised it like so. logger = logging.getLogger(pydagogue) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter([%(levelname)s]%(pathname)s:%(lineno)d %(message)s)) logger.addHandler(handler) logger.setLevel(logging.DEBUG) I think there's a bug in the module. I'm running two Ubuntu machines. One with the latest release and one with an older one. The same code runs different on both machines. On the latest one, I get wrong module names and line numbers. On the older one, it works fine. Can someone else please try this out and check if it's a problem on my end or something genuinely wrong? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] editing Path
Hello. Iam beginning to use python on windows. how canI add a path to Python search-list whereI can store my python scripts ? On IDLE the command browse path lets me to see the existing path but not to edit it. thanks Eli___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] executing script from script
Hello. I wish that my Python program will not be stored on a single file. how canI call one python script from another ? Thanks Eli___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] numpy and python
I use Python 2.4 IDLE to open a py code which import numeric. I have installed both scipy and numpy into my c:\python24. However, it was still reported as: from Numeric import * ImportError: No module named Numeric I got confused... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] editing Path
Hi Eli, You really dont have to edit the search path, because if all the files lie in the same-directory as the top-level file, then Python automatically includes that directory in its search path. HTH, Regards, Asrarahmed On 11/6/06, Eli Brosh [EMAIL PROTECTED] wrote: Hello. Iam beginning to use python on windows. how canI add a path to Python search-list whereI can store my python scripts ? On IDLE the command browse path lets me to see the existing path but not to edit it. thanks Eli___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] executing script from script
Eli Brosh wrote: Hello. I wish that my Python program will not be stored on a single file. how can I call one python script from another ? Put part of the script in a module that you import from another module. Read more here: http://docs.python.org/tut/node8.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate
Hi Folks, I have written a function that takes a date and an integer representing the number of days. Please test it, comment onthe logic. Here is the code: CODE BEGINS The function takes two arguments, date and number of days. It checks for the right format and if the format is okay, it calculates the end date. import stringimport datetimeimport traceback def dateCheck(date1,num_days): flag = True startdate = None enddate = None if num_days 0 or num_days 31: flag = False print The argument for -n has to be between 0 and 31 return (flag,startdate,enddate) else: date_lst = string.split(date1,/) ln = len(date_lst) if ln != 3 : flag = False print The argument for -D option has to be in the format: dd/mm/ return (flag,startdate,enddate) else: date_lst.reverse() print date_lst try: if int(date_lst[0]) 2000: flag = False print The year cannot be earlier than 2000 and it should be in the format ''. return (flag,startdate,enddate) except ValueError: flag = False err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) try: startdate = datetime.date(int(date_lst[0]),int(date_lst[1]),int(date_lst[2])) enddate = startdate + datetime.timedelta(days=num_days) print startdate, enddate except ValueError: flag = False startdate = None enddate = None err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) if enddate datetime.date.today(): enddate = datetime.date.today() if startdate datetime.date.today(): flag = False startdate = None enddate = None print The -D option should have a date not later than today's date return (flag,startdate,enddate) CODE ENDS TIA. Regards, Asrarahmed -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] First real script
Hello to all, This is my first script, I mean the first that I'm trying to do on my own. Its a very simple Cellular Automata thing, the idea is that the initial list A_List is rewritten based on some rules, in this case Wolfram's rule 30. You can modify the list length and its initial state, you can also set the number of iterations. What I would like is to see how it can be improved. The basic functionality is done, I just want to listen some advise from experts like you : ) For example how can I improve the way in which the rules are written? Would you use the same method that I have chosen? And what about the if and else that are right after the two loops? they are there because if not when the loop gets to the last number an exception arises. Thanks a lot Carlos Here is the code: Note: Right now maya is not needed to run the code. #My first try at Cellular Automata #A very basic script that lets you play with Wolfram's rule 30 #if you wish to see the results in maya, you will need CGKit and Maya #from maya.api import * #from maya.mel import * import time #This is the initial state. You can put as many integers as you wish A_List = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] A_Len = len(A_List) print 'A_List: ',A_List print 'A_Len: ', A_Len B_List = [] S = A_Len print S #This is the number of iterations. for r in range (50): for i in range (S): #if i S-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] if a == 1 and b == 1 and c == 1: X = 0 elif a == 1 and b == 1 and c == 0: X = 0 elif a == 1 and b == 0 and c == 1: X = 0 elif a == 1 and b == 0 and c == 0: X = 1 elif a == 0 and b == 1 and c == 1: X = 1 elif a == 0 and b == 1 and c == 0: X = 1 elif a == 0 and b == 0 and c == 1: X = 1 elif a == 0 and b == 0 and c == 0: X = 0 #print i,a,b,c,X #if X == 1: #print r,i,X #polyCube() #move(r=(i,r,0)) B_List.append(X) print 'B_List: ',B_List A_List = B_List B_List = [] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] numpy and python
On Mon, 6 Nov 2006, linda.s wrote: I use Python 2.4 IDLE to open a py code which import numeric. I have installed both scipy and numpy into my c:\python24. However, it was still reported as: Hi Linda, We need more details. What version of scipy and numpy did you install? Where did you get them them from? This detail matters particularly for numpy, which has several different incarnations (Numeric, numarray, NumPy), and they all do similar-but-slightly-different things. Did you install the one from: http://numpy.scipy.org/ Also, what steps did you do to install those third-party modules? from Numeric import * ImportError: No module named Numeric I got confused... If you're using NumPy, then the correct package name for it is 'numpy', not 'Numeric'. from numpy import * Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate
On Mon, 6 Nov 2006, Asrarahmed Kadri wrote: I have written a function that takes a date and an integer representing the number of days. Please test it, comment on the logic . Hi Asrarahmed, You should be able to write your own tests too. You might want to look at: http://www.diveintopython.org/unit_testing/index.html for an example of how to write unit tests; the author there goes through an example with a Roman Numeral program written with unit tests. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
Alan Gauld wrote: Michael Sparks [EMAIL PROTECTED] wrote That's equivalent to the regular expression: * ^[0-9A-Za-z_.-]*$ While using a dictionary is probably overkill, so is a regex. A simple string holding all characters and an 'in' test would probably be both easier to read and faster. Which kind of illustrates the point of the thread I think! :-) Now, which is clearer? If you learn to read write regular expressions, then the short regular expression is the clearest form. It's also quicker. Whether its quicker will depend on several factors including the implementation of the regex library as well as the length of the string. If its a single char I'd expect the dictionary lookup to be faster than a regex parse or the string inclusion test... In fact this is how the C standard library usually implements functions like toupper() and tolower() etc, and for speed reasons. It's been a long time since I looked at the source for a C standard library but I remember these functions being implemented as direct table lookup - a static char* indexed by a character value - not dictionary lookup. If anyone really cares which Python implementation is faster, the timeit module is your friend. Assertions like would probably be faster or it's also quicker don't hold much weight. In Python, if you want to know what is faster, you must test. Kent, who doesn't have enough time or interest at the present to try timing it himself... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
On Mon, 6 Nov 2006, Carlos wrote: This is my first script, I mean the first that I'm trying to do on my own. Its a very simple Cellular Automata thing, the idea is that the initial list A_List is rewritten based on some rules, in this case Wolfram's rule 30. You can modify the list length and its initial state, you can also set the number of iterations. Hi Carlos, Cool. I did something like this a while ago too! http://mail.python.org/pipermail/tutor/2002-September/017256.html Looking at your code, the only suggestion I could make is to encode the rules into some kind of lookup structure. That is, the block: if a == 1 and b == 1 and c == 1: X = 0 elif a == 1 and b == 1 and c == 0: X = 0 elif a == 1 and b == 0 and c == 1: X = 0 elif a == 1 and b == 0 and c == 0: X = 1 elif a == 0 and b == 1 and c == 1: X = 1 elif a == 0 and b == 1 and c == 0: X = 1 elif a == 0 and b == 0 and c == 1: X = 1 elif a == 0 and b == 0 and c == 0: X = 0 could be tweaked to be more compact. Conceptually, it takes in three values (X, Y, Z), and returns a result in X. If we look at it in a different light, that's a key-value lookup, where the key is going to be a 3-tuple. So you can encode the guts of rule 30 with a dictionary: rule_30 = { (1, 1, 1) : 0, (1, 1, 0) : 0, (1, 0, 1) : 0, (1, 0, 0) : 1, (0, 1, 1) : 1, (0, 1, 0) : 1, (0, 0, 1) : 1, (0, 0, 0) : 0, } After we have this, the assignment to X looks much more simple: X = rule_30[x, y, z] Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] executing script from script
Eli Brosh [EMAIL PROTECTED] wrote I wish that my Python program will not be stored on a single file. how can I call one python script from another ? As Kent says normally you don't call one script from another, instead you write a set of functions (or classes) that you put in one or more modules. You then import those modules into your top level script (the one you actually execute) and call the functions in the modules. You can read more about this in my Modules and Functions topic in my tutorial. If you really do want to call a Python script you do it the same way as you would call any other executable program from inside a script: using the subprocess module. This is described in my Operating System topic, in the Other mechanisms for external program access subsection. 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] editing Path
Eli Brosh schrieb: Hello. I am beginning to use python on windows. how can I add a path to Python search-list where I can store my python scripts ? As has been said there are two aspects. If you want your scripts to execute as programs you need to modify the PATH environment variable MyComputer-Properties-Advanced-Env Variables But note that this only works inside a DOS box, if you are using the Start-Run dialog then I think you need to modify the registry someplace (I can't recall where) But normally you just double click the icon in Windows Explorer... OTOH if you want to import your scripts as modules into other scripts then you need to set the PYTHONPATH environment variable. If you want to do both you need to modify both variables. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help to debug this function.. it takes a date andnum. of days and returns startdate and enddate
Asrarahmed Kadri [EMAIL PROTECTED] wrote Please test it, comment on the logic . I haven't tested it but here are some comments: import string import datetime import traceback def dateCheck(date1,num_days): flag = True startdate = None enddate = None if num_days 0 or num_days 31: flag = False print The argument for -n has to be between 0 and 31 return (flag,startdate,enddate) else: You don't need the else since the if block returns. Thus you only reach the followiong code if the test is false. This reduces the anumber of levels of indenting by one which improves readability and thus maintenance. date_lst = string.split(date1,/) better to use the string methods. ie date1.split('/') ln = len(date_lst) if ln != 3 : you could have combined those lines into one since you never use 'ln' except in the test. if len(date1.split('/') != 3: flag = False print The argument for -D option has to be in the format: dd/mm/ return (flag,startdate,enddate) else: Same as above, the else is just adding levels of indentation. date_lst.reverse() print date_lst try: if int(date_lst[0]) 2000: flag = False print The year cannot be earlier than 2000 and it should be in the format ''. return (flag,startdate,enddate) except ValueError: flag = False err_msg = traceback.format_exc() index = string.find(err_msg,'Value') Again use the string method: index = err_msg.find('Value') print err_msg[index:] return (flag,startdate,enddate) try: startdate = datetime.date (int(date_lst[0]),int(date_lst[1]),int(date_lst[2])) enddate = startdate + datetime.timedelta(days=num_days) print startdate, enddate except ValueError: flag = False startdate = None enddate = None err_msg = traceback.format_exc() index = string.find(err_msg,'Value') print err_msg[index:] return (flag,startdate,enddate) Since this block is essentially identical to the except block above you could package them both as a function which would shorten the code a little. if enddate datetime.date.today(): enddate = datetime.date.today() if startdate datetime.date.today(): flag = False startdate = None enddate = None print The -D option should have a date not later than today's date Since this is a function and not part of the user interface there shouldn't really be any knowledge of the -D option in this code. What if you want to call it from another module that uses different options? It would be better to raise a ValueError which can be caught by the external program: raise ValueEerror (startdate later than today) return (flag,startdate,enddate) CODE ENDS 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
[Tutor] is gotchas?
I've been using python is 1.5* but haven't used `is` that much. 1)where do `is` and `==` yield the same results? 2)where do they not yield the same results? 3)is there a special method for `is'. 4)Pointers to docs are welcome. thanks tim -- Tim Johnson [EMAIL PROTECTED] http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Carlos [EMAIL PROTECTED] wrote Here is the code: Note: Right now maya is not needed to run the code. import time #This is the initial state. You can put as many integers as you wish A_List = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] A_Len = len(A_List) print 'A_List: ',A_List print 'A_Len: ', A_Len B_List = [] S = A_Len print S Not sure why you do this? Why not just use A_Len? #This is the number of iterations. for r in range (50): for i in range (S): #if i S-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] if a == 1 and b == 1 and c == 1: X = 0 elif a == 1 and b == 1 and c == 0: X = 0 elif a == 1 and b == 0 and c == 1: X = 0 I would rewrite these tests to use tuples: if (a,b,c) == (1,1,1): X = 0 elif (a,b,c) == (1,1,0): X = 0 elif (a,b,c) == (1,0,1): X = 0 etc... You could also use a dictionary to make it sligtly more concise: tests = {(1,1,1): 0, (1,1,0): 0,(1,0,0): 1} then X = tests[(a,b,c)] I find either option easier to read and maintain than the boolean expressions. B_List.append(X) print 'B_List: ',B_List A_List = B_List B_List = [] HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
Tim Johnson wrote: I've been using python is 1.5* but haven't used `is` that much. 1)where do `is` and `==` yield the same results? 2)where do they not yield the same results? is tests for object identity - 'a is b' is true if a is the same object as b. There is no special method, no specialization for different data types, just 'is it the same thing?' == tests for equality of value. It's exact meaning depends on the types of objects your are comparing. It can be specialized by defining a special method. a is b generally implies a == b because if a is b then a==b is the same as a==a which is true for pretty much anything - it would be a very strange type for which a == a is not true. Maybe NaN (Not a Number) compares false to itself, I'm not sure, I don't know how to create NaN on Windows. But really the meaning of == is defined by the underlying type so in your own classes you can make it do anything you want. a==b does not imply a is b - it is quite reasonable for two different things to have the same value: In [9]: a=[1,2] In [10]: b=[1,2] In [11]: a is b Out[11]: False In [12]: a==b Out[12]: True In [13]: a='abc**def' In [14]: b='abc' + '**def' In [15]: a is b Out[15]: False In [16]: a==b Out[16]: True 3)is there a special method for `is'. No. Kent 4)Pointers to docs are welcome. thanks tim ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate (fwd)
[Forwarding to Tutor; busy at the moment] -- Forwarded message -- Date: Mon, 6 Nov 2006 18:41:54 + From: Asrarahmed Kadri [EMAIL PROTECTED] To: Danny Yoo [EMAIL PROTECTED] Subject: Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate Hi Danny, Can you please test it !!! Also I would like to know if it can be coded in a better way... TIA. Regards, Asrarahmed On 11/6/06, Danny Yoo [EMAIL PROTECTED] wrote: On Mon, 6 Nov 2006, Asrarahmed Kadri wrote: I have written a function that takes a date and an integer representing the number of days. Please test it, comment on the logic . Hi Asrarahmed, You should be able to write your own tests too. You might want to look at: http://www.diveintopython.org/unit_testing/index.html for an example of how to write unit tests; the author there goes through an example with a Roman Numeral program written with unit tests. -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
Michael Sparks [EMAIL PROTECTED] wrote A regex compiles to a jump table, and executes as a statemachine. Sometimes, but it depends on the implementation. If someone uses a C++ compiler that uses the standard library implememation of regex (like say the Microsoft Visual C++ version up till V6 did) then they will not get that and they will have slow regex. The GNU compiler OTOH does provide fast regex. But it depends entirely on the implementation of the regex library. And can even depend on the compiler chosen in the case above since many dynamic languages use the underlying library for their regex implementation. or the implementation in the library is crap, and I don't believe for a second python would be that dumb) Maybe not, but C/C++ can be! Given you can compile the regex and use it over and over again (as was the context the example code (isplain) was executed in) using a regex is absolutely the best way. Fine if the user compiles it, but for one-off use its quite common not to compile regex. For one-off the compilation can be slower than the one-off execution. I'd be extremely surprised if you could get your suggested approach faster. Like I said it depends on an awful lot of factors. One reason perl is popular is that it has the worlds best regex implementation, it regularly beat compiled C programs when it first came out. Nowadays the regex libraries are improving, but the VB one, for example, is still pretty slow in my experience, even in VB.Net important. (heck, that's the reason regexes are useful - compact clear representations of a lexical structure that you want to check a string matches rather than obfuscated by the language doing the checking) I've never heard anyone claim that regex's were clear before :-) * ^[0-9A-Za-z_.-]*$ Is a very simple pattern, and as a result an extremely simple specification. That is quite simple for a regex, but I'd still argue that for beginners (which is what this list is about) thats still quite an eyeful. If any developer has a problem with that sort of pattern, they really need to go away and learn regexes, since they're missing important tools. (which shouldn't be over used). I agree totally. I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regexes. I think its complex for an novice amateur programmer. And to Kent's point re the C library, he is quite correct, toupper() etc use a lookup table not a dictionary, my mistake. But the difference between hashing and indexing is still less than a regex pattern match for a single character. And the point of timing is also valid, but I too can't be bothered to try... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] (OT) Flame wars (was: Amazing power of Regular Expressions...)
Greetings, all: -Original Message- Date: Mon, 6 Nov 2006 10:32:32 + From: Michael Sparks [EMAIL PROTECTED] Subject: Re: [Tutor] Amazing power of Regular Expressions... To: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain; charset=iso-8859-1 On Monday 06 November 2006 01:08, Alan Gauld wrote: While using a dictionary is probably overkill, so is a rage. No, in this case it's absolutely the right choice. A simple string holding all characters and an 'in' test would probably be both easier to read and faster. I'm stunned you think this. It's precisely this sort of naivete that baffles me with regard to regales. Which kind of illustrates the point of the thread I think! :-) Actually, no, it doesn't. snip I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regales. Michael. With the final sentence above, this thread has ceased to be an intellectual discussion and become a religious argument. Until then, I was enjoying an informative discussion by knowledgeable people on a topic of considerable interest. Now I'm upset by the implications of the statement and embarrassed on behalf of the writer. When a person his so convinced of his/her rightness that they feel justified in insulting those in opposition, that person has substituted flaming for advocacy. They have also, in my opinion, seriously weakened their position on the subject. Why would someone resort to such an attack if they were, in fact, correct? I am disappointed to see such behavior on this list, and I hope it's occurrence will continue to be vanishingly small. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars (was: Amazing power of Regular Expressions...)
Wow... I had to click this e-mail just because I saw the first posts on the mentioned thread and could see it turning for the worst.. I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regales. Michael.If this is your method to helping people, you should be the one to step back and go away. While your at it, go an take an educated look at debates.. You might learn that your tactics for trying to sway your side of the opinion are harsh and completely self killing. Any point you were trying to make just became invalid because of this childish b/s. On 11/6/06, Carroll, Barry [EMAIL PROTECTED] wrote: Greetings, all: -Original Message- Date: Mon, 6 Nov 2006 10:32:32 + From: Michael Sparks [EMAIL PROTECTED] Subject: Re: [Tutor] Amazing power of Regular Expressions... To: tutor@python.org Message-ID: [EMAIL PROTECTED] Content-Type: text/plain;charset=iso-8859-1 On Monday 06 November 2006 01:08, Alan Gauld wrote: While using a dictionary is probably overkill, so is a rage. No, in this case it's absolutely the right choice. A simple string holding all characters and an 'in' test wouldprobably be both easier to read and faster. I'm stunned you think this. It's precisely this sort of naivete that baffles me with regard to regales. Which kind of illustrates the point of the thread I think! :-) Actually, no, it doesn't.snip I'm serious, if you think ^[0-9A-Za-z_.-]*$ is unclear and complex, go away and relearn regales. Michael.With the final sentence above, this thread has ceased to be anintellectual discussion and become a religious argument.Until then, I was enjoying an informative discussion by knowledgeable people on atopic of considerable interest.Now I'm upset by the implications ofthe statement and embarrassed on behalf of the writer.When a person his so convinced of his/her rightness that they feel justified in insulting those in opposition, that person has substitutedflaming for advocacy.They have also, in my opinion, seriously weakenedtheir position on the subject.Why would someone resort to such an attack if they were, in fact, correct?I am disappointed to see such behavior on this list, and I hope it'soccurrence will continue to be vanishingly small.Regards,Barry [EMAIL PROTECTED]541-302-1107We who cut mere stones must always be envisioning cathedrals.-Quarry worker's creed___ Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
On 07/11/06, Kent Johnson [EMAIL PROTECTED] wrote: If anyone really cares which Python implementation is faster, the timeit module is your friend. Assertions like would probably be faster or it's also quicker don't hold much weight. In Python, if you want to know what is faster, you must test. Hmm, what exactly is the contentious code? Morpork:~ repton$ python -m timeit -s 's=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-' 'J in s' 100 loops, best of 3: 0.295 usec per loop Morpork:~ repton$ python -m timeit -s 'import re' -s 'r = re.compile([0-9A-Za-z_.-])' 'r.match(J)' 100 loops, best of 3: 1.16 usec per loop -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Hi again, Thanks for your comments they are really appreciated. Alan, yes you are right, there is no need to use S, A_Len works the same way. Beginner mistake The dictionary way seems to be way better than my idea, will give it a try. And Danny, your CA is very nice. Do you know a better way to do this? if i A_Len-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] if I dont do this I get the following error: c = A_List[i+1] IndexError: list index out of range I have the impression that this can be done in a less clunky way. Again thanks for your comments. : ) Best Regards, Carlos. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
Wow... I had to click this e-mail just because I saw the first posts on the mentioned thread and could see it turning for the worst.. Hi everyone, So let's try to squash this one now. There are more interesting problems to solve. Or other flame wars to fight. Let me see if we can do something constructive. I've been doing a shallow, superficial study of the Ruby language at the moment. One of the things I've been impressed about is that they've managed to make lambdas look non-threatening to people with their syntactic sugar of code blocks. For example, ## Ruby # def twice yield yield twice { puts hello world } # This prints out hello world twice in a row: the twice() function takes in an implicit code block, which it can later call by using their 'yield' statement. What the Ruby folks are doing is trying to make the use of higher-order procedures look really simple. In fact, most of the encouraged idiom style I've seen so far extensively uses this code style pervasively (especially for iteration), and that's very admirable. The exact functionality can be done in Python, but it does look a little more intimidating at first: ## Python def twice(f): f() f() twice(lambda: sys.stdout.write(hello world\n)) This does the same thing, but it looks a little scarier because the concepts needed to grasp his are superficially harder than that in the Ruby code. Anyway, let's derail off this regex flamewar and get us back to talking about code and about stuff that actually matters, like learning how to use functions well.. *wink* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Do you know a better way to do this? if i A_Len-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] Hi Carlos, Here's one way to handle it. If you're familiar with modulo clock arithmetic, you might want to apply it above. Here's an example: for i in [1, 2, 3, 11, 12, 13, 14]: ... print i, i % 12 ... 1 1 2 2 3 3 11 11 12 0 13 1 14 2 The idea is that the second columns results are the result of doing: i % 12 and that number rolls around twelve. Your index can roll around A_Len. There are other alternative approaches to handle the boundary case. We can talk about them if you'd like. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Carlos [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Do you know a better way to do this? if i A_Len-1: a = A_List[i-1] b = A_List[i] c = A_List[i+1] else: a = A_List[i-1] b = A_List[i] c = A_List[0] You would think so, just by looking at it, but I must confess I can't offhand think of anytthing significantly better. The only way to make it more consistent would be to 1) implement a real circular list (there probably is one out there somewhere) 2) always duplicate the first entry at the end of the list, then stop an len-2. HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Danny Yoo [EMAIL PROTECTED] wrote Here's one way to handle it. If you're familiar with modulo clock arithmetic, you might want to apply it above. Indeed, I should have thought of that. Good catch Danny. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
Danny Yoo [EMAIL PROTECTED] wrote So let's try to squash this one now. There are more interesting problems to solve. Or other flame wars to fight. I wasn't aware we were having a war, but I'm happy to desist :-) Let me see if we can do something constructive. I've been doing a shallow, superficial study of the Ruby language at the moment. One of the things I've been impressed about is that they've managed to make lambdas look non-threatening to people with their syntactic sugar of code blocks. Ruby blocks are almost as good as Smalltalk blocks for this kind of thing and very powerful. Regular readers will know I have often expressed dissappointment at the limitations of Python's lambdas, it's one thing the Ruby boys have got right IMHO. The exact functionality can be done in Python, but it does look a little more intimidating at first: ## Python def twice(f): f() f() twice(lambda: sys.stdout.write(hello world\n)) This does the same thing, but it looks a little scarier because the concepts needed to grasp his are superficially harder than that in the Ruby code. The other advantage in Ruby is that the block can be arbitrarily complex, not just a single expression as in a Python lambda. This allows us to embed loops and all sorts, effectively adding new command structures to the language in a way that only Lisp and Tcl have really been good at up till now. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
Chris Hengge wrote: I may have just missed the point to your attempt to derail this conversation =P Ah, well, don't worry. I didn't learn of lambda until I'd been using Python for a year or more. I was trying to pass arguments to callbacks in TKinter. one of the Pythonistas (Alan, Danny, Kent) told me Oh, that's trivial with lambda and since then, I've tried to read up on lambda and Functional Programming in general. However.. Why do all that when you can just str = Hello World print str * 2 (Maybe I missed some concept that this small example doesn't accuratly reflect) Yes, I do believe you're correct here, Chris :) I will not presume to know enough about lambda to explain it to you, but I will refer you to these articles: http://www.secnetix.de/~olli/Python/lambda_functions.hawk and Alan Gauld's tutorial, of course :) specifically, the page http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm Or browse there from the main page http://www.freenetpages.co.uk/hp/alan.gauld/ click 'functional programming' under Advanced Topics' if you want the menu frame to remain on the left of the screen. Consider this: You don't say outputstring = Hello, World! print outputstring because you're only using the string once, and it's not something that would look ugly all on one line. Instead, you do print Hello, World! An alternate example: a_list = [[a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a]] print a_list would make more sense than print [[a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a], [a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a,b,a]] because then if you need to change the list, or use it again somewhere, you don't have to go through the pain of typing it out each time, since in the first case, you assigned it to a variable, a_list. The long and short of it is: (or more specifically, the short of it) lambda lets you define functions you don't have to bind to a name. so, supposing you have the function def call_a_function(a_function): a_function() That will call a function object, you can do something like this: def f(): sys.stdout.write(Hello, World!) call_a_function(f) or you could do call_a_function(lambda: sys.stdout.write(Hello, World!)) It's like the string example above. It's a waste to have the function definition on two lines, and the call on another line, if the function's compact enough to fit on a single line using lambda. But also note that you can't reuse the lambda function unless you store it in a variable. In this way, it's similar to the 'print Hello, World!' statement. I hope that helps you, Chris. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First real script
Danny Yoo wrote: Do you know a better way to do this? [snip stuff] Hi Carlos, Here's one way to handle it. If you're familiar with modulo clock arithmetic, you might want to apply it above. Also, consider this example, Carlos: aList = [1,2,3,4,5,6] a,b,c = aList[1:4] a 2 b 3 c 4 HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
* Alan Gauld [EMAIL PROTECTED] [061106 14:01]: The other advantage in Ruby is that the block can be arbitrarily complex, not just a single expression as in a Python lambda. This allows us to embed loops and all sorts, effectively adding new command structures to the language in a way that only Lisp and Tcl have really been good at up till now. Sorry Alan, but you are leaving out rebol. Command structures in rebol are are just functions and IMHO, easier to roll your own than lisp macros. But with freedom comes responsibility. (Tim: rebol = 50% python = 50%) -- Tim Johnson [EMAIL PROTECTED] http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
On Mon, 6 Nov 2006, Chris Hengge wrote: I may have just missed the point to your attempt to derail this conversation =P Hi Chris, Ah! Are we talking about regular expressions anymore? No? Good. *grin* Why do all that when you can just str = Hello World print str * 2 Let me do a more substantial example. As you know, Python's for loop works on iterables: # for x in list(hello): ...print x ... h e l l o # We're running a for loop across a list of characters. In this case, our list is iterable. (We could iterate directly on the string itself, but let's stick with lists for the moment.) An iterable in Python is something that can give us an iterator. ### my_iterator = iter(list(hello)) ### An iterator is something that responses to next() requests until we consume everything: # my_iterator.next() 'h' my_iterator.next() 'e' my_iterator.next() 'l' my_iterator.next() 'l' my_iterator.next() 'o' my_iterator.next() Traceback (most recent call last): File stdin, line 1, in ? StopIteration ## So there's a few layers of indirection here. iterable - iterator - elements Ruby takes a different approach: they also have an iterator protocol, but what they require is something that provides an each() method. For example: irb(main):002:0 'hello'.split(//).each {|c| puts c} h e l l o This each method takes in a code block, and runs it on every element in the thing we're iterating across. The iterable itself provides the looping mechanism instead of the client code. The concept sorta looks like this in Python: ### class MyString: def __init__(self, s): self.s = s def each(self, f): i = 0 while i len(self.s): f(self.s[i]) i = i + 1 MyString(hello).each(lambda c: sys.stdout.write(c + '\n')) This, too, iterates across our iterable. The one handling the control flow is the 'each' method, which is a little wacky to think about at first. The Ruby folks make this work because their syntax is custom tailored for this pattern, so it's easier to read and write. I'm probably not doing it much justice with my ugly examples. *grin* ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] numpy and python
[Danny] If you're using NumPy, then the correct package name for it is 'numpy', not 'Numeric'. from numpy import * [Linda] I think the code is suing Numeric (is it called numpy now? if so, how to make the change?) So it's not your code? If it's not your own code then, nail down what the required external modules are, since that's important to know. Look for the word Numeric in their sources: if that's what they use, then they are using the older Numeric module, and not the numpy module that you've installed. In your case, assuming the old code is Numeric, I'd recommend just installing the old Numeric module as well. We want to avoid any weird backward-compatibility issues that might come up with numpy. (You can try to migrating that code to numpy later, once you're on a stable Numeric platform. See the top of http://numpy.scipy.org/ which mentions a program called numpy.oldnumeric.alter_code1 that should address this.) You can find Numeric here: http://sourceforge.net/project/showfiles.php?group_id=1369package_id=1351 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] 3D rendered bar chart (made of glass)
Dear Guys, I have downloaded CGkit and Aqsis and tried the examples from it. I run the samples, like the torus with grass. It is simple fantastic. I would like to make some artistic visualization with the power of python and the beauty of a professional renderer. I think about colored semitranslucent glass cubes. Like a simple bar graph, but the cube's 3D position, extension, color and text would be defined by database content and some calculus. It would be fine to make some axes and making the 3D view settings in an interactive 3D program. May you recommend any simple solution about it ? Yours sincerely, __ Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] a line
What does Pythonw -i test.py -i do in Mac machine? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (OT) Flame wars
On Monday 06 November 2006 22:52, Alan Gauld wrote: I wasn't aware we were having a war, but I'm happy to desist :-) FWIW, I wasn't aware of one either. (Mind you I've often noticed what passes for plain speaking in the UK passes for vehement flame war elsewhere, so maybe that's it) Anyway, if that's what people here think a flame war looks like... Well, a) I'll try and avoid such /mild/ comments in future ;) b) good for such people, real flame wars are really nasty ! Michael. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
* Kent Johnson [EMAIL PROTECTED] [061106 10:31]: In [9]: a=[1,2] In [10]: b=[1,2] Hmmm! Hmmm! Lookee here: ## console session a=[1,2] b=[1,2] a is b False c='1' ## one byte d='1' ## one byte c is d True c='1,2' d='1,2' c is d False The Hmmm! is emmitted because I'm thinking that if everything is an object in python, then why does `c is d` evaluate to True when the assigned value is 1 byte and evaluate to False when the assigned value is more that 1 byte? I think I ran into this before and that's why I never used `is'. Good thread. Beats flame wars. thanks tim -- Tim Johnson [EMAIL PROTECTED] http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
For small string object python has optimization method so it is really the same object!Cheers,pujoOn 11/7/06, Tim Johnson [EMAIL PROTECTED] wrote:* Kent Johnson [EMAIL PROTECTED] [061106 10:31]: In [9]: a=[1,2] In [10]: b=[1,2]Hmmm! Hmmm!Lookee here:## console session a=[1,2] b=[1,2] a is b False c='1'## one byte d='1'## one byte c is dTrue c='1,2' d='1,2' c is dFalseThe Hmmm! is emmitted because I'm thinking that if everything is an object in python, then why does `c is d` evaluate to True whenthe assigned value is 1 byte and evaluate to False when the assignedvalue is more that 1 byte?I think I ran into this before and that's why I never used `is'. Good thread. Beats flame wars.thankstim--Tim Johnson [EMAIL PROTECTED]http://www.alaska-internet-solutions.com ___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
Just out of curiousity (since I really can't say myself), does the code below import re each time it loops? I ran the same commands and saw quite similar results (0.176 usec per loop for the first test and 0.993 usec per loop for the second test), and I was just curious if that import (and the re.compile, for that matter) happen with each loop? Jonathon John Fouhy wrote: On 07/11/06, Kent Johnson [EMAIL PROTECTED] wrote: If anyone really cares which Python implementation is faster, the timeit module is your friend. Assertions like would probably be faster or it's also quicker don't hold much weight. In Python, if you want to know what is faster, you must test. Hmm, what exactly is the contentious code? Morpork:~ repton$ python -m timeit -s 's=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-' 'J in s' 100 loops, best of 3: 0.295 usec per loop Morpork:~ repton$ python -m timeit -s 'import re' -s 'r = re.compile([0-9A-Za-z_.-])' 'r.match(J)' 100 loops, best of 3: 1.16 usec per loop ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Amazing power of Regular Expressions...
On 07/11/06, Jonathon Sisson [EMAIL PROTECTED] wrote: Just out of curiousity (since I really can't say myself), does the code below import re each time it loops? I ran the same commands and saw quite similar results (0.176 usec per loop for the first test and 0.993 usec per loop for the second test), and I was just curious if that import (and the re.compile, for that matter) happen with each loop? Nope. Here's the command again: python -m timeit -s 'import re' -s 'r = re.compile([0-9A-Za-z_.-])' 'r.match(J)' -s means startup code. So, 'import re' and 're.compile(...)' happen only once, before the main test starts. You can read help on timeit by typing 'import timeit; help(timeit)' in the python console. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
c='1' ## one byte d='1' ## one byte c is d True c='1,2' d='1,2' c is d False The Hmmm! is emmitted because I'm thinking that if everything is an object in python, then why does `c is d` evaluate to True when the assigned value is 1 byte and evaluate to False when the assigned value is more that 1 byte? 'is' is the operator you want if you want to check for object identity. You should probably not use it for strings, or for immutables for that matter. Its value here is undefined above in the sense that our programs shouldn't depend on the behavior you're seeing there. (And you'll see different behavior depending on if Python is being run as an interpreter vs. on a whole program. On a whole program, all the duplicate string literals tend to be shared since Python strings are immutable.) A closer look at: http://docs.python.org/ref/objects.html is helpful, especially near the bottom. 'is' is relatively rare; I've seen it used most often in code dealing with object caches. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
On 11/6/06, Tim Johnson [EMAIL PROTECTED] wrote: * Kent Johnson [EMAIL PROTECTED] [061106 10:31]: In [9]: a=[1,2] In [10]: b=[1,2]Hmmm! Hmmm!Lookee here:## console session a=[1,2] b=[1,2] a is bFalse c='1'## one byte d='1'## one byte c is dTrue c='1,2' d='1,2' c is dFalseThe Hmmm! is emmitted because I'm thinking that if everything is anobject in python, then why does `c is d` evaluate to True whenthe assigned value is 1 byte and evaluate to False when the assigned value is more that 1 byte?I think I ran into this before and that's why I never used `is'.You might want to try: a = 'a' b = 'a' a is b TrueWhy? Interned strings. As Pujo aluded to, various simple or well-used objects (like the digits between 0 and 100), and strings that have been interned with the intern() function.There is a unique item: None. There is only one object of type NoneType. No matter how many times you reference it, it will always be the same object. So it is a perfect use of is: def f(arg1, arg2, optarg=None): if optarg is None: -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is gotchas?
others already gave good responses, so mine are short. 1)where do `is` and `==` yield the same results? is is object identity comparison while == is object value comparison 2)where do they not yield the same results? they give different results when you have two different objects regardless of the equality of their values. 3)is there a special method for `is'. no, not really. you can use id() and '==' to proxy for is: a is b == id(a) == id(b) 4)Pointers to docs are welcome. http://docs.python.org/lib/comparisons.html http://docs.python.org/ref/comparisons.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Core Python Programming, Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to set PYTHONPATH
How do i set the PYTHONPATH variable ? From answers to my query on "editing path" I realized that this is what should be done if i want to include another folder in the Python search path. I tried: import sys sys.path.append('additional path') but it worked only at runtime and is forgotten when I restart Python. I would like to append the PYTHONPATH permanently. How is it done under Windows XP ? Thank you very much for your attention Eli Brosh___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor