From steve at pearwood.info Tue Mar 1 00:44:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2011 10:44:37 +1100 Subject: [Tutor] string conversion In-Reply-To: <4D6C1377.4040407@ed.ac.uk> References: <4D6C1377.4040407@ed.ac.uk> Message-ID: <4D6C3365.8050104@pearwood.info> Robert Clement wrote: > Hi > > I have a wxpython control in which users are intended to enter control > characters used to define binary string delimiters, eg. '\xBA\xBA' or > '\t\r\n' . Do you mean that your users enter *actual* control characters? What do they type to enter (say) an ASCII null character into the field? Or do you mean they type the string representation of the control character, e.g. for ASCII null they press \ then 0 on their keyboard, and the field shows \0 rather than one of those funny little square boxes you get for missing characters in fonts. I will assume you mean the second, because I can't imagine how to enter control characters directly into a field (other than the simple ones like newline and tab). > The string returned by the control is a unicode version of the string > entered by the user, eg. u'\\xBA\\xBA' or u'\\t\\r\\n' . The data you are dealing with is binary, that is, made up of bytes between 0 and 255. The field is Unicode, that is, made up of characters with code points between 0 and some upper limit which is *much* higher than 255. If wxpython has some way to set the encoding of the field to ASCII, that will probably save you a lot of grief; otherwise, you'll need to decide what you want to do if the user types something like ? or ? or other unicode characters. In any case, it seems that you are expecting strings with the representation of control characters, rather than actual control characters. > I would like to be able retrieve the original string containing the > escaped control characters or hex values so that I can assign it to a > variable to be used to split the binary string. You have the original string -- the user typed , and you are provided . Remember that backslashes in Python are special, and so they are escaped when displaying the string. Because \t is used for the display of tab, it can't be used for the display of backslash-t. Instead the display of backslash is backslash-backslash. But that's just the *display*, not the string itself. If you type \t into your field, and retrieve the string which looks like u'\\t', if you call len() on the string you will get 2, not 3, or 6. If you print it with the print command, it will print as \t with no string delimiters u' and ' and no escaped backslash. So you have the original string, exactly as typed by the user. I *think* what you want is to convert it to *actual* control characters, so that a literal backslash-t is converted to a tab character, etc. >>> s = u'\\t' >>> print len(s), s, repr(s) 2 \t u'\\t' >>> t = s.decode('string_escape') >>> print len(t), t, repr(t) 1 '\t' Hope that helps. -- Steven From benderjacob44 at gmail.com Tue Mar 1 00:49:18 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Mon, 28 Feb 2011 18:49:18 -0500 Subject: [Tutor] Socket and Changing IP's Message-ID: <4D6C347E.7000101@gmail.com> Tutors, I was looking into network programming, and I came across a problem. Socket programs need an IP address to function correctly, right? Well, IP addresses are always changing, so how should I go about making sockets that will work for an extended period of time? Thanks in advance! From waynejwerner at gmail.com Tue Mar 1 00:57:42 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 28 Feb 2011 17:57:42 -0600 Subject: [Tutor] Socket and Changing IP's In-Reply-To: <4D6C347E.7000101@gmail.com> References: <4D6C347E.7000101@gmail.com> Message-ID: On Mon, Feb 28, 2011 at 5:49 PM, Jacob Bender wrote: > Tutors, > > I was looking into network programming, and I came across a problem. > Socket programs need an IP address to function correctly, right? Well, IP > addresses are always changing, so how should I go about making sockets that > will work for an extended period of time? Thanks in advance! If your IP address is changing that frequently, something is probably wrong! Your IP should basically stay the same from the time you connect to the internet until the time you disconnect - longer if you use static IPs. What are you attempting to program? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Tue Mar 1 01:02:23 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Mon, 28 Feb 2011 19:02:23 -0500 Subject: [Tutor] Socket and Changing IP's In-Reply-To: References: <4D6C347E.7000101@gmail.com> Message-ID: <4D6C378F.6080806@gmail.com> On 2/28/2011 6:57 PM, Wayne Werner wrote: > On Mon, Feb 28, 2011 at 5:49 PM, Jacob Bender > wrote: > > Tutors, > > I was looking into network programming, and I came across a > problem. Socket programs need an IP address to function correctly, > right? Well, IP addresses are always changing, so how should I go > about making sockets that will work for an extended period of > time? Thanks in advance! > > > If your IP address is changing that frequently, something is probably > wrong! > > Your IP should basically stay the same from the time you connect to > the internet until the time you disconnect - longer if you use static IPs. > > What are you attempting to program? > > -Wayne I'm trying to be a host without having to keep the computer on ALL of the time. Acting as a "Dropbox" would be an example. My IP doesn't change very often. It's stayed the same for days. -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Tue Mar 1 01:04:40 2011 From: smokefloat at gmail.com (David Hutto) Date: Mon, 28 Feb 2011 19:04:40 -0500 Subject: [Tutor] Socket and Changing IP's In-Reply-To: <4D6C378F.6080806@gmail.com> References: <4D6C347E.7000101@gmail.com> <4D6C378F.6080806@gmail.com> Message-ID: On Mon, Feb 28, 2011 at 7:02 PM, Jacob Bender wrote: > On 2/28/2011 6:57 PM, Wayne Werner wrote: > > On Mon, Feb 28, 2011 at 5:49 PM, Jacob Bender > wrote: >> >> Tutors, >> >> ? ?I was looking into network programming, and I came across a problem. >> Socket programs need an IP address to function correctly, right? Well, IP >> addresses are always changing, so how should I go about making sockets that >> will work for an extended period of time? Thanks in advance! > > If your IP address is changing that frequently, something is probably wrong! > Your IP should basically stay the same from the time you connect to the > internet until the time you disconnect - longer if you use static IPs. > What are you attempting to program? > -Wayne > > ??? I'm trying to be a host without having to keep the computer on ALL of > the time. If you don't want your computer on, and you want your hosting services allocated elsewhere, then why are you worried about that particular dynamically changing address? Go static with "offsite". Acting as a "Dropbox" would be an example. My IP doesn't change > very often. It's stayed the same for days. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From alan.gauld at btinternet.com Tue Mar 1 02:20:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2011 01:20:33 -0000 Subject: [Tutor] Timer with exe command References: Message-ID: "Kaden McLaws" wrote > I would like to set up the following using python: > A timer that is activated when a user logs on to our computer, > then shuts the computer down when the timer runs out You can do that from the Operating System, no programming required. But hopw you do it wioll depend on which Operating System you are running, which is about the only thing you omit to mention! Assuming it's Windows take a look at the 'at' command... If its Linux or MacOS try 'cron' > parsing. It would be effective if the last time the timer activated > was recorded in a txt file, logged, so that the program can > check and ensure that the last time the timer ended was > at least 12 hours ago, so the computer just isnt turned > right back on for another 90 mins repeatedly. That's a little bit more tricky but doable in a startup script. Python might be a suitable medium for that task. > Is there also a way to run the python hidden in the > background so he cannot just figure out how to close it? Not really. If he knows how to drive the OS well then pretty much anything you do can be traced. You can of course disguise the name of the script so it looks harmless, but you can't hide the interpreter - unless you have a separate copy with an obscure name... HTH, Alan G. From bouncingcats at gmail.com Tue Mar 1 07:49:02 2011 From: bouncingcats at gmail.com (David) Date: Tue, 1 Mar 2011 17:49:02 +1100 Subject: [Tutor] A class that instantiates conditionally ? Message-ID: I have an idea that might clean up my code slightly, if I can make one of my classes clever enough to refuse to instantiate itself if a necessary condition is not met. Below I propose some example code that seems to achieve this, and I am asking here for feedback on it, because I have not written much python. So I might be doing something unwise due to fiddling with things I don't totally understand. My aim is that instead of writing this: class MyClass: pass condition = 0 if condition: my_object = MyClass() else: my_object = None I could instead write this: class MyClass_2: # put the if-test here inside the class my_object_2 = MyClass_2(condition) to achieve the goal that (my_object_2 == None) when (condition == False). I read the (ver 2.6) Python Language Reference Section 3.4.1. Basic customization Section 3.4.3. Customizing class creation Most of the content there is way beyond my current understanding, but I came up with the following code, which seems to work: class MyClass_2(object): def __new__(self, condition): if condition: return object.__new__(self) else: return None condition = 0 my_object_2 = MyClass_2(condition) print my_object_2 condition = 1 my_object_2 = MyClass_2(condition) print my_object_2 Can anyone see any technical or style issues with that? Or alternatively reassure me that it is completely ok? Thanks. From sander.sweers at gmail.com Tue Mar 1 08:25:09 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 01 Mar 2011 08:25:09 +0100 Subject: [Tutor] Socket and Changing IP's In-Reply-To: <4D6C378F.6080806@gmail.com> References: <4D6C347E.7000101@gmail.com> <4D6C378F.6080806@gmail.com> Message-ID: <1298964309.2242.5.camel@Nokia-N900> On Tue,? 1 Mar 2011, 01:02:23 CET, Jacob Bender wrote: >? ? ? ? ? I'm trying to be a host without having to keep the computer on ALL > of the time. Acting as a "Dropbox" would be an example. My IP doesn't > change very often. It's stayed the same for days. The best solution here is to get a hostname from a service like dyndns.org. It has easy ways to update the ip address off the hostname. Then from your script connect to the hostname instead of the ip directly. Br sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.klaitos at gmail.com Tue Mar 1 09:49:56 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Tue, 1 Mar 2011 09:49:56 +0100 Subject: [Tutor] Multiples python files In-Reply-To: References: Message-ID: Thank you all for answers. Again. 2011/2/28 Alan Gauld > > "Christopher Brookes" wrote > > > I don't understand >> >> @classmethod >> def DisplayAll(cls, herosAll): >> >> What is cls ? >> > > This is one of the advanced techniques I referred to a few days ago. > > Basically the "best"(?) solution to your problem is to store the list of > characters inside the Character class as what is known as a class variable. > > Then everytime you create a new Character you can add it to the list by > the init method. And when a character is deleted you remove it via the del > method. > > You can then define class methods to read/print the list, find out how many > characters exist etc. > > This is much cleaner than keeping a separate global variable since the code > for managing characters is all in one place with the classs definition. But > it does introduce a bunch of new syntax features which I didn't think you > were ready for yet! :-) > > One thing you will need to be very careful about as you go forward is > namespaces. Remember that everytime you import a module you need to precede > any names in that module with the module name. And names inside a class need > to be preceded by the class name. And names inside objects need to be > preceded by the object (variable) name. > If the class is inside a module you need to use both module and class. Thus > if the Character class is defined inside character.py you would have > something like this in main.py: > > import character > myObj = character.Character(....) > print myObj.display() > print character.Character.displayAll() > > etc. > > You can simplify it by using the "from m import v" style: > > from character import Character > myObj = Character(....) > myObj.display() > Character.displayAll() > > etc. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hanlie.pretorius at gmail.com Tue Mar 1 10:21:37 2011 From: hanlie.pretorius at gmail.com (Hanlie Pretorius) Date: Tue, 1 Mar 2011 11:21:37 +0200 Subject: [Tutor] Accessing a DLL from python Message-ID: Hi Python Tutors, I'm using a storm water modelling program, EPA SWMM, to model the hydrology and hydraulics of a study area. SWMM reports its results in a binary (.out) file that contains the results for each element in the model at each time step in the model run. According to the SWMM interface manual (http://www.epa.gov/ednnrmrl/models/swmm/swmm5_iface.zip), one can use a DLL file to read the .out file. I want to do this so that I can read the state of a river at a specific time and plot its water level in a GIS. After some searching on the Internet, I came across ctypes, which I have tried. According to the SWMM manual: [manual] Opening the Output File ---------------------------------- A function named OpenSwmmOutFile(outFile) that performs these tasks is contained in the example code files that accompany this guide. The argument to the function is the name of the binary output file. The return value from the function is an integer code with the following meanings: 0 - the run was successful 1 - the run was terminated with an error 2 - the output file could not be opened. [/manual] So, I tried the following python code: [code] In [14]: swmmdll = cdll.LoadLibrary("C:\\Hanlie\\model\\SWMM\\swmm5_0_018.dll") In [15]: results_file="C:\\Hanlie\\model\\SWMM\\c83a_v0\\c83a_v0.3.out" In [16]: open_file=swmmdll.OpenSwmmOutFile(results_file) ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'OpenSwmmOutFile' not found [/code] Can anyone perhaps help me to access the functions in this DLL? The manual also states: [manual] The following files are needed for applications that call functions from the swmm5.dll library: ? swmm5.h for C/C++ applications ? swmm5.bas for Visual Basic applications ? swmm5.pas for Delphi applications. [/manual] And they give an example in C, Basic and Pascal to use the interface. I have appended the C example to this message. Thanks Hanlie [code] // swmm5_iface.c // // Example code for interfacing SWMM 5 with C/C++ programs. // // Remember to #include the file swmm5_iface.h in the calling program. #include #include #include "swmm5.h" int SWMM_Nperiods; // number of reporting periods int SWMM_FlowUnits; // flow units code int SWMM_Nsubcatch; // number of subcatchments int SWMM_Nnodes; // number of drainage system nodes int SWMM_Nlinks; // number of drainage system links int SWMM_Npolluts; // number of pollutants tracked double SWMM_StartDate; // start date of simulation int SWMM_ReportStep; // reporting time step (seconds) int RunSwmmExe(char* cmdLine); int RunSwmmDll(char* inpFile, char* rptFile, char* outFile); int OpenSwmmOutFile(char* outFile); int GetSwmmResult(int iType, int iIndex, int vIndex, int period, float* value); void CloseSwmmOutFile(void); static const int SUBCATCH = 0; static const int NODE = 1; static const int LINK = 2; static const int SYS = 3; static const int RECORDSIZE = 4; // number of bytes per file record static int SubcatchVars; // number of subcatch reporting variables static int NodeVars; // number of node reporting variables static int LinkVars; // number of link reporting variables static int SysVars; // number of system reporting variables static FILE* Fout; // file handle static int StartPos; // file position where results start static int BytesPerPeriod; // bytes used for results in each period static void ProcessMessages(void); //----------------------------------------------------------------------------- int RunSwmmExe(char* cmdLine) //----------------------------------------------------------------------------- { int exitCode; STARTUPINFO si; PROCESS_INFORMATION pi; // --- initialize data structures memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); si.wShowWindow = SW_SHOWNORMAL; // --- launch swmm5.exe exitCode = CreateProcess(NULL, cmdLine, NULL, NULL, 0, 0, NULL, NULL, &si, &pi); // --- wait for program to end exitCode = WaitForSingleObject(pi.hProcess, INFINITE); // --- retrieve the error code produced by the program GetExitCodeProcess(pi.hProcess, &exitCode); // --- release handles CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return exitCode; } //----------------------------------------------------------------------------- int RunSwmmDll(char* inpFile, char* rptFile, char* outFile) //----------------------------------------------------------------------------- { int err; double elapsedTime; // --- open a SWMM project err = swmm_open(inpFile, rptFile, outFile); if (!err) { // --- initialize all processing systems err = swmm_start(1); if (err == 0) { // --- step through the simulation do { // --- allow Windows to process any pending events ProcessMessages(); // --- extend the simulation by one routing time step err = swmm_step(&elapsedTime); ///////////////////////////////////////////// // --- call progress reporting function here, // using elapsedTime as an argument ///////////////////////////////////////////// } while (elapsedTime > 0.0 && err == 0); // --- close all processing systems swmm_end(); } } // --- close the project swmm_close(); return err; } //----------------------------------------------------------------------------- void ProcessMessages(void) //----------------------------------------------------------------------------- { /**** Only use this function with a Win32 application ***** MSG msg; while (TRUE) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) break; else { TranslateMessage(&msg); DispatchMessage(&msg); } } else break; } ***********************************************************/ } //----------------------------------------------------------------------------- int OpenSwmmOutFile(char* outFile) //----------------------------------------------------------------------------- { int magic1, magic2, errCode, offset, offset0, version; int err; // --- open the output file Fout = fopen(outFile, "rb"); if (Fout == NULL) return 2; // --- check that file contains at least 14 records fseek(Fout, 0L, SEEK_END); if (ftell(Fout) < 14*RECORDSIZE) { fclose(Fout); return 1; } // --- read parameters from end of file fseek(Fout, -5*RECORDSIZE, SEEK_END); fread(&offset0, RECORDSIZE, 1, Fout); fread(&StartPos, RECORDSIZE, 1, Fout); fread(&SWMM_Nperiods, RECORDSIZE, 1, Fout); fread(&errCode, RECORDSIZE, 1, Fout); fread(&magic2, RECORDSIZE, 1, Fout); // --- read magic number from beginning of file fseek(Fout, 0L, SEEK_SET); fread(&magic1, RECORDSIZE, 1, Fout); // --- perform error checks if (magic1 != magic2) err = 1; else if (errCode != 0) err = 1; else if (SWMM_Nperiods == 0) err = 1; else err = 0; // --- quit if errors found if (err > 0 ) { fclose(Fout); Fout = NULL; return err; } // --- otherwise read additional parameters from start of file fread(&version, RECORDSIZE, 1, Fout); fread(&SWMM_FlowUnits, RECORDSIZE, 1, Fout); fread(&SWMM_Nsubcatch, RECORDSIZE, 1, Fout); fread(&SWMM_Nnodes, RECORDSIZE, 1, Fout); fread(&SWMM_Nlinks, RECORDSIZE, 1, Fout); fread(&SWMM_Npolluts, RECORDSIZE, 1, Fout); // Skip over saved subcatch/node/link input values offset = (SWMM_Nsubcatch+2) * RECORDSIZE // Subcatchment area + (3*SWMM_Nnodes+4) * RECORDSIZE // Node type, invert & max depth + (5*SWMM_Nlinks+6) * RECORDSIZE; // Link type, z1, z2, max depth & length offset = offset0 + offset; fseek(Fout, offset, SEEK_SET); // Read number & codes of computed variables fread(&SubcatchVars, RECORDSIZE, 1, Fout); // # Subcatch variables fseek(Fout, SubcatchVars*RECORDSIZE, SEEK_CUR); fread(&NodeVars, RECORDSIZE, 1, Fout); // # Node variables fseek(Fout, NodeVars*RECORDSIZE, SEEK_CUR); fread(&LinkVars, RECORDSIZE, 1, Fout); // # Link variables fseek(Fout, LinkVars*RECORDSIZE, SEEK_CUR); fread(&SysVars, RECORDSIZE, 1, Fout); // # System variables // --- read data just before start of output results offset = StartPos - 3*RECORDSIZE; fseek(Fout, offset, SEEK_SET); fread(&SWMM_StartDate, sizeof(double), 1, Fout); fread(&SWMM_ReportStep, RECORDSIZE, 1, Fout); // --- compute number of bytes of results values used per time period BytesPerPeriod = 2*RECORDSIZE + // date value (a double) (SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars+ SWMM_Nlinks*LinkVars + SysVars)*RECORDSIZE; // --- return with file left open return err; } //----------------------------------------------------------------------------- int GetSwmmResult(int iType, int iIndex, int vIndex, int period, float* value) //----------------------------------------------------------------------------- { int offset; // --- compute offset into output file *value = 0.0; offset = StartPos + (period-1)*BytesPerPeriod + 2*RECORDSIZE; if ( iType == SUBCATCH ) { offset += RECORDSIZE*(iIndex*SubcatchVars + vIndex); } else if (iType == NODE) { offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + iIndex*NodeVars + vIndex); } else if (iType == LINK) { offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars + iIndex*LinkVars + vIndex); } else if (iType == SYS) { offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + SWMM_Nnodes*NodeVars + SWMM_Nlinks*LinkVars + vIndex); } else return 0; // --- re-position the file and read the result fseek(Fout, offset, SEEK_SET); fread(value, RECORDSIZE, 1, Fout); return 1; } //----------------------------------------------------------------------------- void CloseSwmmOutFile(void) //----------------------------------------------------------------------------- { if (Fout != NULL) { fclose(Fout); Fout = NULL; } } [/code] From hanlie.pretorius at gmail.com Tue Mar 1 13:22:26 2011 From: hanlie.pretorius at gmail.com (Hanlie Pretorius) Date: Tue, 1 Mar 2011 14:22:26 +0200 Subject: [Tutor] Accessing a DLL from python In-Reply-To: References: Message-ID: I see that I have misread the manual and that I need to reproduce the code in the C example in python. The SWMM DLL doesn't contain ready-made functions to open files etc. Apologies for posting before I was completely sure of the problem. Hanlie 2011/3/1, Hanlie Pretorius : > Hi Python Tutors, > > I'm using a storm water modelling program, EPA SWMM, to model the > hydrology and hydraulics of a study area. > > SWMM reports its results in a binary (.out) file that contains the > results for each element in the model at each time step in the model > run. According to the SWMM interface manual > (http://www.epa.gov/ednnrmrl/models/swmm/swmm5_iface.zip), one can use > a DLL file to read the .out file. I want to do this so that I can read > the state of a river at a specific time and plot its water level in a > GIS. > > After some searching on the Internet, I came across ctypes, which I > have tried. According to the SWMM manual: > > [manual] > Opening the Output File > ---------------------------------- > A function named OpenSwmmOutFile(outFile) that performs these tasks is > contained in the example code files that accompany this guide. The > argument to the function is the name of the binary output file. The > return value from the function is an integer code with the following > meanings: > 0 - the run was successful > 1 - the run was terminated with an error > 2 - the output file could not be opened. > [/manual] > > So, I tried the following python code: > [code] > In [14]: swmmdll = > cdll.LoadLibrary("C:\\Hanlie\\model\\SWMM\\swmm5_0_018.dll") > > In [15]: results_file="C:\\Hanlie\\model\\SWMM\\c83a_v0\\c83a_v0.3.out" > > In [16]: open_file=swmmdll.OpenSwmmOutFile(results_file) > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__ > func = self.__getitem__(name) > File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: function 'OpenSwmmOutFile' not found > [/code] > > Can anyone perhaps help me to access the functions in this DLL? > > The manual also states: > [manual] > The following files are needed for applications that call functions > from the swmm5.dll library: > ? swmm5.h for C/C++ applications > ? swmm5.bas for Visual Basic applications > ? swmm5.pas for Delphi applications. > [/manual] > > And they give an example in C, Basic and Pascal to use the interface. > I have appended the C example to this message. > > Thanks > Hanlie > > [code] > // swmm5_iface.c > // > // Example code for interfacing SWMM 5 with C/C++ programs. > // > // Remember to #include the file swmm5_iface.h in the calling program. > > #include > #include > #include "swmm5.h" > > int SWMM_Nperiods; // number of reporting periods > int SWMM_FlowUnits; // flow units code > int SWMM_Nsubcatch; // number of subcatchments > int SWMM_Nnodes; // number of drainage system nodes > int SWMM_Nlinks; // number of drainage system links > int SWMM_Npolluts; // number of pollutants tracked > double SWMM_StartDate; // start date of simulation > int SWMM_ReportStep; // reporting time step (seconds) > > int RunSwmmExe(char* cmdLine); > int RunSwmmDll(char* inpFile, char* rptFile, char* outFile); > int OpenSwmmOutFile(char* outFile); > int GetSwmmResult(int iType, int iIndex, int vIndex, int period, > float* value); > void CloseSwmmOutFile(void); > > static const int SUBCATCH = 0; > static const int NODE = 1; > static const int LINK = 2; > static const int SYS = 3; > static const int RECORDSIZE = 4; // number of bytes per file record > > static int SubcatchVars; // number of subcatch reporting > variables > static int NodeVars; // number of node reporting > variables > static int LinkVars; // number of link reporting > variables > static int SysVars; // number of system reporting > variables > > static FILE* Fout; // file handle > static int StartPos; // file position where results start > static int BytesPerPeriod; // bytes used for results in each > period > static void ProcessMessages(void); > > //----------------------------------------------------------------------------- > int RunSwmmExe(char* cmdLine) > //----------------------------------------------------------------------------- > { > int exitCode; > STARTUPINFO si; > PROCESS_INFORMATION pi; > > // --- initialize data structures > memset(&si, 0, sizeof(si)); > memset(&pi, 0, sizeof(pi)); > si.cb = sizeof(si); > si.wShowWindow = SW_SHOWNORMAL; > > // --- launch swmm5.exe > exitCode = CreateProcess(NULL, cmdLine, NULL, NULL, 0, > 0, NULL, NULL, &si, &pi); > > // --- wait for program to end > exitCode = WaitForSingleObject(pi.hProcess, INFINITE); > > // --- retrieve the error code produced by the program > GetExitCodeProcess(pi.hProcess, &exitCode); > > // --- release handles > CloseHandle(pi.hProcess); > CloseHandle(pi.hThread); > return exitCode; > } > > > //----------------------------------------------------------------------------- > int RunSwmmDll(char* inpFile, char* rptFile, char* outFile) > //----------------------------------------------------------------------------- > { > int err; > double elapsedTime; > > // --- open a SWMM project > err = swmm_open(inpFile, rptFile, outFile); > if (!err) > { > // --- initialize all processing systems > err = swmm_start(1); > if (err == 0) > { > // --- step through the simulation > do > { > // --- allow Windows to process any pending events > ProcessMessages(); > > // --- extend the simulation by one routing time step > err = swmm_step(&elapsedTime); > > ///////////////////////////////////////////// > // --- call progress reporting function here, > // using elapsedTime as an argument > ///////////////////////////////////////////// > > } while (elapsedTime > 0.0 && err == 0); > > // --- close all processing systems > swmm_end(); > } > } > > // --- close the project > swmm_close(); > return err; > } > > > //----------------------------------------------------------------------------- > void ProcessMessages(void) > //----------------------------------------------------------------------------- > { > > /**** Only use this function with a Win32 application ***** > MSG msg; > while (TRUE) > { > if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) > { > if (msg.message == WM_QUIT) break; > else > { > TranslateMessage(&msg); > DispatchMessage(&msg); > } > } > else break; > } > ***********************************************************/ > > } > > > //----------------------------------------------------------------------------- > int OpenSwmmOutFile(char* outFile) > //----------------------------------------------------------------------------- > { > int magic1, magic2, errCode, offset, offset0, version; > int err; > > // --- open the output file > Fout = fopen(outFile, "rb"); > if (Fout == NULL) return 2; > > // --- check that file contains at least 14 records > fseek(Fout, 0L, SEEK_END); > if (ftell(Fout) < 14*RECORDSIZE) > { > fclose(Fout); > return 1; > } > > // --- read parameters from end of file > fseek(Fout, -5*RECORDSIZE, SEEK_END); > fread(&offset0, RECORDSIZE, 1, Fout); > fread(&StartPos, RECORDSIZE, 1, Fout); > fread(&SWMM_Nperiods, RECORDSIZE, 1, Fout); > fread(&errCode, RECORDSIZE, 1, Fout); > fread(&magic2, RECORDSIZE, 1, Fout); > > // --- read magic number from beginning of file > fseek(Fout, 0L, SEEK_SET); > fread(&magic1, RECORDSIZE, 1, Fout); > > // --- perform error checks > if (magic1 != magic2) err = 1; > else if (errCode != 0) err = 1; > else if (SWMM_Nperiods == 0) err = 1; > else err = 0; > > // --- quit if errors found > if (err > 0 ) > { > fclose(Fout); > Fout = NULL; > return err; > } > > // --- otherwise read additional parameters from start of file > fread(&version, RECORDSIZE, 1, Fout); > fread(&SWMM_FlowUnits, RECORDSIZE, 1, Fout); > fread(&SWMM_Nsubcatch, RECORDSIZE, 1, Fout); > fread(&SWMM_Nnodes, RECORDSIZE, 1, Fout); > fread(&SWMM_Nlinks, RECORDSIZE, 1, Fout); > fread(&SWMM_Npolluts, RECORDSIZE, 1, Fout); > > // Skip over saved subcatch/node/link input values > offset = (SWMM_Nsubcatch+2) * RECORDSIZE // Subcatchment area > + (3*SWMM_Nnodes+4) * RECORDSIZE // Node type, invert & max > depth > + (5*SWMM_Nlinks+6) * RECORDSIZE; // Link type, z1, z2, > max depth & length > offset = offset0 + offset; > fseek(Fout, offset, SEEK_SET); > > // Read number & codes of computed variables > fread(&SubcatchVars, RECORDSIZE, 1, Fout); // # Subcatch variables > fseek(Fout, SubcatchVars*RECORDSIZE, SEEK_CUR); > fread(&NodeVars, RECORDSIZE, 1, Fout); // # Node variables > fseek(Fout, NodeVars*RECORDSIZE, SEEK_CUR); > fread(&LinkVars, RECORDSIZE, 1, Fout); // # Link variables > fseek(Fout, LinkVars*RECORDSIZE, SEEK_CUR); > fread(&SysVars, RECORDSIZE, 1, Fout); // # System variables > > // --- read data just before start of output results > offset = StartPos - 3*RECORDSIZE; > fseek(Fout, offset, SEEK_SET); > fread(&SWMM_StartDate, sizeof(double), 1, Fout); > fread(&SWMM_ReportStep, RECORDSIZE, 1, Fout); > > // --- compute number of bytes of results values used per time period > BytesPerPeriod = 2*RECORDSIZE + // date value (a double) > (SWMM_Nsubcatch*SubcatchVars + > SWMM_Nnodes*NodeVars+ > SWMM_Nlinks*LinkVars + > SysVars)*RECORDSIZE; > > // --- return with file left open > return err; > } > > > //----------------------------------------------------------------------------- > int GetSwmmResult(int iType, int iIndex, int vIndex, int period, float* > value) > //----------------------------------------------------------------------------- > { > int offset; > > // --- compute offset into output file > *value = 0.0; > offset = StartPos + (period-1)*BytesPerPeriod + 2*RECORDSIZE; > if ( iType == SUBCATCH ) > { > offset += RECORDSIZE*(iIndex*SubcatchVars + vIndex); > } > else if (iType == NODE) > { > offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + > iIndex*NodeVars + vIndex); > } > else if (iType == LINK) > { > offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + > SWMM_Nnodes*NodeVars + > iIndex*LinkVars + vIndex); > } > else if (iType == SYS) > { > offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + > SWMM_Nnodes*NodeVars + > SWMM_Nlinks*LinkVars + vIndex); > } > else return 0; > > // --- re-position the file and read the result > fseek(Fout, offset, SEEK_SET); > fread(value, RECORDSIZE, 1, Fout); > return 1; > } > > > //----------------------------------------------------------------------------- > void CloseSwmmOutFile(void) > //----------------------------------------------------------------------------- > { > if (Fout != NULL) > { > fclose(Fout); > Fout = NULL; > } > } > [/code] > From hanlie.pretorius at gmail.com Tue Mar 1 13:33:22 2011 From: hanlie.pretorius at gmail.com (Hanlie Pretorius) Date: Tue, 1 Mar 2011 14:33:22 +0200 Subject: [Tutor] Accessing a DLL from python In-Reply-To: References: Message-ID: Can anyone perhaps suggest the easiest way of translating the C code into Python, bearing in mind that I'm rather a beginner? Thanks Hanlie 2011/3/1, Hanlie Pretorius : > I see that I have misread the manual and that I need to reproduce the > code in the C example in python. The SWMM DLL doesn't contain > ready-made functions to open files etc. > > Apologies for posting before I was completely sure of the problem. > > Hanlie > > 2011/3/1, Hanlie Pretorius : >> Hi Python Tutors, >> >> I'm using a storm water modelling program, EPA SWMM, to model the >> hydrology and hydraulics of a study area. >> >> SWMM reports its results in a binary (.out) file that contains the >> results for each element in the model at each time step in the model >> run. According to the SWMM interface manual >> (http://www.epa.gov/ednnrmrl/models/swmm/swmm5_iface.zip), one can use >> a DLL file to read the .out file. I want to do this so that I can read >> the state of a river at a specific time and plot its water level in a >> GIS. >> >> After some searching on the Internet, I came across ctypes, which I >> have tried. According to the SWMM manual: >> >> [manual] >> Opening the Output File >> ---------------------------------- >> A function named OpenSwmmOutFile(outFile) that performs these tasks is >> contained in the example code files that accompany this guide. The >> argument to the function is the name of the binary output file. The >> return value from the function is an integer code with the following >> meanings: >> 0 - the run was successful >> 1 - the run was terminated with an error >> 2 - the output file could not be opened. >> [/manual] >> >> So, I tried the following python code: >> [code] >> In [14]: swmmdll = >> cdll.LoadLibrary("C:\\Hanlie\\model\\SWMM\\swmm5_0_018.dll") >> >> In [15]: results_file="C:\\Hanlie\\model\\SWMM\\c83a_v0\\c83a_v0.3.out" >> >> In [16]: open_file=swmmdll.OpenSwmmOutFile(results_file) >> ------------------------------------------------------------ >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\Python26\lib\ctypes\__init__.py", line 366, in __getattr__ >> func = self.__getitem__(name) >> File "C:\Python26\lib\ctypes\__init__.py", line 371, in __getitem__ >> func = self._FuncPtr((name_or_ordinal, self)) >> AttributeError: function 'OpenSwmmOutFile' not found >> [/code] >> >> Can anyone perhaps help me to access the functions in this DLL? >> >> The manual also states: >> [manual] >> The following files are needed for applications that call functions >> from the swmm5.dll library: >> ? swmm5.h for C/C++ applications >> ? swmm5.bas for Visual Basic applications >> ? swmm5.pas for Delphi applications. >> [/manual] >> >> And they give an example in C, Basic and Pascal to use the interface. >> I have appended the C example to this message. >> >> Thanks >> Hanlie >> >> [code] >> // swmm5_iface.c >> // >> // Example code for interfacing SWMM 5 with C/C++ programs. >> // >> // Remember to #include the file swmm5_iface.h in the calling program. >> >> #include >> #include >> #include "swmm5.h" >> >> int SWMM_Nperiods; // number of reporting periods >> int SWMM_FlowUnits; // flow units code >> int SWMM_Nsubcatch; // number of subcatchments >> int SWMM_Nnodes; // number of drainage system nodes >> int SWMM_Nlinks; // number of drainage system links >> int SWMM_Npolluts; // number of pollutants tracked >> double SWMM_StartDate; // start date of simulation >> int SWMM_ReportStep; // reporting time step (seconds) >> >> int RunSwmmExe(char* cmdLine); >> int RunSwmmDll(char* inpFile, char* rptFile, char* outFile); >> int OpenSwmmOutFile(char* outFile); >> int GetSwmmResult(int iType, int iIndex, int vIndex, int period, >> float* value); >> void CloseSwmmOutFile(void); >> >> static const int SUBCATCH = 0; >> static const int NODE = 1; >> static const int LINK = 2; >> static const int SYS = 3; >> static const int RECORDSIZE = 4; // number of bytes per file record >> >> static int SubcatchVars; // number of subcatch reporting >> variables >> static int NodeVars; // number of node reporting >> variables >> static int LinkVars; // number of link reporting >> variables >> static int SysVars; // number of system reporting >> variables >> >> static FILE* Fout; // file handle >> static int StartPos; // file position where results >> start >> static int BytesPerPeriod; // bytes used for results in each >> period >> static void ProcessMessages(void); >> >> //----------------------------------------------------------------------------- >> int RunSwmmExe(char* cmdLine) >> //----------------------------------------------------------------------------- >> { >> int exitCode; >> STARTUPINFO si; >> PROCESS_INFORMATION pi; >> >> // --- initialize data structures >> memset(&si, 0, sizeof(si)); >> memset(&pi, 0, sizeof(pi)); >> si.cb = sizeof(si); >> si.wShowWindow = SW_SHOWNORMAL; >> >> // --- launch swmm5.exe >> exitCode = CreateProcess(NULL, cmdLine, NULL, NULL, 0, >> 0, NULL, NULL, &si, &pi); >> >> // --- wait for program to end >> exitCode = WaitForSingleObject(pi.hProcess, INFINITE); >> >> // --- retrieve the error code produced by the program >> GetExitCodeProcess(pi.hProcess, &exitCode); >> >> // --- release handles >> CloseHandle(pi.hProcess); >> CloseHandle(pi.hThread); >> return exitCode; >> } >> >> >> //----------------------------------------------------------------------------- >> int RunSwmmDll(char* inpFile, char* rptFile, char* outFile) >> //----------------------------------------------------------------------------- >> { >> int err; >> double elapsedTime; >> >> // --- open a SWMM project >> err = swmm_open(inpFile, rptFile, outFile); >> if (!err) >> { >> // --- initialize all processing systems >> err = swmm_start(1); >> if (err == 0) >> { >> // --- step through the simulation >> do >> { >> // --- allow Windows to process any pending events >> ProcessMessages(); >> >> // --- extend the simulation by one routing time step >> err = swmm_step(&elapsedTime); >> >> ///////////////////////////////////////////// >> // --- call progress reporting function here, >> // using elapsedTime as an argument >> ///////////////////////////////////////////// >> >> } while (elapsedTime > 0.0 && err == 0); >> >> // --- close all processing systems >> swmm_end(); >> } >> } >> >> // --- close the project >> swmm_close(); >> return err; >> } >> >> >> //----------------------------------------------------------------------------- >> void ProcessMessages(void) >> //----------------------------------------------------------------------------- >> { >> >> /**** Only use this function with a Win32 application ***** >> MSG msg; >> while (TRUE) >> { >> if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) >> { >> if (msg.message == WM_QUIT) break; >> else >> { >> TranslateMessage(&msg); >> DispatchMessage(&msg); >> } >> } >> else break; >> } >> ***********************************************************/ >> >> } >> >> >> //----------------------------------------------------------------------------- >> int OpenSwmmOutFile(char* outFile) >> //----------------------------------------------------------------------------- >> { >> int magic1, magic2, errCode, offset, offset0, version; >> int err; >> >> // --- open the output file >> Fout = fopen(outFile, "rb"); >> if (Fout == NULL) return 2; >> >> // --- check that file contains at least 14 records >> fseek(Fout, 0L, SEEK_END); >> if (ftell(Fout) < 14*RECORDSIZE) >> { >> fclose(Fout); >> return 1; >> } >> >> // --- read parameters from end of file >> fseek(Fout, -5*RECORDSIZE, SEEK_END); >> fread(&offset0, RECORDSIZE, 1, Fout); >> fread(&StartPos, RECORDSIZE, 1, Fout); >> fread(&SWMM_Nperiods, RECORDSIZE, 1, Fout); >> fread(&errCode, RECORDSIZE, 1, Fout); >> fread(&magic2, RECORDSIZE, 1, Fout); >> >> // --- read magic number from beginning of file >> fseek(Fout, 0L, SEEK_SET); >> fread(&magic1, RECORDSIZE, 1, Fout); >> >> // --- perform error checks >> if (magic1 != magic2) err = 1; >> else if (errCode != 0) err = 1; >> else if (SWMM_Nperiods == 0) err = 1; >> else err = 0; >> >> // --- quit if errors found >> if (err > 0 ) >> { >> fclose(Fout); >> Fout = NULL; >> return err; >> } >> >> // --- otherwise read additional parameters from start of file >> fread(&version, RECORDSIZE, 1, Fout); >> fread(&SWMM_FlowUnits, RECORDSIZE, 1, Fout); >> fread(&SWMM_Nsubcatch, RECORDSIZE, 1, Fout); >> fread(&SWMM_Nnodes, RECORDSIZE, 1, Fout); >> fread(&SWMM_Nlinks, RECORDSIZE, 1, Fout); >> fread(&SWMM_Npolluts, RECORDSIZE, 1, Fout); >> >> // Skip over saved subcatch/node/link input values >> offset = (SWMM_Nsubcatch+2) * RECORDSIZE // Subcatchment area >> + (3*SWMM_Nnodes+4) * RECORDSIZE // Node type, invert & max >> depth >> + (5*SWMM_Nlinks+6) * RECORDSIZE; // Link type, z1, z2, >> max depth & length >> offset = offset0 + offset; >> fseek(Fout, offset, SEEK_SET); >> >> // Read number & codes of computed variables >> fread(&SubcatchVars, RECORDSIZE, 1, Fout); // # Subcatch variables >> fseek(Fout, SubcatchVars*RECORDSIZE, SEEK_CUR); >> fread(&NodeVars, RECORDSIZE, 1, Fout); // # Node variables >> fseek(Fout, NodeVars*RECORDSIZE, SEEK_CUR); >> fread(&LinkVars, RECORDSIZE, 1, Fout); // # Link variables >> fseek(Fout, LinkVars*RECORDSIZE, SEEK_CUR); >> fread(&SysVars, RECORDSIZE, 1, Fout); // # System variables >> >> // --- read data just before start of output results >> offset = StartPos - 3*RECORDSIZE; >> fseek(Fout, offset, SEEK_SET); >> fread(&SWMM_StartDate, sizeof(double), 1, Fout); >> fread(&SWMM_ReportStep, RECORDSIZE, 1, Fout); >> >> // --- compute number of bytes of results values used per time period >> BytesPerPeriod = 2*RECORDSIZE + // date value (a double) >> (SWMM_Nsubcatch*SubcatchVars + >> SWMM_Nnodes*NodeVars+ >> SWMM_Nlinks*LinkVars + >> SysVars)*RECORDSIZE; >> >> // --- return with file left open >> return err; >> } >> >> >> //----------------------------------------------------------------------------- >> int GetSwmmResult(int iType, int iIndex, int vIndex, int period, float* >> value) >> //----------------------------------------------------------------------------- >> { >> int offset; >> >> // --- compute offset into output file >> *value = 0.0; >> offset = StartPos + (period-1)*BytesPerPeriod + 2*RECORDSIZE; >> if ( iType == SUBCATCH ) >> { >> offset += RECORDSIZE*(iIndex*SubcatchVars + vIndex); >> } >> else if (iType == NODE) >> { >> offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + >> iIndex*NodeVars + vIndex); >> } >> else if (iType == LINK) >> { >> offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + >> SWMM_Nnodes*NodeVars + >> iIndex*LinkVars + vIndex); >> } >> else if (iType == SYS) >> { >> offset += RECORDSIZE*(SWMM_Nsubcatch*SubcatchVars + >> SWMM_Nnodes*NodeVars + >> SWMM_Nlinks*LinkVars + vIndex); >> } >> else return 0; >> >> // --- re-position the file and read the result >> fseek(Fout, offset, SEEK_SET); >> fread(value, RECORDSIZE, 1, Fout); >> return 1; >> } >> >> >> //----------------------------------------------------------------------------- >> void CloseSwmmOutFile(void) >> //----------------------------------------------------------------------------- >> { >> if (Fout != NULL) >> { >> fclose(Fout); >> Fout = NULL; >> } >> } >> [/code] >> > From stefan_ml at behnel.de Tue Mar 1 13:53:08 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 01 Mar 2011 13:53:08 +0100 Subject: [Tutor] Accessing a DLL from python In-Reply-To: References: Message-ID: Hanlie Pretorius, 01.03.2011 13:33: > Can anyone perhaps suggest the easiest way of translating the C code > into Python, bearing in mind that I'm rather a beginner? A beginner of what? Python? Programming in general? The C code you posted doesn't look too complex, so you could try to translate it (mostly literally) into Python syntax and use Cython to wrap that in a binary extension. Cython is basically Python, but it allows you to call directly into C code. Here's a tutorial: http://docs.cython.org/src/tutorial/clibraries.html Stefan From emanuel.lauria at gmail.com Tue Mar 1 16:19:02 2011 From: emanuel.lauria at gmail.com (Emanuel Lauria) Date: Tue, 1 Mar 2011 16:19:02 +0100 Subject: [Tutor] couchdb.mapping 'Document' class Message-ID: Hi everyone, I'm trying to map a couchdb document to a python object using couchdb.mapping. I'm stuck in the very first part were it says I should declare a Python class that inherits from the 'Document'.. Where does this 'Document' superclass comes from? I can't resolve it. Or do I have to create it? How? Could someone point me in to the right direction? >>> import couchdb >>> class Person(Document): ... name = TextField() ... Traceback (most recent call last): File "", line 1, in NameError: name 'Document' is not defined Thanks for your help, and please forgive me if im too n00b in this. I havent found any documentation except http://packages.python.org/CouchDB/mapping.html which is not enough. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 1 17:31:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2011 16:31:27 -0000 Subject: [Tutor] A class that instantiates conditionally ? References: Message-ID: "David" wrote > clever enough to refuse to instantiate itself if a necessary > condition > is not met. > > class MyClass_2(object): > def __new__(self, condition): > if condition: > return object.__new__(self) > else: > return None Thats pretty much how I'd do it. Alan G. From alan.gauld at btinternet.com Tue Mar 1 17:35:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2011 16:35:54 -0000 Subject: [Tutor] A class that instantiates conditionally ? References: Message-ID: "David" wrote > clever enough to refuse to instantiate itself if a necessary > condition > is not met. Oops, sent too soon. I meant to add that you should realize that the implication of your design is that the user of the class now has to check each object to see if it is a valid reference or None. You could raise an exception instead of returning None which allows a try/except style... This extra overhead is one reason these kinds of "clever" tricks are usually avoided. A valid object with null content is often preferrable, or a singleton style pattern. But occasionally your style is needed, just be aware of the extra overhead you introduce by using it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From coolankur2006 at gmail.com Tue Mar 1 17:44:51 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 1 Mar 2011 22:14:51 +0530 Subject: [Tutor] Recommendation for Pygame Message-ID: Hey Any good recommendation (ebook,links,videos,Live Example) to get started with the pygame api. I am totally new to pygame. Thanks in advance. Waiting for the suggestions :):) Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Mar 1 18:06:28 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 1 Mar 2011 18:06:28 +0100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: Message-ID: On Tue, Mar 1, 2011 at 5:35 PM, Alan Gauld wrote: > > "David" wrote > >> clever enough to refuse to instantiate itself if a necessary condition >> is not met. > > Oops, sent too soon. > > I meant to add that you should realize that the implication of your > design is that the user of the class now has to check each object > to see if it is a valid reference or None. You could raise an exception > instead of returning None which allows a try/except style... > > This extra overhead is one reason these kinds of "clever" tricks > are usually avoided. A valid object with null content is often > preferrable, or a singleton style pattern. But occasionally your > style is needed, just be aware of the extra overhead you > introduce by using it. > Side question: Any reason why you'd raise the exception from __new__ rather than __init__? If you want to return None, then yeah I can see why you'd have to use __new__, but would there be any reason you can't or shouldn't simply raise an exception from __init__? From cfuller084 at thinkingplanet.net Tue Mar 1 18:27:40 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 1 Mar 2011 11:27:40 -0600 Subject: [Tutor] Recommendation for Pygame In-Reply-To: References: Message-ID: <201103011127.42279.cfuller084@thinkingplanet.net> http://www.pyweek.org/ Cheers On Tuesday 01 March 2011, ANKUR AGGARWAL wrote: > Hey > Any good recommendation (ebook,links,videos,Live Example) to get started > with the pygame api. I am totally new to pygame. > Thanks in advance. Waiting for the suggestions :):) > Ankur Aggarwal From alan.gauld at btinternet.com Tue Mar 1 18:50:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2011 17:50:18 -0000 Subject: [Tutor] A class that instantiates conditionally ? References: Message-ID: "Hugo Arts" wrote > Side question: Any reason why you'd raise the exception from __new__ > rather than __init__? If you want to return None, then yeah I can > see > why you'd have to use __new__, but would there be any reason you > can't > or shouldn't simply raise an exception from __init__? Because by the time you get to init you have already created the instance. If you really want to avoid creating an instance it needs to be in new. Alan G From alan.gauld at btinternet.com Tue Mar 1 18:51:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Mar 2011 17:51:50 -0000 Subject: [Tutor] Recommendation for Pygame References: Message-ID: "ANKUR AGGARWAL" wrote > Any good recommendation (ebook,links,videos,Live Example) to get > started > with the pygame api. I am totally new to pygame. > Thanks in advance. Waiting for the suggestions :):) Have you looked at the tutorial on the pygamje web site? Also the Dietel book has a chapter on Pygame. Expensive book but you might get it via a library? Alan G. From scarolan at gmail.com Tue Mar 1 18:55:12 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Mar 2011 11:55:12 -0600 Subject: [Tutor] Dynamically assign variable names to tuple objects Message-ID: Maybe someone can help with this. I have a function that takes a single file as an argument and outputs a tuple with each line of the file as a string element. This is part of a script that is intended to concatenate lines in files, and output them to a different file. This is as far as I've gotten: import sys myfiles = tuple(sys.argv[1:]) numfiles = len(myfiles) def makeTuple(file): outlist = [] f = open(file, 'r') for line in f.readlines(): line = line.rstrip(' \n') outlist.append(line) return tuple(outlist) for i in range(numfiles): makeTuple(myfiles[i]) The script creates the tuples as it was intended to, but I'm not sure how to assign variable names to each tuple so that I can work with them afterwards. How would you dynamically assign variable names to each tuple created by makeTuple(), so that they can be manipulated further? From scarolan at gmail.com Tue Mar 1 19:10:49 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Mar 2011 12:10:49 -0600 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On Tue, Mar 1, 2011 at 11:55 AM, Sean Carolan wrote: > Maybe someone can help with this. ?I have a function that takes a > single file as an argument and outputs a tuple with each line of the > file as a string element. ?This is part of a script that is intended > to concatenate lines in files, and output them to a different file. Not sure if this is the "right" or best way to do this, but I ended up using vars() to assign my variable names, like so: import sys myfiles = tuple(sys.argv[1:]) numfiles = len(myfiles) varlist = [] def makeTuple(file): 6 lines: outlist = [] ---------- for i in range(numfiles): varlist.append('tuple'+str(i)) vars()[varlist[i]] = makeTuple(myfiles[i]) From fsalamero at gmail.com Tue Mar 1 19:12:38 2011 From: fsalamero at gmail.com (Fernando Salamero) Date: Tue, 1 Mar 2011 19:12:38 +0100 Subject: [Tutor] Recommendation for pygame In-Reply-To: References: Message-ID: I teach videogames programming to my students using Python and Pygame: http://pythonwiki.wikispaces.com Sorry, in spanish... From martin at linux-ip.net Tue Mar 1 19:44:51 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 1 Mar 2011 19:44:51 +0100 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: Sean, : Maybe someone can help with this. I have a function that takes a : single file as an argument and outputs a tuple with each line of : the file as a string element. This is part of a script that is : intended to concatenate lines in files, and output them to a : different file. This is as far as I've gotten: : : : import sys : : myfiles = tuple(sys.argv[1:]) : numfiles = len(myfiles) : : def makeTuple(file): : outlist = [] : f = open(file, 'r') : for line in f.readlines(): : line = line.rstrip(' \n') : outlist.append(line) : return tuple(outlist) : : for i in range(numfiles): : makeTuple(myfiles[i]) : : : The script creates the tuples as it was intended to, but I'm not sure : how to assign variable names to each tuple so that I can work with : them afterwards. How would you dynamically assign variable names to : each tuple created by makeTuple(), so that they can be manipulated : further? Well, your function makeTuple() is returning something. You could simply take the returned result and assign that to whatever variable you wish. Some minor notes: * Your use of numFiles, i.e. 'for i in range(numFiles):' is not necessary, you can iterate directly over the file list. * You are using 'f.readlines()' which loads the whole file into memory (not that this is important in this example, since you are reading the whole file into memory, anyway). Nonetheless, one wonderfully pythonic feature is that you can iterate directly over File-like objects. Try this: file = open(filename,'r') for line in file: # -- do something with each line * It seems a bit strange to me that you want to use a tuple for the contents of these files. A list of lines in a file seems more natural (to me). Tuples are hashable, which is quite convenient, but you can't modify them. * You use a tuple also for the list of files the user has passed. Why not just use the list you already have? sys.argv * There are different camps on the creation of lists and dictionaries. I find the English-like creation easier to read, so I always do: d = dict() # -- same as d = {} l = list() # -- same as l = [] Do you know how to use a dictionary? It seems a natural for what it looks like you are trying to do (although you have not explained your intent, so can only guess). d = dict() for file in sys.argv[1:]: d[file] = makeTuple(file) You then sent this: : for i in range(numfiles): : varlist.append('tuple'+str(i)) : vars()[varlist[i]] = makeTuple(myfiles[i]) I saw in your follow-up that you went straight for vars(). I really don't think that's what you wish to use. Get rid of vars(), he had to go to jail. Don't go visit vars() again for at least two months, then maybe he'll be out on probation. Adjusting your code (instead of the dictionary approach I suggested above), I'd suggest using your list variable directly! varlist = [] for i in myfiles: varlist.append( makeTuple( i ) ) Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From hugo.yoshi at gmail.com Tue Mar 1 19:47:34 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 1 Mar 2011 19:47:34 +0100 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On Tue, Mar 1, 2011 at 7:10 PM, Sean Carolan wrote: > On Tue, Mar 1, 2011 at 11:55 AM, Sean Carolan wrote: >> Maybe someone can help with this. ?I have a function that takes a >> single file as an argument and outputs a tuple with each line of the >> file as a string element. ?This is part of a script that is intended >> to concatenate lines in files, and output them to a different file. > > Not sure if this is the "right" or best way to do this, but I ended up > using vars() to assign my variable names, like so: > > import sys > > myfiles = tuple(sys.argv[1:]) > numfiles = len(myfiles) > varlist = [] > > def makeTuple(file): > ? 6 lines: ? ?outlist = [] ---------- > > for i in range(numfiles): > ? ?varlist.append('tuple'+str(i)) > ? ?vars()[varlist[i]] = makeTuple(myfiles[i]) http://docs.python.org/library/functions.html#vars As you can see in the documentation, you really shouldn't modify the object returned by vars() or locals(). It might work in some cases for some implementations of python, but it's actually an undefined operation, which basically means that an implementation may do anything it damn well pleases when you try to actually do it. Really, you shouldn't be trying to dynamically add variables to the namespace for each tuple, it's dangerous and can introduce all sorts of hard-to-catch bugs. Instead, put all your tuples in a list, and address them by index: tuples = [] for file in myfiles: tuples.append(makeTuple(file)) now you can address your tuples by tuples[0], tuples[1] and so forth, which is pretty much the same as tuple0, tuple1, etc. Even better, since it's in a list we can also iterate over it now with a for loop, isn't that great? Note also how I'm iterating over the myfiles list, which means I don't have to use the range() function together with indexing with i, which is a lot more readable. HTH, Hugo PS: There's even shorter ways to write this little script, but I won't bother you with them. If you want to know, check the map function, and list comprehensions. From scarolan at gmail.com Tue Mar 1 19:59:49 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Mar 2011 12:59:49 -0600 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: > I saw in your follow-up that you went straight for vars(). ?I really > don't think that's what you wish to use. ?Get rid of vars(), he had > to go to jail. ?Don't go visit vars() again for at least two months, > then maybe he'll be out on probation. Thanks Martin and Hugo. As you can tell I'm no python guru. Maybe I should take a step back and explain exactly what it is I'm trying to do. I know this can be done quickly with awk or even perl but I want to get more practice with python. So here's the basic idea: Take an arbitrary number of text files. Assume that each text file has the exact same number of lines. Concatenate each line of each file with the corresponding lines of the other files and output the data. So in other words, the first line of output will be file1_line1+file2_line1+file3_line1, etc. I'll work on this some more and see what I can come up with. From joel.goldstick at gmail.com Tue Mar 1 20:09:39 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 1 Mar 2011 14:09:39 -0500 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On Tue, Mar 1, 2011 at 1:59 PM, Sean Carolan wrote: > > I saw in your follow-up that you went straight for vars(). I really > > don't think that's what you wish to use. Get rid of vars(), he had > > to go to jail. Don't go visit vars() again for at least two months, > > then maybe he'll be out on probation. > > Thanks Martin and Hugo. As you can tell I'm no python guru. Maybe I > should take a step back and explain exactly what it is I'm trying to > do. I know this can be done quickly with awk or even perl but I want > to get more practice with python. So here's the basic idea: > > Take an arbitrary number of text files. Assume that each text file has > the exact same number of lines. Concatenate each line of each file > with the corresponding lines of the other files and output the data. > So in other words, the first line of output will be > file1_line1+file2_line1+file3_line1, etc. > > I'll work on this some more and see what I can come up with. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Just some quick ideas: Read about Generators. Using Hugo's snippet for reading a file a line at a time, you can write a function to yield a single line of the file for each call. Do this for as many files as you are combining, and concatinate the lines each pass. Then write to your outfile -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Mar 1 20:14:48 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 01 Mar 2011 11:14:48 -0800 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On 3/1/2011 10:59 AM Sean Carolan said... > Take an arbitrary number of text files. Assume that each text file has > the exact same number of lines. Concatenate each line of each file > with the corresponding lines of the other files and output the data. > So in other words, the first line of output will be > file1_line1+file2_line1+file3_line1, etc. > Hint: Look at zip. Emile From hugo.yoshi at gmail.com Tue Mar 1 20:18:15 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 1 Mar 2011 20:18:15 +0100 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On Tue, Mar 1, 2011 at 7:59 PM, Sean Carolan wrote: >> I saw in your follow-up that you went straight for vars(). ?I really >> don't think that's what you wish to use. ?Get rid of vars(), he had >> to go to jail. ?Don't go visit vars() again for at least two months, >> then maybe he'll be out on probation. > > Thanks Martin and Hugo. ?As you can tell I'm no python guru. ?Maybe I > should take a step back and explain exactly what it is I'm trying to > do. ?I know this can be done quickly with awk or even perl but I want > to get more practice with python. ?So here's the basic idea: > > Take an arbitrary number of text files. Assume that each text file has > the exact same number of lines. ?Concatenate each line of each file > with the corresponding lines of the other files and output the data. > So in other words, the first line of output will be > file1_line1+file2_line1+file3_line1, etc. > > I'll work on this some more and see what I can come up with. My advice would be to go read up on the zip() function and the str.join() function. Then, if you are using python 2.x, go find itertools.izip. It does the same thing as zip but it's more memory efficient. With those two you can do it in about two lines or so (and maybe a few for set up and clarity and such). If you get stuck, don't hesitate to ask. HTH, Hugo From emanuel.lauria at gmail.com Tue Mar 1 20:10:45 2011 From: emanuel.lauria at gmail.com (Emanuel Lauria) Date: Tue, 1 Mar 2011 20:10:45 +0100 Subject: [Tutor] File transfer HTTP -> SFTP Message-ID: Sorry if im annoying, but I think this is a better question than my previous one of today. I have some Images in an HTTP Server that I need to transfer to an SFTP server using a Python script. So far I can download them to my hard drive, and upload them to the sftp server; quite easy. I would like to do the transfer without touching my hard drive. How could I do that? Im using paramiko, but STPClient.put() reads from the filesystem. Thanks put(self, localpath, remotepath, callback=None) Copy a local file (localpath) to the SFTP server as remotepath. -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Tue Mar 1 20:49:29 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Mar 2011 13:49:29 -0600 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: > My advice would be to go read up on the zip() function and the > str.join() function. Then, if you are using python 2.x, go find > itertools.izip. It does the same thing as zip but it's more memory > efficient. With those two you can do it in about two lines or so (and > maybe a few for set up and clarity and such). This is what I've got so far: import sys myfiles = sys.argv[1:] for i in zip(open(myfiles[0]), open(myfiles[1]), open(myfiles[2])): print " ".join(i) How would you: 1. zip an arbitrary number of files in this manner? I hard-coded it to do only three. 2. Strip out trailing spaces and line breaks from the lines in each file? From emile at fenx.com Tue Mar 1 21:14:13 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 01 Mar 2011 12:14:13 -0800 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: On 3/1/2011 11:49 AM Sean Carolan said... >> My advice would be to go read up on the zip() function and the >> str.join() function. Then, if you are using python 2.x, go find >> itertools.izip. It does the same thing as zip but it's more memory >> efficient. With those two you can do it in about two lines or so (and >> maybe a few for set up and clarity and such). > > This is what I've got so far: > > import sys > myfiles = sys.argv[1:] > for i in zip(open(myfiles[0]), open(myfiles[1]), open(myfiles[2])): > print " ".join(i) > > How would you: > > 1. zip an arbitrary number of files in this manner? I hard-coded it > to do only three. One way: for i in zip([ open(filename) for filename in myfiles ]) > 2. Strip out trailing spaces and line breaks from the lines in each file? Convert the file contents before zip'ing -- so add def cleanedup(filename): return [ line.strip() for line in open(filename) ] Then your loop looks like: for i in zip([ cleanedup(filename) for filename in myfiles ]) HTH, Emile From knacktus at googlemail.com Tue Mar 1 21:39:34 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 01 Mar 2011 21:39:34 +0100 Subject: [Tutor] couchdb.mapping 'Document' class In-Reply-To: References: Message-ID: <4D6D5986.3020803@googlemail.com> Am 01.03.2011 16:19, schrieb Emanuel Lauria: > Hi everyone, > > I'm trying to map a couchdb document to a python object using > couchdb.mapping. I'm stuck in the very first part were it says I should > declare a Python class that inherits from the 'Document'.. Where does > this 'Document' superclass comes from? I can't resolve it. Or do I have > to create it? How? Could someone point me in to the right direction? > > >>> import couchdb > > >>> class Person(Document): > ... name = TextField() > ... > Traceback (most recent call last): > File "", line 1, in > NameError: name 'Document' is not defined > It looks like the class Document is located in the module couchdb.client (it's chapter 3.3). This should work: import couchdb.client class Person(couchdb.client.Document): ... HTH Jan > > Thanks for your help, and please forgive me if im too n00b in this. I > havent found any documentation except > http://packages.python.org/CouchDB/mapping.html which is not enough. > > Thanks > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From modulok at gmail.com Tue Mar 1 21:46:50 2011 From: modulok at gmail.com (Modulok) Date: Tue, 1 Mar 2011 13:46:50 -0700 Subject: [Tutor] File transfer HTTP -> SFTP In-Reply-To: References: Message-ID: This isn't a python solution, but if you have an ssh connection to both servers, (I assume so) you can forward them directly. It would look like this in an operating system shell like tcsh or bash: me at baz> scp -r me at foo.com:/home/me/pictures me at bar.com:/somewhere/ You could wrap the above command with python via the subprocess module if needed. -Modulok- On 3/1/11, Emanuel Lauria wrote: > Sorry if im annoying, but I think this is a better question than my previous > one of today. > > I have some Images in an HTTP Server that I need to transfer to an SFTP > server using a Python script. > > So far I can download them to my hard drive, and upload them to the sftp > server; quite easy. I would like to do the transfer without touching my hard > drive. > > How could I do that? > > Im using paramiko, but STPClient.put() reads from the filesystem. > > Thanks > > put(self, localpath, remotepath, callback=None) > Copy a local file (localpath) to the SFTP server as remotepath. From steve at pearwood.info Tue Mar 1 22:37:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2011 08:37:50 +1100 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: References: Message-ID: <4D6D672E.8040001@pearwood.info> Emile van Sebille wrote: > On 3/1/2011 11:49 AM Sean Carolan said... >>> My advice would be to go read up on the zip() function and the >>> str.join() function. Then, if you are using python 2.x, go find >>> itertools.izip. It does the same thing as zip but it's more memory >>> efficient. With those two you can do it in about two lines or so (and >>> maybe a few for set up and clarity and such). >> >> This is what I've got so far: >> >> import sys >> myfiles = sys.argv[1:] >> for i in zip(open(myfiles[0]), open(myfiles[1]), open(myfiles[2])): >> print " ".join(i) >> >> How would you: >> >> 1. zip an arbitrary number of files in this manner? I hard-coded it >> to do only three. > > One way: > > for i in zip([ open(filename) for filename in myfiles ]) Almost, you need to expand the list: zip( *[open(filename) for filename in myfiles] ) which is equivalent to pseudocode: zip(open(myfiles[0]), open(myfiles[1]), ..., open(myfiles[N])) Another way is: zip(*map(open, myfiles)) Again, you need to expand the list using *. >> 2. Strip out trailing spaces and line breaks from the lines in each >> file? > > Convert the file contents before zip'ing -- so add > > def cleanedup(filename): > return [ line.strip() for line in open(filename) ] Better to do the stripping on demand, rather than all up front. Especially if the files are huge. Turn the list comprehension [...] into a generator expression (...): def cleanedup(filename): return (line.strip() for line in open(filename)) > Then your loop looks like: > > for i in zip([ cleanedup(filename) for filename in myfiles ]) -- Steven From scarolan at gmail.com Tue Mar 1 23:06:33 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Mar 2011 16:06:33 -0600 Subject: [Tutor] Dynamically assign variable names to tuple objects In-Reply-To: <4D6D672E.8040001@pearwood.info> References: <4D6D672E.8040001@pearwood.info> Message-ID: > Another way is: > > zip(*map(open, myfiles)) >> Then your loop looks like: >> >> for i in zip([ cleanedup(filename) for filename in myfiles ]) Thanks, Steven! I knew there was a way to do this with just a few lines. I will read up some more on list expansion and the map built-in. From emmanuel.ruellan at laposte.net Wed Mar 2 10:22:21 2011 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Wed, 2 Mar 2011 10:22:21 +0100 Subject: [Tutor] Alternatives to pymssql to work with MS SQL Server Message-ID: Hi tutors, I installed Python 2.6 and pymssql on a machine, but as soon as I import pymssql, it crashes. It looks like this is a known problem: http://code.google.com/p/pymssql/issues/detail?id=2 What alternatives to pymssql do you recommend? I just want to be able to perform some simple queries on an MS SQL Server database. Best regards, Emmanuel Ruellan -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Mar 2 10:34:08 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 02 Mar 2011 09:34:08 +0000 Subject: [Tutor] Alternatives to pymssql to work with MS SQL Server In-Reply-To: References: Message-ID: <4D6E0F10.2050200@timgolden.me.uk> On 02/03/2011 09:22, Emmanuel Ruellan wrote: > I installed Python 2.6 and pymssql on a machine, but as soon as I import > pymssql, it crashes. > > It looks like this is a known problem: > http://code.google.com/p/pymssql/issues/detail?id=2 > > What alternatives to pymssql do you recommend? I just want to be able to > perform some simple queries on an MS SQL Server database. I use pyodbc: http://code.google.com/p/pyodbc/ because I tend to operate at the raw-SQL level. But if you want a rather higher-level interface then sqlalchemy is definitely your friend (which uses pyodbc under the covers by default): http://www.sqlalchemy.org/ TJG From steve at pearwood.info Wed Mar 2 10:33:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2011 20:33:33 +1100 Subject: [Tutor] Alternatives to pymssql to work with MS SQL Server In-Reply-To: References: Message-ID: <4D6E0EED.507@pearwood.info> Emmanuel Ruellan wrote: > What alternatives to pymssql do you recommend? I just want to be able to > perform some simple queries on an MS SQL Server database. This is a mailing list for teaching beginners how to program in Python. While we're happy to help with other Python-related questions, you'll probably have more luck at the general Python mailing list python-list at python.org, or the News group comp.lang.python. -- Steven From steve at pearwood.info Wed Mar 2 10:44:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Mar 2011 20:44:43 +1100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: Message-ID: <4D6E118B.8040502@pearwood.info> Alan Gauld wrote: > > "David" wrote > >> clever enough to refuse to instantiate itself if a necessary condition >> is not met. >> > >> class MyClass_2(object): >> def __new__(self, condition): >> if condition: >> return object.__new__(self) >> else: >> return None > > Thats pretty much how I'd do it. By convention, the name of the first argument to __new__ is cls, not self, because it is bound to the class object itself (MyClass_2 in this example) rather than the instance. The instance doesn't yet exist, so that's not surprising! -- Steven From emmanuel.ruellan at laposte.net Wed Mar 2 11:49:55 2011 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Wed, 2 Mar 2011 11:49:55 +0100 Subject: [Tutor] Alternatives to pymssql to work with MS SQL Server In-Reply-To: <4D6E0EED.507@pearwood.info> References: <4D6E0EED.507@pearwood.info> Message-ID: Tim, it's raw SQL queries I want to use. Pyodbc looks fine, thanks for suggesting it to me. I'll have to test it on the specific machine on which I encountered the problem with pymssql. Ra?l, thanks for the link to a list of alternatives to pymssql. You suggested that I try and change the order of the imports. Actually pymssql was the first module I imported, but I did it from Idle, therefore it's probably not really the first import. Steven, sorry if my question was slightly off topic. I turned to this list to ask my question because I enjoy reading this list and people here know their stuff, but maybe I should stop considering that my questions fall into the 'beginner' category, now that I've been dabbling in Python for a few years. -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Wed Mar 2 17:03:28 2011 From: knacktus at googlemail.com (Knacktus) Date: Wed, 02 Mar 2011 17:03:28 +0100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: Message-ID: <4D6E6A50.7080102@googlemail.com> Am 01.03.2011 07:49, schrieb David: > I have an idea that might clean up my code slightly, if I can make one > of my classes > clever enough to refuse to instantiate itself if a necessary condition > is not met. I think that's too clever ;-). Instead, you could create a function which has the only and explicit purpose to decide wether or not to create the class, e.g. def class_for_condition(condition): if condition: return MyClass() return None and use this throughout your code, e.g. my_object = class_for_condition(condition) But to me, it sounds a bit like trouble in general. As Alan said, you have to deal with two options for my_object in the remaining code. I can't really judge without seeing what you want to do later on, but maybe you have the chance to branch on a higher abstraction level? if condition: do_all_this_stuff() # do the things with my_object else: do_the_other_stuff() # do the things you don't need my_object Cheers, Jan > > Below I propose some example code that seems to achieve this, and I am > asking here > for feedback on it, because I have not written much python. So I might be doing > something unwise due to fiddling with things I don't totally understand. > > My aim is that instead of writing this: > > class MyClass: > pass > > condition = 0 > > if condition: > my_object = MyClass() > else: > my_object = None > > I could instead write this: > > class MyClass_2: > # put the if-test here inside the class > > my_object_2 = MyClass_2(condition) > > to achieve the goal that (my_object_2 == None) when (condition == False). > > I read the (ver 2.6) Python Language Reference > Section 3.4.1. Basic customization > Section 3.4.3. Customizing class creation > > Most of the content there is way beyond my current understanding, but I came up > with the following code, which seems to work: > > class MyClass_2(object): > def __new__(self, condition): > if condition: > return object.__new__(self) > else: > return None > > condition = 0 > my_object_2 = MyClass_2(condition) > print my_object_2 > condition = 1 > my_object_2 = MyClass_2(condition) > print my_object_2 > > Can anyone see any technical or style issues with that? Or > alternatively reassure me that it is completely ok? > Thanks. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From 1984docmccoy at gmail.com Wed Mar 2 13:56:58 2011 From: 1984docmccoy at gmail.com (Arthur Mc Coy) Date: Wed, 2 Mar 2011 14:56:58 +0200 Subject: [Tutor] python simplejson decoding Message-ID: Hi all, I'm trying an example (in attached file). First, I create a list of 3 objects. Then I do: PutJSONObjects(objects) objects = GetJSONObjects() PutJSONObjects(objects, "objects2.json") 1) PutJSONObjects(objects) method creates objects.json file (by default). It works fine. 2) Then objects = GetJSONObjects() method get the file contents and return. 3) Finally the script fails on the third method PutJSONObjects(objects, "objects2.json") saying: AttributeError: 'dict' object has no attribute '__dict__' That is true, because objects returned by GetJSONObjects() is not a list of objects, but simple string.... So here is the question, please, how should I DECODE .json file into list of python objects so that I will be able to put the copy of these objects into a new file called objects2.json ? simplejson docs are hard to follow - without examples. Please, help me. Be happy! Bart -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: cache.py Type: application/octet-stream Size: 1423 bytes Desc: not available URL: From alan.gauld at btinternet.com Wed Mar 2 19:54:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Mar 2011 18:54:19 -0000 Subject: [Tutor] Alternatives to pymssql to work with MS SQL Server References: <4D6E0EED.507@pearwood.info> Message-ID: "Emmanuel Ruellan" wrote > Steven, sorry if my question was slightly off topic. ... > I should stop considering that my questions fall into > the 'beginner' category, now that I've been dabbling in > Python for a few years. Steven's point was, I think, more that your question was not really about Python but about a specific database access module. If your issue had been about how to use the module to perform a query or such it would have been valid, but as it was it didn't really cover anything to do with using Python the language. But I am always amazed how this list can usually find at least one knowledgable reader to help out on any topic! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bouncingcats at gmail.com Thu Mar 3 01:47:33 2011 From: bouncingcats at gmail.com (David) Date: Thu, 3 Mar 2011 11:47:33 +1100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: <4D6E6A50.7080102@googlemail.com> References: <4D6E6A50.7080102@googlemail.com> Message-ID: Another classic case of trying something not the best way, due to inexperience. But it has been a good process: I learned something new from setting myself the initial puzzle and then finding a solution,and then learned more from the great tutoring here. Thanks very much for all the replies. On 2 March 2011 03:31, Alan Gauld wrote: > >> class MyClass_2(object): >> def __new__(self, condition): >> if condition: >> return object.__new__(self) >> else: >> return None > > Thats pretty much how I'd do it. Thanks for reviewing my code. On 2 March 2011 03:35, Alan Gauld wrote: > > Oops, sent too soon. > > I meant to add that you should realize that the implication of your > design is that the user of the class now has to check each object > to see if it is a valid reference or None. You could raise an exception > instead of returning None which allows a try/except style... > > This extra overhead is one reason these kinds of "clever" tricks > are usually avoided. A valid object with null content is often > preferrable, or a singleton style pattern. But occasionally your > style is needed, just be aware of the extra overhead you > introduce by using it. Spot on. It would require two "if" tests, one inside __new__() and another in the code. I found your mention of try/except there especially helpful, because it was a pertinent reminder that I was not thinking in "ask forgiveness not permission" mode. This (newbie mistake) occurred because I wanted my application to continue, not abort with an exception, but after your prompt I recalled that "except" doesn't have to raise exceptions it can do other things. So I went in the direction you suggested and I am happy with the results. Basically my application is interpreting binary file data by instantiating a structured object for each file in a fixed list of binary files, and I was looking for a neat way to ignore any errors on files that might not be present (failed to open). So, after feedback here my solution now is to use try/except in the class __init__() to create a valid object with null content, and then use "if" tests in the rest of the code that processes the objects to just ignore them if they are null, which is a nice clear way to do it. On 2 March 2011 20:44, Steven D'Aprano wrote: > > By convention, the name of the first argument to __new__ is cls, not self, > because it is bound to the class object itself (MyClass_2 in this example) > rather than the instance. The instance doesn't yet exist, so that's not > surprising! Thanks for pointing that out. In 2.6 Language Reference 3.4.3 they used "mcs" (metaclass?) which I didn't comprehend at all at the time (the mindset of just wanting to get some code working to fix a problem is not the most helpful mindset for decoding a large body of new information), so I just used "self" when getting their example code to work for me. In Section 3.4.1 they use "cls" which I now see clearly and understand thanks. On 3 March 2011 03:03, Knacktus wrote: > > I think that's too clever ;-). I agree now .. but it was a useful experiment. Thanks for the tute. From izzaddin.ruhulessin at gmail.com Thu Mar 3 07:59:43 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Thu, 3 Mar 2011 07:59:43 +0100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: <4D6E6A50.7080102@googlemail.com> Message-ID: Maybe: foo = lambda x: MyClass() if condition else None 2011/3/3 David > Another classic case of trying something not the best way, due to > inexperience. > But it has been a good process: I learned something new from > setting myself the initial puzzle and then finding a solution,and then > learned more from the great tutoring here. Thanks very much for all > the replies. > > On 2 March 2011 03:31, Alan Gauld wrote: > > > >> class MyClass_2(object): > >> def __new__(self, condition): > >> if condition: > >> return object.__new__(self) > >> else: > >> return None > > > > Thats pretty much how I'd do it. > > Thanks for reviewing my code. > > On 2 March 2011 03:35, Alan Gauld wrote: > > > > Oops, sent too soon. > > > > I meant to add that you should realize that the implication of your > > design is that the user of the class now has to check each object > > to see if it is a valid reference or None. You could raise an exception > > instead of returning None which allows a try/except style... > > > > This extra overhead is one reason these kinds of "clever" tricks > > are usually avoided. A valid object with null content is often > > preferrable, or a singleton style pattern. But occasionally your > > style is needed, just be aware of the extra overhead you > > introduce by using it. > > Spot on. It would require two "if" tests, one inside __new__() and > another in the code. > > I found your mention of try/except there especially helpful, because > it was a pertinent reminder that I was not thinking in "ask forgiveness > not permission" mode. This (newbie mistake) occurred because I > wanted my application to continue, not abort with an exception, but > after your prompt I recalled that "except" doesn't have to raise exceptions > it can do other things. > > So I went in the direction you suggested and I am happy with the results. > Basically my application is interpreting binary file data by instantiating > a > structured object for each file in a fixed list of binary files, and I > was looking > for a neat way to ignore any errors on files that might not be present > (failed to open). So, after feedback here my solution now is to use > try/except in the class __init__() to create a valid object with null > content, > and then use "if" tests in the rest of the code that processes the objects > to > just ignore them if they are null, which is a nice clear way to do it. > > On 2 March 2011 20:44, Steven D'Aprano wrote: > > > > By convention, the name of the first argument to __new__ is cls, not > self, > > because it is bound to the class object itself (MyClass_2 in this > example) > > rather than the instance. The instance doesn't yet exist, so that's not > > surprising! > > Thanks for pointing that out. In 2.6 Language Reference 3.4.3 they used > "mcs" (metaclass?) which I didn't comprehend at all at the time (the > mindset > of just wanting to get some code working to fix a problem is not the most > helpful mindset for decoding a large body of new information), so I just > used > "self" when getting their example code to work for me. In Section 3.4.1 > they > use "cls" which I now see clearly and understand thanks. > > On 3 March 2011 03:03, Knacktus wrote: > > > > I think that's too clever ;-). > > I agree now .. but it was a useful experiment. Thanks for the tute. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Thu Mar 3 08:00:32 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Thu, 3 Mar 2011 08:00:32 +0100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: <4D6E6A50.7080102@googlemail.com> Message-ID: Of course that would be: > foo = lambda condition: MyClass() if condition else None 2011/3/3 Izz ad-Din Ruhulessin > Maybe: > > foo = lambda x: MyClass() if condition else None > > > 2011/3/3 David > > Another classic case of trying something not the best way, due to >> inexperience. >> But it has been a good process: I learned something new from >> setting myself the initial puzzle and then finding a solution,and then >> learned more from the great tutoring here. Thanks very much for all >> the replies. >> >> On 2 March 2011 03:31, Alan Gauld wrote: >> > >> >> class MyClass_2(object): >> >> def __new__(self, condition): >> >> if condition: >> >> return object.__new__(self) >> >> else: >> >> return None >> > >> > Thats pretty much how I'd do it. >> >> Thanks for reviewing my code. >> >> On 2 March 2011 03:35, Alan Gauld wrote: >> > >> > Oops, sent too soon. >> > >> > I meant to add that you should realize that the implication of your >> > design is that the user of the class now has to check each object >> > to see if it is a valid reference or None. You could raise an exception >> > instead of returning None which allows a try/except style... >> > >> > This extra overhead is one reason these kinds of "clever" tricks >> > are usually avoided. A valid object with null content is often >> > preferrable, or a singleton style pattern. But occasionally your >> > style is needed, just be aware of the extra overhead you >> > introduce by using it. >> >> Spot on. It would require two "if" tests, one inside __new__() and >> another in the code. >> >> I found your mention of try/except there especially helpful, because >> it was a pertinent reminder that I was not thinking in "ask forgiveness >> not permission" mode. This (newbie mistake) occurred because I >> wanted my application to continue, not abort with an exception, but >> after your prompt I recalled that "except" doesn't have to raise >> exceptions >> it can do other things. >> >> So I went in the direction you suggested and I am happy with the results. >> Basically my application is interpreting binary file data by instantiating >> a >> structured object for each file in a fixed list of binary files, and I >> was looking >> for a neat way to ignore any errors on files that might not be present >> (failed to open). So, after feedback here my solution now is to use >> try/except in the class __init__() to create a valid object with null >> content, >> and then use "if" tests in the rest of the code that processes the objects >> to >> just ignore them if they are null, which is a nice clear way to do it. >> >> On 2 March 2011 20:44, Steven D'Aprano wrote: >> > >> > By convention, the name of the first argument to __new__ is cls, not >> self, >> > because it is bound to the class object itself (MyClass_2 in this >> example) >> > rather than the instance. The instance doesn't yet exist, so that's not >> > surprising! >> >> Thanks for pointing that out. In 2.6 Language Reference 3.4.3 they used >> "mcs" (metaclass?) which I didn't comprehend at all at the time (the >> mindset >> of just wanting to get some code working to fix a problem is not the most >> helpful mindset for decoding a large body of new information), so I just >> used >> "self" when getting their example code to work for me. In Section 3.4.1 >> they >> use "cls" which I now see clearly and understand thanks. >> >> On 3 March 2011 03:03, Knacktus wrote: >> > >> > I think that's too clever ;-). >> >> I agree now .. but it was a useful experiment. Thanks for the tute. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Thu Mar 3 14:28:06 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 3 Mar 2011 13:28:06 +0000 Subject: [Tutor] How to extract data from text to excel? Message-ID: hi, i found a module called xlwt (http://www.python-excel.org/) that can write to Excel. i want the code to read from a file (robert.txt) and then write to excel in a column. for eg: cell col0, row0 = 0 cell col0, row1 = 0 cell col0, row2 = 0 cell col0, row3 = 1 cell col0, row4 = 0 cell col0, row5 = 1 however, it seems that the output from this code is that it only writes to one cell in the excel. Pls advise how to modify the code. Pls advise if there are alternative way for python to do this task? tq import xlwt # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') for line in f: # separate fields by commas L = line.strip() sheet.write(row,0,L) row += 1 wbk.save('reformatted.data.xls') thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: robert.txt URL: From steve at pearwood.info Thu Mar 3 15:02:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Mar 2011 01:02:23 +1100 Subject: [Tutor] A class that instantiates conditionally ? In-Reply-To: References: <4D6E6A50.7080102@googlemail.com> Message-ID: <4D6F9F6F.1000603@pearwood.info> David wrote: >>> class MyClass_2(object): >>> def __new__(self, condition): >>> if condition: >>> return object.__new__(self) >>> else: >>> return None [...] > Spot on. It would require two "if" tests, one inside __new__() and > another in the code. You will always need at least two if tests: once in the function producing the result ("does the test succeed? if not, return this instead...") and once in the code using the result ("did the magic value get returned?"). Consider str.find()... the caller has to check whether it returns -1, but the find method itself has to check whether the search string is found or not, and return -1 if it is not. This may or may not require a *literal* if statement, but there's still an implied test in the code. > I found your mention of try/except there especially helpful, because > it was a pertinent reminder that I was not thinking in "ask forgiveness > not permission" mode. This (newbie mistake) occurred because I > wanted my application to continue, not abort with an exception, but > after your prompt I recalled that "except" doesn't have to raise exceptions > it can do other things. Fair enough, and arguably having the class raise an exception is a better design, but with all the people saying your original design was "too clever", I'd like to give it some love :) I think the design is just clever enough. I would consider using it if I were designing something like the regular expression match and search methods, which return None if the regex doesn't match. -- Steven From steve at pearwood.info Thu Mar 3 15:10:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Mar 2011 01:10:27 +1100 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: References: Message-ID: <4D6FA153.5090901@pearwood.info> tee chwee liong wrote: > hi, > > i found a module called xlwt (http://www.python-excel.org/) that can write to Excel. i want the code to read from a file (robert.txt) and then write to excel in a column. for eg: > cell col0, row0 = 0 > cell col0, row1 = 0 > cell col0, row2 = 0 > cell col0, row3 = 1 > cell col0, row4 = 0 > cell col0, row5 = 1 > > however, it seems that the output from this code is that it only writes to one cell in the excel. That's because your data ("robert.txt") only contains one line with one field. You read that one field as a big chunk of text, and then write it to one cell, and then the loop ends. > import xlwt > # Create workbook and worksheet > wbk = xlwt.Workbook() > sheet = wbk.add_sheet('python') > row = 0 # row counter > f = open('robert.txt') > for line in f: > # separate fields by commas What does this comment mean? You don't have any commas in the file "robert.txt", and you don't actually do anything with or to commas in your code. I think that comment is false. > L = line.strip() > sheet.write(row,0,L) Here you write the entire contents of the file into one cell. You need to iterate over L: for c in L: sheet.write(row, 0, c) row += 1 -- Steven From joel.goldstick at gmail.com Thu Mar 3 20:57:13 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 3 Mar 2011 14:57:13 -0500 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: <4D6FA153.5090901@pearwood.info> References: <4D6FA153.5090901@pearwood.info> Message-ID: On Thu, Mar 3, 2011 at 9:10 AM, Steven D'Aprano wrote: > tee chwee liong wrote: > >> hi, >> i found a module called xlwt (http://www.python-excel.org/) that can >> write to Excel. i want the code to read from a file (robert.txt) and then >> write to excel in a column. for eg: >> cell col0, row0 = 0 >> cell col0, row1 = 0 >> cell col0, row2 = 0 >> cell col0, row3 = 1 >> cell col0, row4 = 0 >> cell col0, row5 = 1 >> >> however, it seems that the output from this code is that it only writes to >> one cell in the excel. >> > > That's because your data ("robert.txt") only contains one line with one > field. You read that one field as a big chunk of text, and then write it to > one cell, and then the loop ends. > > > import xlwt >> # Create workbook and worksheet wbk = xlwt.Workbook() sheet = >> wbk.add_sheet('python') >> row = 0 # row counter >> f = open('robert.txt') >> for line in f: # separate fields by commas >> > > What does this comment mean? You don't have any commas in the file > "robert.txt", and you don't actually do anything with or to commas in your > code. I think that comment is false. > > > L = line.strip() sheet.write(row,0,L) >> > > Here you write the entire contents of the file into one cell. You need to > iterate over L: > > for c in L: > sheet.write(row, 0, c) > row += 1 > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I might not understand what you need to do, but it seems to me that its simpler to create a csv file that can be read by excel. Actually, since you have only one field per row, there are no commas. Here is what I came up with: #!/usr/bin/env python """ Read a file containing a long string of ones and zeros Separate each bit with a comma, then write the whole csv thing to an output file. This can be read by an excel like application with one bit in each row of the first column """ f = open('./robert.txt','r') f_data = f.read() list_of_bits = list(f_data) csv_string = '\n'.join(list_of_bits[:-1]) # these 3 lines show what is going on print f_data print list_of_bits print csv_string f_out = open('./robert.csv', 'w') f_out.write(csv_string) f_out.close() -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From andy.a.bouchot at gmail.com Thu Mar 3 22:28:33 2011 From: andy.a.bouchot at gmail.com (Andrew Bouchot) Date: Thu, 3 Mar 2011 15:28:33 -0600 Subject: [Tutor] Help! Message-ID: okay so this is my comp sci lab * Problem: *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an item. Unfortunately, after 143 items are produced, the fabricator must cool off for 5 minutes and 13 seconds before it can continue. Write a program that will calculate the amount of time required to manufacture a given number of items. * Output: *Output the amount of time D days HH:MM:SS * Sample Input : * numItems =1340 Represents the numbers items to be manufactured * Sample Output : * 2 days 00:03:17 this is the coding i have written for it! numitems= int(raw_input("Enter the number of items needed to be manufactured:")) seconds=numitems*127 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) but how would i add the 5 min and 13 seconds after 143 items have been produced??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Thu Mar 3 22:56:06 2011 From: knacktus at googlemail.com (Knacktus) Date: Thu, 03 Mar 2011 22:56:06 +0100 Subject: [Tutor] Help! In-Reply-To: References: Message-ID: <4D700E76.6060701@googlemail.com> Am 03.03.2011 22:28, schrieb Andrew Bouchot: > okay so this is my comp sci lab > * > > Problem: > > *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an > item. Unfortunately, after 143 items are produced, the fabricator must > cool off for 5 minutes and 13 seconds before it can continue. Write a > program that will calculate the amount of time required to manufacture a > given number of items. * > > Output: > > *Output the amount of time D days HH:MM:SS * > > Sample Input : > > * > > numItems =1340 Represents the numbers items to be manufactured > > * > > Sample Output : > > * > > 2 days 00:03:17 > > this is the coding i have written for it! > > numitems= int(raw_input("Enter the number of items needed to be > manufactured:")) > seconds=numitems*127 > m, s = divmod(seconds, 60) > h, m = divmod(m, 60) > print "%d:%02d:%02d" % (h, m, s) > > but how would i add the 5 min and 13 seconds after 143 items have been > produced??? For any given number of item, how many cool-down periods do you have in total? What's the prodcution time without cooling? -----------|++++++++|-----------|++++++++|----------|++++++++|------ producing |cooling |producing |cooling |producing |cooling |producing HTH, Jan > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From eire1130 at gmail.com Thu Mar 3 22:58:17 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 3 Mar 2011 16:58:17 -0500 Subject: [Tutor] Help! In-Reply-To: References: Message-ID: This isn't so much as a python problem as it is a simple math problem, and I feel you are being lazy, but in the offchance you're having problems with the '/' operator: cooloff = (numitems/143)*313 total = cooloff + seconds I think you are using python 2.6 (and I guess 2.7) or older based on your print statement. I could be totally wrong, in which case numitems/143 will not work correctly. In 2.6 and older the / operator does floor division. You are almost assuredly going to get flamed for not having a descriptive title and for asking what is obviously homework questions On Thu, Mar 3, 2011 at 4:28 PM, Andrew Bouchot wrote: > okay so this is my comp sci lab > > * > > Problem: > *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an > item. Unfortunately, after 143 items are produced, the fabricator must cool > off for 5 minutes and 13 seconds before it can continue. Write a program > that will calculate the amount of time required to manufacture a given > number of items. * > > Output: > *Output the amount of time D days HH:MM:SS * > > Sample Input : > * > > numItems =1340 Represents the numbers items to be manufactured > * > > Sample Output : > * > > 2 days 00:03:17 > > > > this is the coding i have written for it! > > numitems= int(raw_input("Enter the number of items needed to be > manufactured:")) > seconds=numitems*127 > m, s = divmod(seconds, 60) > h, m = divmod(m, 60) > print "%d:%02d:%02d" % (h, m, s) > > but how would i add the 5 min and 13 seconds after 143 items have been > produced??? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Thu Mar 3 23:08:12 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 3 Mar 2011 17:08:12 -0500 Subject: [Tutor] Help! In-Reply-To: <4D700E76.6060701@googlemail.com> References: <4D700E76.6060701@googlemail.com> Message-ID: On Thu, Mar 3, 2011 at 4:56 PM, Knacktus wrote: > Am 03.03.2011 22:28, schrieb Andrew Bouchot: >> >> okay so this is my comp sci lab >> * >> >> Problem: >> >> *ProductionTime.py It takes exactly 2 minutes and 7 second to produce an >> item. Unfortunately, after 143 items are produced, the fabricator must >> cool off for 5 minutes and 13 seconds before it can continue. Write a >> program that will calculate the amount of time required to manufacture a >> given number of items. * >> >> Output: >> >> *Output the amount of time D days HH:MM:SS * >> >> Sample Input : >> >> * >> >> numItems =1340 Represents the numbers items to be manufactured >> >> * >> >> Sample Output : >> >> * >> >> 2 days 00:03:17 >> >> this is the coding i have written for it! >> >> numitems= int(raw_input("Enter the number of items needed to be >> manufactured:")) >> seconds=numitems*127 >> m, s = divmod(seconds, 60) >> h, m = divmod(m, 60) >> print "%d:%02d:%02d" % (h, m, s) >> >> but how would i add the 5 min and 13 seconds after 143 items have been >> produced??? > > For any given number of item, how many cool-down periods do you have in > total? > What's the prodcution time without cooling? > > -----------|++++++++|-----------|++++++++|----------|++++++++|------ > producing ?|cooling |producing ?|cooling |producing |cooling |producing > Maybe I understood it wrong, but they ask "but how would i add the 5 min and 13 seconds after 143 items have been produced???", which is produce 143, then wait 5:13. Those times are irrelevant, unless the need is in between the produced 143, which would make the pseudo: > count = 0 > while count != 144 > do stuff time.sleep(5:13/143 interval) count += 1 > HTH, > > Jan > >> >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From kb1pkl at aim.com Fri Mar 4 00:39:59 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 03 Mar 2011 18:39:59 -0500 Subject: [Tutor] Homework Problem Flaming (was: Help!) In-Reply-To: References: Message-ID: <4D7026CF.9060507@aim.com> On 03/03/2011 04:58 PM, James Reynolds wrote: > You are almost assuredly going to get flamed for not having a descriptive > title and for asking what is obviously homework questions > Maybe for not having a descriptive title, but there's nothing wrong with coming to the list with homework! The requirements are that you've put some work into it, you show your code, you say what is should be doing that it isn't, and that you explain what you've tried doing previously. At least, those are what I look for. Even better that he said right up front that it was homework. With homework problems, instead of saying "Hey, replace lines 42-48 with foo", saying "Look into the bar module, it bazifies the proper value for you". Teaching people to learn better for themselves instead of hand-feeding them the answers. This list does a really good job with it, IMO. -- Corey Richardson From steve at pearwood.info Fri Mar 4 01:32:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Mar 2011 11:32:48 +1100 Subject: [Tutor] Help! In-Reply-To: References: Message-ID: <4D703330.8070806@pearwood.info> James Reynolds wrote: [...] > You are almost assuredly going to get flamed for not having a descriptive > title and for asking what is obviously homework questions At least Andrew did the right thing by being honest that it was a homework question, and by showing the work he's done so far. But yes, you're right, a more descriptive title is always appreciated. And speaking for flaming, thank you for not top-posting in the future. If you *must* top-post, because you're using one of those stupid "smart" phones that won't let you do otherwise, at least apologize for doing so. Andrew, you ask: >> but how would i add the 5 min and 13 seconds after 143 items have >> been produced??? You should always do all your calculations in a single unit of time (probably seconds), and only convert back to D HH:MM:SS at the very end. If you have N items to produce, you need to consider it broken up into groups of 143 items, plus cooling off time *between* each group. If N is an exact multiple of 143 items, you have something like this: (143)(cool)(143)(cool)(143)(cool)(143)(cool)(143) Notice that you don't care about the cooling off time after you're done. If N is not an exact multiple, there will be some remainder: (143)(cool)(143)(cool)(143)(cool)(143)(cool)(143)(cool)(remainder) You can work out the number of groups of 143, and the remainder left over, using the divmod function. Then you can work out the number of cooling periods -- this is just the fence post problem. If you have a fence with N posts |===|===|===|===|===|===|===|===|===| how many sections are there? Or conversely, given M sections of a fence, how many posts do you need? -- Steven From tcl76 at hotmail.com Fri Mar 4 01:44:30 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 4 Mar 2011 00:44:30 +0000 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: <4D6FA153.5090901@pearwood.info> References: , <4D6FA153.5090901@pearwood.info> Message-ID: > What does this comment mean? You don't have any commas in the file > "robert.txt", and you don't actually do anything with or to commas in > your code. I think that comment is false. > > > L = line.strip() > > sheet.write(row,0,L) > > Here you write the entire contents of the file into one cell. You need > to iterate over L: > > for c in L: > sheet.write(row, 0, c) > row += 1 hi steven, ok i get what you meant. there are no pattern to split the entire contents in the robert.txt. is the content still needed to be splitted? L = line.split() will result in one long string. could you pls explain what is c? how do i modify the c in the code? pls advise. tq for line in f: #for c in L: L = line.split() print L sheet.write(row,0) row += 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Mar 4 01:55:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Mar 2011 11:55:13 +1100 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: References: , <4D6FA153.5090901@pearwood.info> Message-ID: <4D703871.60105@pearwood.info> tee chwee liong wrote: >> What does this comment mean? You don't have any commas in the file >> "robert.txt", and you don't actually do anything with or to commas in >> your code. I think that comment is false. >> >>> L = line.strip() >>> sheet.write(row,0,L) >> Here you write the entire contents of the file into one cell. You need >> to iterate over L: >> >> for c in L: >> sheet.write(row, 0, c) >> row += 1 > > hi steven, > > ok i get what you meant. there are no pattern to split the entire contents in the robert.txt. > is the content still needed to be splitted? > L = line.split() will result in one long string. Do not confuse split() and strip() methods. This is easy to do, even for native English speakers, so be extra careful. In your earlier code, you used strip(), which removes leading and trailing whitespace: >>> L = ' 0001110011 \n' # ends with a newline >>> L.strip() '0001110011' Compare split: >>> L = "001110101 0011110 011011110" >>> L.split() ['001110101', '0011110', '011011110'] You get a list of strings. If there is no whitespace in the string, you get a list containing one string: >>> L = "0011101010011110011011110" >>> L.split() ['0011101010011110011011110'] > could you pls explain what is c? how do i modify the c in the code? The interactive interpreter is your best friend in the world. You should learn to use it to answer simple questions, and count yourself lucky that Python has an interactive interpreter. Not all languages do. >>> L = "001110" >>> for c in L: ... print c ... 0 0 1 1 1 0 c is just a name like any other name: >>> L = "001110" >>> for c in L: ... if c == '1': ... c = 'Surprise!' ... print c ... 0 0 Surprise! Surprise! Surprise! 0 -- Steven From tcl76 at hotmail.com Fri Mar 4 02:08:08 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 4 Mar 2011 01:08:08 +0000 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: <4D703871.60105@pearwood.info> References: , , <4D6FA153.5090901@pearwood.info>, , <4D703871.60105@pearwood.info> Message-ID: thanks Steven, i get what you mean now. final code works: import xlwt """Reads robert.txt""" # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') L = line.strip() for c in L: sheet.write(row,0,c) row += 1 wbk.save('reformatted.data.xls') thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladymcse2000 at gmail.com Fri Mar 4 02:18:11 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Thu, 3 Mar 2011 17:18:11 -0800 Subject: [Tutor] Need some help on output Message-ID: I am creating a dictionary by parsing a text file. The code is below: backup_servers = {} fo = open('c:/test/backup_shares.txt') for line in fo: backup_server = line.split(',') backup_servers[backup_server[0]]=backup_server[1] for i, v in backup_servers.items(): backup_shares = i archive_dir = v archive_dir += '/' archive_dir += str(today) archive_dir += '.txt' I need to use the output from the above with the win32.py modules to map drives and then create a file name with timestamp appended to it for backups that I'm doing and database dumps. The problem is that it's output like so: c:/test /backup_name_2011-03-03.txt \\server_name1\backup_share c:/test /backup_name_2011-03-03.txt \\server_name1\backup_share I've tried this several ways and using a print command as so: print backup_shares, archive_dir print '%s %s' %( backup_shares, archive_dir) and it still inserts a new line The contents of the file are just: \\server_name1\backup_share$,c:/test \\server_name1\backup_share$,c:/test I tried including the backup slashes in the text file, omitting them and including them in the print statement, to no avail. Any comments? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Fri Mar 4 02:37:19 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Fri, 4 Mar 2011 07:07:19 +0530 Subject: [Tutor] Need some help on output In-Reply-To: References: Message-ID: On Fri, Mar 4, 2011 at 6:48 AM, Becky Mcquilling wrote: > I am creating a dictionary by parsing a text file. > > The code is below: > backup_servers = {} > fo = open('c:/test/backup_shares.txt') > for line in fo: > ??backup_server = line.split(',') > ??backup_servers[backup_server[0]]=backup_server[1] Looping over a file object returns lines including the trailing newline. If that's not required, you have to remove the newline at the end yourself using the strip method. To see the behaviour, print out the value of line at the start of the loop body. Documentation on file objects: http://docs.python.org/library/stdtypes.html#file-objects Documentation on strings: http://docs.python.org/library/stdtypes.html#string-methods > -- regards, kushal From ladymcse2000 at gmail.com Fri Mar 4 08:47:22 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Thu, 3 Mar 2011 23:47:22 -0800 Subject: [Tutor] Need some help on output In-Reply-To: References: Message-ID: Thanks, that helped. I took a second look and realized where I had tried calling the .strip() method was wrong. Appreciate the pointer. Becky On Thu, Mar 3, 2011 at 5:37 PM, Kushal Kumaran < kushal.kumaran+python at gmail.com> wrote: > On Fri, Mar 4, 2011 at 6:48 AM, Becky Mcquilling > wrote: > > I am creating a dictionary by parsing a text file. > > > > The code is below: > > backup_servers = {} > > fo = open('c:/test/backup_shares.txt') > > for line in fo: > > backup_server = line.split(',') > > backup_servers[backup_server[0]]=backup_server[1] > > Looping over a file object returns lines including the trailing > newline. If that's not required, you have to remove the newline at > the end yourself using the strip method. > > To see the behaviour, print out the value of line at the start of the loop > body. > > Documentation on file objects: > http://docs.python.org/library/stdtypes.html#file-objects > Documentation on strings: > http://docs.python.org/library/stdtypes.html#string-methods > > > > > -- > regards, > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gaurav.tula at gmail.com Fri Mar 4 09:12:52 2011 From: gaurav.tula at gmail.com (Gaurav Malhotra) Date: Fri, 4 Mar 2011 13:42:52 +0530 Subject: [Tutor] Need some help on output In-Reply-To: References: Message-ID: I am beginner.......................I want to know best book to start with when it comes with python programming -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Fri Mar 4 09:21:40 2011 From: smokefloat at gmail.com (David Hutto) Date: Fri, 4 Mar 2011 03:21:40 -0500 Subject: [Tutor] Need some help on output In-Reply-To: References: Message-ID: That depends on what your motivation is for learning python. I'd start with a few hello world tutorial online. like print "hello world"/ python 3.0 print("hello world"), and on that not, decide on the version you want to use on your system first. From tcl76 at hotmail.com Fri Mar 4 09:33:44 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 4 Mar 2011 08:33:44 +0000 Subject: [Tutor] How to extract data from text to excel? In-Reply-To: References: , , , <4D6FA153.5090901@pearwood.info>, , , , <4D703871.60105@pearwood.info>, Message-ID: bug in the previous code so the final code should be: import xlwt """Reads robert.txt This is the final script that writes by incrementing each row but maintain one column""" # Create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('python') row = 0 # row counter f = open('robert.txt') for line in f: L = line.strip() print L for c in L: print c sheet.write(row,0,c) row += 1 wbk.save('reformatted.data.xls') _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 4 10:28:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Mar 2011 09:28:20 -0000 Subject: [Tutor] Book Request [Was: Re: Need some help on output] References: Message-ID: "Gaurav Malhotra" wrote >I am beginner....................... Welcome. But when posting messages please start a new thread do not use an existing one. Otherwise your message is likely to be missed by anyone not reading the previous subject. > I want to know best book to start with > when it comes with python programming Books/tutorials are very subjective. The style of tutorial that I like may not suit you. That having been said: Are you a beginner to Python? Or a beginner to programming? There are beginners pages for both categories on the python.org web site that list online tutorials. Choose a few and try them out, they are all free. One thing you will need to decide is whether to learn the latest Python Version 3 or to use the older Python Version 2. They are not compatible and thee is more widespread support for V2, but V3 iscatching up. For now I would recommend a complete beginner go with Version 3 but if you already know another language then go with Version 2 (you will learn faster than a beginner and so may run into some current limitations of V3) Once you find a tutorial that suits your style then stick to it. Do the examples don't just read them. Post any questions or problems you encounter to this mailing list. Tell us the Python version, the tutorial you use and the Operating system. Include full error messages in posts, they may not look helpful to you but they are very helpful to us! :-). Enjoy programming in Python. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jigenbakuda at yahoo.com Sat Mar 5 01:15:08 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Fri, 4 Mar 2011 16:15:08 -0800 (PST) Subject: [Tutor] Help! (solution) In-Reply-To: References: Message-ID: <850472.57932.qm@web130201.mail.mud.yahoo.com> I know that the question has long been answered (and probably due today), but I solved it and it was great exercise for me (as I'm not in college at the moment and I need assignments like these to gauge my skills). I'll probably build a gui for it tomorrow, just so I can practice at that. I wish I had a comp sci lab... (T_T) but I digress But anyways Andrew here is an alternative way to solve the problem (even if it is a long and round about method). And to anyone else who is reading beside Andrew, if something about my code could be better, please tell me, as this was just as much a learning experience for me as it is for Andrew. I need constructive criticism at the moment so I don't develop bad habits. def production_time(): creation_time = 127 time_till_rest = 18161 items = raw_input("How many items will be produced?\n> ") item_time = int(items) * creation_time rest_times = item_time/time_till_rest print rest_times if rest_times > 0: total = item_time + (313 * rest_times) #313 is 5 min and 13 secs in second form else: total = item_time time = sec_to_standard(total) print "It would take %d days %d hours %d minutes and %d seconds to produce that many items" %(time[0], time[1], time[2], time[3]) def sec_to_standard(seconds): day = 86400 #secs hour = 3600 #secs mins = 60#seconds creation_time = 127 #secs time_till_rest = 18161 #secs days = 0 hours = 0 minutes = 0 secs = 0 if seconds > day: while seconds > day: print "doing days" seconds = seconds - day days += 1 if seconds > hour: while seconds > hour: print "doing hours" seconds = seconds - hour hours += 1 if hours >= 24: days += 1 hours -= 24 if seconds > mins: while seconds > mins: print "doing minutes" seconds = seconds - mins minutes += 1 if minutes > 60: hours += 1 minutes -= 60 secs = seconds return days, hours, minutes, secs production_time() ---- What is it about you... that intrigues me so? ________________________________ From: Andrew Bouchot To: tutor at python.org Sent: Thu, March 3, 2011 4:28:33 PM Subject: [Tutor] Help! okay so this is my comp sci lab Problem: ProductionTime.py It takes exactly 2 minutes and 7 second to produce an item. Unfortunately, after 143 items are produced, the fabricator must cool off for 5 minutes and 13 seconds before it can continue. Write a program that will calculate the amount of time required to manufacture a given number of items. Output: Output the amount of time D days HH:MM:SS Sample Input : numItems =1340 Represents the numbers items to be manufactured Sample Output : 2 days 00:03:17 this is the coding i have written for it! numitems= int(raw_input("Enter the number of items needed to be manufactured:")) seconds=numitems*127 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) but how would i add the 5 min and 13 seconds after 143 items have been produced??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolf.halton at gmail.com Sat Mar 5 02:09:50 2011 From: wolf.halton at gmail.com (Wolf Halton) Date: Fri, 4 Mar 2011 20:09:50 -0500 Subject: [Tutor] Fwd: Re: Help! (solution) In-Reply-To: <850472.57932.qm@web130201.mail.mud.yahoo.com> References: <850472.57932.qm@web130201.mail.mud.yahoo.com> Message-ID: Put the timing code for one itemt in a while loop and have the variable for elapsed time incremented by the amount of time the fabricator has to cool every time the modulus of the loop counter / 127 is 0 AND the count is above 0. production = 0 time = 127 # seconds timer = 0 rest = 313 run = input("Enter your run total: ") while production != run: timer = timer + time if run % production = 0: timer = timer + rest print "It took %i seconds to produce %i items." % (timer, run) d = 24*60*60 h = 60*60 m = 60 D = timer / d # how many days Dsec = timer % d # seconds left after deducting the days H = Dsec / h # how many hours Hsec = Dsec % h # seconds left after deducting hours. M = Hsec / m # how many minutes Msec = Hsec % m # seconds left after deducting minutes print "Production time for %i items: %i Days, %i:%i:%i" % (run, D, H, M, Msec) # my 2 cents ---------- Forwarded message ---------- From: "michael scott" Date: Mar 4, 2011 7:17 PM Subject: Re: [Tutor] Help! (solution) To: I know that the question has long been answered (and probably due today), but I solved it and it was great exercise for me (as I'm not in college at the moment and I need assignments like these to gauge my skills). I'll probably build a gui for it tomorrow, just so I can practice at that. I wish I had a comp sci lab... (T_T) but I digress But anyways Andrew here is an alternative way to solve the problem (even if it is a long and round about method). And to anyone else who is reading beside Andrew, if something about my code could be better, please tell me, as this was just as much a learning experience for me as it is for Andrew. I need constructive criticism at the moment so I don't develop bad habits. def production_time(): creation_time = 127 time_till_rest = 18161 items = raw_input("How many items will be produced?\n> ") item_time = int(items) * creation_time rest_times = item_time/time_till_rest print rest_times if rest_times > 0: total = item_time + (313 * rest_times) #313 is 5 min and 13 secs in second form else: total = item_time time = sec_to_standard(total) print "It would take %d days %d hours %d minutes and %d seconds to produce that many items" %(time[0], time[1], time[2], time[3]) def sec_to_standard(seconds): day = 86400 #secs hour = 3600 #secs mins = 60#seconds creation_time = 127 #secs time_till_rest = 18161 #secs days = 0 hours = 0 minutes = 0 secs = 0 if seconds > day: while seconds > day: print "doing days" seconds = seconds - day days += 1 if seconds > hour: while seconds > hour: print "doing hours" seconds = seconds - hour hours += 1 if hours >= 24: days += 1 hours -= 24 if seconds > mins: while seconds > mins: print "doing minutes" seconds = seconds - mins minutes += 1 if minutes > 60: hours += 1 minutes -= 60 secs = seconds return days, hours, minutes, secs production_time() ---- What is it about you... that intrigues me so? ________________________________ From: Andrew Bouchot To: tutor at python.org Sent: Thu, March 3, 2011 4:28:33 PM Subject: [Tutor] Help! okay so this is my comp sci lab Problem: ProductionTime.py It takes exactly 2 minutes and 7 second to produce an item. Unfortunately, after 143 items are produced, the fabricator must cool off for 5 minutes and 13 seconds before it can continue. Write a program that will calculate the amount of time required to manufacture a given number of items. Output: Output the amount of time D days HH:MM:SS Sample Input : numItems =1340 Represents the numbers items to be manufactured Sample Output : 2 days 00:03:17 this is the coding i have written for it! numitems= int(raw_input("Enter the number of items needed to be manufactured:")) seconds=numitems*127 m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) but how would i add the 5 min and 13 seconds after 143 items have been produced??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From lea-parker at bigpond.com Sat Mar 5 06:43:29 2011 From: lea-parker at bigpond.com (lea-parker at bigpond.com) Date: Sat, 5 Mar 2011 15:43:29 +1000 (EST) Subject: [Tutor] Help - want to display a number with two decimal places Message-ID: <7095982.6984.1299303809919.JavaMail.prodapps@nskntweba09-app> An HTML attachment was scrubbed... URL: From modulok at gmail.com Sat Mar 5 06:49:43 2011 From: modulok at gmail.com (Modulok) Date: Fri, 4 Mar 2011 22:49:43 -0700 Subject: [Tutor] Shared web host and setting the python environment... Message-ID: List, Background: I'm on a linux based shared web host. They cater to PHP, not python. (There's no third party python modules even installed!) So I installed a virtual python in my home directory, plus easy_install and a bunch of modules. Great! The Problem: Unfortunately, the web server uses the system python, not my virtual python, or my modules. (It does execute my scripts as my uid though.) I need modify the environment of every one of my python scripts, perhaps appending to sys.path, so that my third party modules in my home directory can be found. I have zero control over the web server process or its environment. Possible Solutions I thought of: One way to do this would be to edit 'sys.path' at the top of every python script. (Sounds ugly.) Another would be to import the 'user' module and go that route. (Fine, but it's depricated. What replaces it?) A third idea would be to re-direct all requests via mod_rewrite to a single python file or shell script, which sets the environment and calls my python scripts as a sub-process. (Slow, which is fine, but some security concerns here.) Given my situation, what's the best way to accomplish this? (Aside from a new hosting company or a virtual private server.) Any suggestions appreciated. Thanks! -Modulok- From modulok at gmail.com Sat Mar 5 07:25:06 2011 From: modulok at gmail.com (Modulok) Date: Fri, 4 Mar 2011 23:25:06 -0700 Subject: [Tutor] Help - want to display a number with two decimal places In-Reply-To: <7095982.6984.1299303809919.JavaMail.prodapps@nskntweba09-app> References: <7095982.6984.1299303809919.JavaMail.prodapps@nskntweba09-app> Message-ID: On 3/4/11, lea-parker at bigpond.com wrote: > Hello > > I have created the following code but would like the program to include two > decimal places in the amounts displayed to the user. How can I add this? > > My code: > > > # Ask user to enter purchase price > purchasePrice = input ('Enter purchase amount and then press the enter key > $') > > # Tax rates > stateTaxRate = 0.04 > countrySalesTaxRate = 0.02 > > # Process taxes for purchase price > > stateSalesTax = purchasePrice * stateTaxRate > countrySalesTax = purchasePrice * countrySalesTaxRate > > # Process total of taxes > totalSalesTax = stateSalesTax + countrySalesTax > > # Process total sale price > totalSalePrice = totalSalesTax + purchasePrice > > # Display the data > print '%-18s %9d' % ('Purchase Price',purchasePrice) > print '%-18s %9d' % ('State Sales Tax',astateSalesTax) > print '%-18s %9d' % ('Country Sales Tax',countrySalesTax) > print '%-18s %9d' % ('Total Sales tax',totalSalesTax) > print '%-18s %9d' % ('Total Sale Price',totalSalePrice) > Lea, Notice that 'd' in your string substitution means integers, not floats. Any decimal places will be truncated when using 'd'. For floats use 'f' instead. You an also specify a precision, such as '%.2f' shows two decimal places. However, to make all of your numbers line up nicely, regardless of how long they are, you need to look into advanced string formatting via the builtin string method 'format()'. It takes a little practice to understand and use, but the results are exactly what you want. (See: http://docs.python.org/library/stdtypes.html#str.format) Here's an example you could put at the bottom of your code to see it in action: print "{0:<18} {1:>18.2f}".format("Country Sales Tax", countrySalesTax) print "{0:<18} {1:>18.2f}".format("Purchase Price", purchasePrice) # First prints the first argument (the 0th index) to 'format(), # left aligned '<', and 18 characters wide, whitespace padded. # Then prints the second argument, (the 1st index) right aligned, # also 18 characters wide, but the second argument is specified to # be a float 'f', that has a precision of 2 decimal places, '.2'. -Modulok- From ranjand2005 at gmail.com Sat Mar 5 08:13:06 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 5 Mar 2011 12:43:06 +0530 Subject: [Tutor] Error while using calendar module in Python 2.7 Message-ID: I ran the following code in python 2.6 and then in python 2.7 (using calendar module) to manipulate dates and times The following code works fine in Python 2.6 but throws up an error in Python 2.7. Can anyone please say why? CODE: import datetime import calendar while monday.weekday() != calendar.MONDAY: monday -= oneday oneweek = datetime.timedelta(days=7) nextweek = today + oneweek print next week Error: Traceback (most recent call last): File "C:\Python27\Foursoft\calendar.py", line 33, in while friday.weekday() != calendar.FRIDAY: AttributeError: 'module' object has no attribute 'FRIDAY' -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Mar 5 08:28:20 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 5 Mar 2011 02:28:20 -0500 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: Could you paste the whle code, because I get: >>> import datetime >>> import calendar >>> >>> >>> >>> while monday.weekday() != calendar.MONDAY: ... File "", line 2 ^ IndentationError: expected an indented block >>> monday -= oneday File "", line 1 monday -= oneday ^ IndentationError: unexpected indent >>> >>> oneweek = datetime.timedelta(days=7) >>> >>> nextweek = today + oneweek Traceback (most recent call last): File "", line 1, in NameError: name 'today' is not defined >>> >>> print next week From smokefloat at gmail.com Sat Mar 5 08:37:44 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 5 Mar 2011 02:37:44 -0500 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: >>> >>> while monday.weekday() != calendar.MONDAY: ... monday -= oneday ... oneweek = datetime.timedelta(days=7) ... nextweek = today + oneweek ... print "next week" ... Traceback (most recent call last): File "", line 1, in NameError: name 'monday' is not defined >>> This means that calender doesn't have an Monday as something you can access. Look at how you use datetime.timedelta(days=7). If you type help (datetime), you can see that timedelta is a function you can access from datetime. However your utilization of calendar doesn't align with the other. Look at the difference in each using the help function(datetime.timedelta and calendar.MONDAY). Also the error you show is a little confusing, because it looks like you were trying calendar.FRIDAY instead of calendar.MONDAY at that point. From ranjand2005 at gmail.com Sat Mar 5 08:50:55 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 5 Mar 2011 13:20:55 +0530 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: Sorry David The correctly indented code with the while loop is while friday.weekday() != calendar.MONDAY: MONDAY -= oneday oneweek = datetime.timedelta(days=7) nextweek = today + oneweek nextyear = today.replace(year=today.year+1) print "Today (year-month-day) =", today print "Most recent Monday =", monday Is there any change in the calendar module from Python 2.6 to 2.7. This example works fine in Python 2.6 but throws up an error in 2.7 On Sat, Mar 5, 2011 at 12:58 PM, David Hutto wrote: > Could you paste the whle code, because I get: > > >>> import datetime > >>> import calendar > >>> > >>> > >>> > >>> while monday.weekday() != calendar.MONDAY: > ... > File "", line 2 > > ^ > IndentationError: expected an indented block > >>> monday -= oneday > File "", line 1 > monday -= oneday > ^ > IndentationError: unexpected indent > >>> > >>> oneweek = datetime.timedelta(days=7) > >>> > >>> nextweek = today + oneweek > Traceback (most recent call last): > File "", line 1, in > NameError: name 'today' is not defined > >>> > >>> print next week > -- The inherent vice of capitalism is the unequal sharing of blessings; the inherent virtue of socialism is the equal sharing of miseries. ~ Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranjand2005 at gmail.com Sat Mar 5 08:52:42 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 5 Mar 2011 13:22:42 +0530 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: Please consider this corrected example The correctly indented code with the while loop is while monday.weekday() != calendar.MONDAY: MONDAY -= oneday oneweek = datetime.timedelta(days=7) nextweek = today + oneweek nextyear = today.replace(year=today.year+1) print "Today (year-month-day) =", today print "Most recent Monday =", monday On Sat, Mar 5, 2011 at 1:20 PM, ranjan das wrote: > Sorry David > > > > > > > Is there any change in the calendar module from Python 2.6 to 2.7. > > This example works fine in Python 2.6 but throws up an error in 2.7 > > > > On Sat, Mar 5, 2011 at 12:58 PM, David Hutto wrote: > >> Could you paste the whle code, because I get: >> >> >>> import datetime >> >>> import calendar >> >>> >> >>> >> >>> >> >>> while monday.weekday() != calendar.MONDAY: >> ... >> File "", line 2 >> >> ^ >> IndentationError: expected an indented block >> >>> monday -= oneday >> File "", line 1 >> monday -= oneday >> ^ >> IndentationError: unexpected indent >> >>> >> >>> oneweek = datetime.timedelta(days=7) >> >>> >> >>> nextweek = today + oneweek >> Traceback (most recent call last): >> File "", line 1, in >> NameError: name 'today' is not defined >> >>> >> >>> print next week >> > > > > -- > The inherent vice of capitalism is the unequal sharing of blessings; the > inherent virtue of socialism is the equal sharing of miseries. > > ~ Winston Churchill > -- The inherent vice of capitalism is the unequal sharing of blessings; the inherent virtue of socialism is the equal sharing of miseries. ~ Winston Churchill -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Sat Mar 5 09:23:39 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Sat, 5 Mar 2011 09:23:39 +0100 Subject: [Tutor] Shared web host and setting the python environment... In-Reply-To: References: Message-ID: Hi, I would go for appending sys.path. This is a simple way to do it, and perhaps not even needed for each python file (only files which use the modules that you have installed)) Another way to do it is adding the modules you need to sys.modules manually. 2011/3/5 Modulok > List, > > Background: > I'm on a linux based shared web host. They cater to PHP, not python. > (There's no third party python modules even installed!) So I installed > a virtual python in my home directory, plus easy_install and a bunch > of modules. Great! > > The Problem: > Unfortunately, the web server uses the system python, not my virtual > python, or my modules. (It does execute my scripts as my uid though.) > I need modify the environment of every one of my python scripts, > perhaps appending to sys.path, so that my third party modules in my > home directory can be found. I have zero control over the web server > process or its environment. > > Possible Solutions I thought of: > One way to do this would be to edit 'sys.path' at the top of every > python script. (Sounds ugly.) Another would be to import the 'user' > module and go that route. (Fine, but it's depricated. What replaces > it?) A third idea would be to re-direct all requests via mod_rewrite > to a single python file or shell script, which sets the environment > and calls my python scripts as a sub-process. (Slow, which is fine, > but some security concerns here.) > > Given my situation, what's the best way to accomplish this? (Aside > from a new hosting company or a virtual private server.) > > Any suggestions appreciated. Thanks! > -Modulok- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Mar 5 10:25:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Mar 2011 09:25:31 -0000 Subject: [Tutor] Help! (solution) References: <850472.57932.qm@web130201.mail.mud.yahoo.com> Message-ID: "michael scott" wrote >...if something about my code could be better, please tell me, OK, Here are some stylistic things... > def production_time(): > creation_time = 127 > time_till_rest = 18161 I'd move the constants out of the function to global level. And it is convention to make constants all CAPS: CREATION_TIME = 127 Also rather than arbitrary values show how these are arrived at: NUMBER_TILL_REST = 143 TIME_TILL_REST = CREATION_TIME * NUMBER_TILL_REST > items = raw_input("How many items will be produced?\n> ") > item_time = int(items) * creation_time > rest_times = item_time/time_till_rest > print rest_times > if rest_times > 0: > total = item_time + (313 * rest_times) #313 is 5 min and 13 > secs in > second form Rather than the "magic number" 313 I'd make it another constant.: REST_TIME = (5 * 60) + 13 # in seconds > else: total = item_time > time = sec_to_standard(total) > print "It would take %d days %d hours %d minutes and %d seconds > to produce > that many items" %(time[0], time[1], time[2], time[3]) > > > def sec_to_standard(seconds): > day = 86400 #secs > hour = 3600 #secs > mins = 60#seconds > creation_time = 127 #secs > time_till_rest = 18161 #secs More constants and some are duplicates. Take them outside and you only have to change them in one place so mainmtenance becomes easier. And the times get expressed as calculations: MIN=60 HOUR = MINS * 60 DAY = HOUR * 24 REST_TIME=(5* MIN)+13 > days = 0 > hours = 0 > minutes = 0 > secs = 0 Some prefer the single line style of days = hours = minutes = secs = 0 > if seconds > day: > while seconds > day: > print "doing days" > seconds = seconds - day > days += 1 This is a complicated way of doing modulo division! days,seconds = divmod(seconds,DAY) > if seconds > hour: > while seconds > hour: > print "doing hours" > seconds = seconds - hour > hours += 1 hours,seconds = divmod(seconds,HOUR) > if hours >= 24: > days += 1 > hours -= 24 This shouldn't be necessary because you already cut out the days > if seconds > mins: > while seconds > mins: > print "doing minutes" > seconds = seconds - mins > minutes += 1 minutes,seconds = divmod(seconds,MIN) > if minutes > 60: > hours += 1 > minutes -= 60 Again it shoudn't be necessary but if it had been you would have had to check the days again after increasing the hours... > secs = seconds You don't need this, just return seconds... > return days, hours, minutes, secs > > production_time() Just some ideas. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Mar 5 10:35:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Mar 2011 09:35:17 -0000 Subject: [Tutor] Help - want to display a number with two decimal places References: <7095982.6984.1299303809919.JavaMail.prodapps@nskntweba09-app> Message-ID: "Modulok" wrote > However, to make all of your numbers line up nicely, regardless of > how > long they are, you need to look into advanced string formatting via > the builtin string method 'format()'. It takes a little practice Or, if your version of Python doesn't support string.format() (pre 2.6?) you can use \t characters to insert tabs and provide a field length value in the format string and use - signs for string alignment. If you need more you can do double formatting where you use an initial format string to create the output values then insert those into the final output string. The new format() method is more powerful in these jinds of situation (although sadly still not as powerful as COBOLs "picture" feature :-( ) So your strings might look like: > # First prints the first argument (the 0th index) to 'format(), > # left aligned '<', and 18 characters wide, whitespace padded. > # Then prints the second argument, (the 1st index) right aligned, > # also 18 characters wide, but the second argument is specified > to > # be a float 'f', that has a precision of 2 decimal places, '.2'. print "%-18.0s\t%18.2f" %(....) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Mar 5 10:44:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Mar 2011 09:44:51 -0000 Subject: [Tutor] Error while using calendar module in Python 2.7 References: Message-ID: "ranjan das" wrote > The following code works fine in Python 2.6 but throws up an error > in Python > 2.7. Can anyone please say why? > > import datetime > import calendar > > while monday.weekday() != calendar.MONDAY: where does 'monday' come from? Can you send a minimal example that could actually run that shjows the error? This is obviously just a code fragment. > Error: > Traceback (most recent call last): > File "C:\Python27\Foursoft\calendar.py", line 33, in > while friday.weekday() != calendar.FRIDAY: > AttributeError: 'module' object has no attribute 'FRIDAY' The obvious solution is that calendar has changed between 2.6 and 2.7 but looking on v3.1(I don;t have 2.7 installed) it looks the same there. Certainly the day constants are still there. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Mar 5 10:47:55 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Mar 2011 20:47:55 +1100 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: <4D7206CB.2050004@pearwood.info> ranjan das wrote: > I ran the following code in python 2.6 and then in python 2.7 (using > calendar module) to manipulate dates and times > > The following code works fine in Python 2.6 but throws up an error in Python > 2.7. Can anyone please say why? No it does not work fine at all. It generates a SyntaxError in every version of Python, including 2.6 and 2.7: print next week ^ SyntaxError: invalid syntax After fixing that error, I get: NameError: name 'monday' is not defined Please COPY and PASTE the ACTUAL code you run, do not retype it. Make sure that it actually does run before claiming it runs. Do not waste everybody's time with junk code that doesn't run, and them waste our time again with not one but *two* corrections, neither of which actually fix the broken code. -- Steven From steve at pearwood.info Sat Mar 5 10:49:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Mar 2011 20:49:44 +1100 Subject: [Tutor] Error while using calendar module in Python 2.7 In-Reply-To: References: Message-ID: <4D720738.5020200@pearwood.info> Alan Gauld wrote: > > "ranjan das" wrote >> Error: >> Traceback (most recent call last): >> File "C:\Python27\Foursoft\calendar.py", line 33, in >> while friday.weekday() != calendar.FRIDAY: >> AttributeError: 'module' object has no attribute 'FRIDAY' > > The obvious solution is that calendar has changed between 2.6 and 2.7 > but looking on v3.1(I don;t have 2.7 installed) it looks the same there. > Certainly the day constants are still there. What's "Foursoft"? I would say that the standard library calendar module is being shadowed by another module with the same name. -- Steven From ranjand2005 at gmail.com Sat Mar 5 10:53:35 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Sat, 5 Mar 2011 15:23:35 +0530 Subject: [Tutor] Sorting a dictionary by a value when the values are tuples Message-ID: This is a small example i created from operator import itemgetter temp={'4':(2,3), '2':(5,8)} print temp.items() new_temp=sorted(temp.items(), key=itemgetter(1) print new_temp I want to sort the dictionary by the value in the first element of the tuple ((2,3) and (5,8)) and then the second value. How do i do it? by setting key=itemgetter(1), it seems to sort the dict by the first value of the tuple. But I am not able to do it for the second value. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Mar 5 10:59:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Mar 2011 20:59:44 +1100 Subject: [Tutor] Help - want to display a number with two decimal places In-Reply-To: References: <7095982.6984.1299303809919.JavaMail.prodapps@nskntweba09-app> Message-ID: <4D720990.8070903@pearwood.info> Modulok wrote: > Notice that 'd' in your string substitution means integers, not > floats. Any decimal places will be truncated when using 'd'. For > floats use 'f' instead. You an also specify a precision, such as > '%.2f' shows two decimal places. > > However, to make all of your numbers line up nicely, regardless of how > long they are, you need to look into advanced string formatting via > the builtin string method 'format()'. It takes a little practice to > understand and use, but the results are exactly what you want. str.format only exists from Python 2.6, but in any case, it certainly isn't true that you "need" to look at format to make numbers line up nicely. The examples you give can all be written using string interpolation: > print "{0:<18} {1:>18.2f}".format("Country Sales Tax", countrySalesTax) > print "{0:<18} {1:>18.2f}".format("Purchase Price", purchasePrice) > # First prints the first argument (the 0th index) to 'format(), > # left aligned '<', and 18 characters wide, whitespace padded. > # Then prints the second argument, (the 1st index) right aligned, > # also 18 characters wide, but the second argument is specified to > # be a float 'f', that has a precision of 2 decimal places, '.2'. >>> countrySalesTax = 11.25 >>> purchasePrice = 124577.35 >>> print "%-18s %18.2f" % ("Country Sales Tax", countrySalesTax); \ ... print "%-18s %18.2f" % ("Purchase Price", purchasePrice) Country Sales Tax 11.25 Purchase Price 124577.35 str.format can do some things better than % interpolation, but formatting strings to a width is not one of them. It's also a matter of opinion which is more cryptic: "%-18s %18.2f" "{0:<18} {1:>18.2f}" -- Steven From steve at pearwood.info Sat Mar 5 11:11:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Mar 2011 21:11:11 +1100 Subject: [Tutor] Sorting a dictionary by a value when the values are tuples In-Reply-To: References: Message-ID: <4D720C3F.8080008@pearwood.info> ranjan das wrote: > This is a small example i created > > > from operator import itemgetter > temp={'4':(2,3), '2':(5,8)} > print temp.items() > new_temp=sorted(temp.items(), key=itemgetter(1) > print new_temp Another syntax error. Please ensure that you test your code before posting. In this case, it's easy to fix: you're missing a closing bracket in the call to sorted(). > I want to sort the dictionary by the value in the first element of the tuple > ((2,3) and (5,8)) and then the second value. That would be the ordinary sort order of tuples. > How do i do it? by setting key=itemgetter(1), it seems to sort the dict by > the first value of the tuple. But I am not able to do it for the second > value. You can't sort *dicts*, because they are unordered. However, you extract the key:value items from the dict into a list, which gives you a list of tuples: >>> from operator import itemgetter >>> temp={'4':(2,3), '2':(5,8)} >>> print temp.items() [('2', (5, 8)), ('4', (2, 3))] You want to ignore the key part (the first item in the *outer* tuples, namely '2' and '4'), and just sort by the value part (the second item of the outer tuples, namely (2, 3) and (5, 8) -- note that these are themselves also tuples. The way to sort them is using itemgetter(1), exactly as you tried: >>> new_temp=sorted(temp.items(), key=itemgetter(1)) >>> print new_temp [('4', (2, 3)), ('2', (5, 8))] What makes you think that it did not work correctly? Here is a better example, showing that it works fine: >>> temp = {'a':(2,3), 'b':(5,8), 'c':(5,1), 'd':(2,1)} >>> temp.items() [('a', (2, 3)), ('c', (5, 1)), ('b', (5, 8)), ('d', (2, 1))] >>> sorted(temp.items(), key=itemgetter(1)) [('d', (2, 1)), ('a', (2, 3)), ('c', (5, 1)), ('b', (5, 8))] -- Steven From alan.gauld at btinternet.com Sat Mar 5 15:03:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 5 Mar 2011 14:03:40 -0000 Subject: [Tutor] Error while using calendar module in Python 2.7 References: <4D720738.5020200@pearwood.info> Message-ID: "Steven D'Aprano" wrote >>> File "C:\Python27\Foursoft\calendar.py", line 33, in > > What's "Foursoft"? > > I would say that the standard library calendar module is being > shadowed Ah, good catch. I didn't notice the path was non standard. Alan G From lagrapidis at yahoo.com Sat Mar 5 21:54:16 2011 From: lagrapidis at yahoo.com (Lukas Agrapidis) Date: Sat, 5 Mar 2011 12:54:16 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <891331.90530.qm@web36106.mail.mud.yahoo.com> http://www.locandalemandriane.it/index04.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From travispierce at hotmail.com Sun Mar 6 01:04:23 2011 From: travispierce at hotmail.com (Travis Pierce) Date: Sat, 5 Mar 2011 18:04:23 -0600 Subject: [Tutor] pyton module index, windoes error 5 Message-ID: I am new to programming and am using Allen Downey's How to Think Like a Programmer, 2nd Edition Python edition to start learning. I am having trouble viewing the pydoc graphic on a local host. I know this is not necessarily a Python question, but I would appreciate any advice that can be provided. I am using Windows 7 I am on chapter 10 and trying to graphically view the Python Index of Modules on local host 7464. When attempting to do this in the command line I receive a windows error. Here is the end of the message I receive: File "C:\Python26\Lib\pkgutil.py", line 211, in iter_modules for fn in os.listdir: WindowsError: [Error 5] Access is denied: '.\\Application Data/*.*' I thought that I may not have root access to the folders in question, but I have gone through and given myself administrative access to all documents in the c:\python26 directory, and I am still receiving this error. Thanks for any help that you can provide! -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1984docmccoy at gmail.com Sun Mar 6 09:56:51 2011 From: 1984docmccoy at gmail.com (Arthur Mc Coy) Date: Sun, 6 Mar 2011 10:56:51 +0200 Subject: [Tutor] c++ data types in python script Message-ID: Hi people, I've used SWIG module to embed python inside c++ app. I pass a list of objects (with lots of different properties of types string, float, custom types like URL, Software and finally of list of strings). Now I'm in python. URL and Software has str() method that converts their value to string recognizable by JSON. But the problem is with list of strings. So, as I said I passed std::list myObjects to python function. Then I iterate it and for each object in myObjects I create a python copy (serialize it) to be able to put into JSON format and store in appropriate file. object has property benchmarks of type list. I do: ... class PythonObject: def __init__(self, object): self.benchmarks = list() for s in object.benchmarks: self.benchmarks.append(s) ... and it fails, also I do: ... class PythonObject: def __init__(self, object): self.benchmarks = [unicode(s) for s in object.benchmarks] ... and it fails, also I do: ... class PythonObject: def __init__(self, object): for s in object.benchmarks: print s[0] + s[1] + s[2] print type(s) ... and it fails printing wor Segmentation fault (core dumped) $ also I do: ... class PythonObject: def __init__(self, object): self.benchmarks = unicode(object.benchmarks) ... and it does not fail, instead it puts in JSON this string: ... "benchmarks": " > *' at 0xb63ed4e8>>", ... but it is not what I need What I'm trying to stress is that c++ objects should be converted (serialized) before putting them into json. Otherwise type errors occur and process fails. I love learning python and hope somebody may suggest me or tell something. Thank you all anyway! Arthur -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sun Mar 6 10:18:35 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 06 Mar 2011 10:18:35 +0100 Subject: [Tutor] c++ data types in python script In-Reply-To: References: Message-ID: Arthur Mc Coy, 06.03.2011 09:56: > I've used SWIG module to embed python inside c++ app. Given that this deals with an advanced topic (C-level extensions), I find comp.lang.python (python-list), where you also posted this, a more appropriate place for discussion than the Python tutor mailing list. So I suggest people answer on c.l.py. Stefan From 1984docmccoy at gmail.com Sun Mar 6 10:46:34 2011 From: 1984docmccoy at gmail.com (Arthur Mc Coy) Date: Sun, 6 Mar 2011 11:46:34 +0200 Subject: [Tutor] c++ data types in python script In-Reply-To: References: Message-ID: Thank you, sorry for duplicating. I hope moderators can delete it if needed. Wish you well, Arthur On Sun, Mar 6, 2011 at 11:18 AM, Stefan Behnel wrote: > Arthur Mc Coy, 06.03.2011 09:56: > > I've used SWIG module to embed python inside c++ app. >> > > Given that this deals with an advanced topic (C-level extensions), I find > comp.lang.python (python-list), where you also posted this, a more > appropriate place for discussion than the Python tutor mailing list. So I > suggest people answer on c.l.py. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mahesh.mach at gmail.com Mon Mar 7 01:50:39 2011 From: mahesh.mach at gmail.com (Mahesh Narayanamurthi) Date: Sun, 6 Mar 2011 19:50:39 -0500 Subject: [Tutor] BLAS Implementation on Python Message-ID: Hello, I am thinking of implementing a BLAS package in pure python. I am wondering if this is a good idea. My design goals are: [1] Efficient manipulation of Matrices and Vectors using pure python objects and python code. [2] Targetted to run on Python3 [3] Extensive use of defensive programming style [4] To serve as a reference design for future High Performance Code in Python [5] To serve as a reference material in classroom courses on numerical computing or for hobbyist programmers Thanks, Mahesh Narayanamurthi -------------- next part -------------- An HTML attachment was scrubbed... URL: From nookasree at yahoo.com Mon Mar 7 04:31:53 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Sun, 6 Mar 2011 19:31:53 -0800 (PST) Subject: [Tutor] calculate the sum of a variable - python Message-ID: <978601.22061.qm@web65405.mail.ac4.yahoo.com> Hi : I'm a Senior SAS Analyst. I'm trying to learn Python. I would appreciate if anybody could help me with this. It works fine if I give input instead of reading a text file. I don't understand where I'm going wrong. I'm trying to read a text file and find out the following: 1. Sum of amt for each id 2. Count of id 3. minimum of date1 4. maximum of date1 Here is the sample text file: test.txt file: bin1 cd1 date1 amt cd id cd2 452 2 2010-02-20 $23.26 0 8100059542 06107 452 2 2010-02-20 $20.78 0 8100059542 06107 452 2 2010-02-24 $5.99 2 8100839745 20151 452 2 2010-02-12 $114.25 7 8100839745 98101 452 2 2010-02-06 $28.00 0 8101142362 06032 452 2 2010-02-09 $15.01 0 8100274453 06040 452 18 2010-02-13 $113.24 0 8100274453 06040 452 2 2010-02-13 $31.80 0 8100274453 06040 Here is the code I've tried out to calculate sum of amt by id: import sys from itertools import groupby from operator import itemgetter t = () tot = [] for line in open ('test.txt','r'): aline = line.rstrip().split() a = aline[5] b = (aline[3].strip('$')) t = (a,b) t1 = str(t) tot.append(t1) print tot def summary(data, key=itemgetter(0), value=itemgetter(1)): for k, group in groupby(data, key): yield (k, sum(value(row) for row in group)) if __name__ == "__main__": for id, tot_spend in summary(tot, key=itemgetter(0), value=itemgetter(1)): print id, tot_spend Error: Traceback (most recent call last): File "", line 2, in File "", line 3, in summary TypeError: unsupported operand type(s) for +: 'int' and 'str' Thanks, Sree. From waynejwerner at gmail.com Mon Mar 7 04:44:00 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 6 Mar 2011 21:44:00 -0600 Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: <978601.22061.qm@web65405.mail.ac4.yahoo.com> References: <978601.22061.qm@web65405.mail.ac4.yahoo.com> Message-ID: On Sun, Mar 6, 2011 at 9:31 PM, nookasree ponamala wrote: > Hi : > > I'm a Senior SAS Analyst. I'm trying to learn Python. I would appreciate if > anybody could help me with this. It works fine if I give input instead of > reading a text file. I don't understand where I'm going wrong. > > I'm trying to read a text file and find out the following: > 1. Sum of amt for each id > 2. Count of id > 3. minimum of date1 > 4. maximum of date1 > > Here is the sample text file: > > test.txt file: > > bin1 cd1 date1 amt cd id cd2 > 452 2 2010-02-20 $23.26 0 8100059542 06107 > 452 2 2010-02-20 $20.78 0 8100059542 06107 > 452 2 2010-02-24 $5.99 2 8100839745 20151 > 452 2 2010-02-12 $114.25 7 8100839745 98101 > 452 2 2010-02-06 $28.00 0 8101142362 06032 > 452 2 2010-02-09 $15.01 0 8100274453 06040 > 452 18 2010-02-13 $113.24 0 8100274453 06040 > 452 2 2010-02-13 $31.80 0 8100274453 06040 > > > Here is the code I've tried out to calculate sum of amt by id: > > import sys > from itertools import groupby > from operator import itemgetter > t = () > tot = [] > for line in open ('test.txt','r'): > aline = line.rstrip().split() > a = aline[5] > b = (aline[3].strip('$')) > t = (a,b) > t1 = str(t) > tot.append(t1) > print tot > def summary(data, key=itemgetter(0), value=itemgetter(1)): > for k, group in groupby(data, key): > yield (k, sum(value(row) for row in group)) > > if __name__ == "__main__": > for id, tot_spend in summary(tot, key=itemgetter(0), > value=itemgetter(1)): > print id, tot_spend > > > Error: > Traceback (most recent call last): > File "", line 2, in > File "", line 3, in summary > TypeError: unsupported operand type(s) for +: 'int' and 'str' > Of course I first have to commend you for including the full traceback with the code because it makes this entirely easy to answer. In general, the traceback tells you the most important stuff last, so I'll start with this line: > TypeError: unsupported operand type(s) for +: 'int' and 'str' That tells us that the problem is you are trying to use + (addition) on an integer and a string - which you can't do because of the type mismatch (TypeError). The next line > File "", line 3, in summary tells us that the error occurred on line3 in summary: 1 | def summary(data, key=itemgetter(0), value=itemgetter(1)): 2 | for k, group in groupby(data, key): 3 | yield (k, sum(value(row) for row in group)) Well, there's no '+', but you do have 'sum', which uses addition under the hood. So how do you go about fixing it? Well, you change the value getting passed to sum to an integer (or other number): sum(int(value(row)) for row in group) Should either fix your problem, or throw a differen error if you try to convert a string like 'Hello' to an integer. (Alternatively, use float if you're interested in decimals) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From nookasree at yahoo.com Mon Mar 7 05:46:21 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Sun, 6 Mar 2011 20:46:21 -0800 (PST) Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: Message-ID: <64268.66027.qm@web65408.mail.ac4.yahoo.com> Thanks for the reply Wayne, but still it is not working, ? when I used int It throws the below error: ? File "", line 2, in ? File "", line 3, in summary ? File "", line 3, in ValueError: invalid literal for int() with base 10: "'" ? I tried using float and the error is: Traceback (most recent call last): ? File "", line 2, in ? File "", line 3, in summary ? File "", line 3, in ValueError: invalid literal for float(): ' ? Thanks, Sree. --- On Mon, 3/7/11, Wayne Werner wrote: From: Wayne Werner Subject: Re: [Tutor] calculate the sum of a variable - python To: "nookasree ponamala" Cc: tutor at python.org Date: Monday, March 7, 2011, 9:14 AM On Sun, Mar 6, 2011 at 9:31 PM, nookasree ponamala wrote: Hi : I'm a Senior SAS Analyst. I'm trying to learn Python. I would appreciate if anybody could help me with this. It works fine if I give input ?instead of reading a text file. I don't understand where I'm going wrong. I'm trying to read a text file and find out the following: 1. Sum of amt for each id 2. Count of id 3. minimum of date1 4. maximum of date1 Here is the sample text file: test.txt file: bin1 ? ?cd1 ? ? date1 ? amt ? ? cd ? ?id cd2 452 ?2 ? ? ? 2010-02-20 ? ? ?$23.26 ?0 ? ?8100059542 ? ? ? ?06107 452 ?2 ? ? ? 2010-02-20 ? ? ?$20.78 ?0 ? ? ? ? ?8100059542 ? ? ? ?06107 452 ?2 ? ? ? 2010-02-24 ? ? ?$5.99 ? 2 ? ? ? ? ?8100839745 ? ? ? ?20151 452 ?2 ? ? ? 2010-02-12 ? ? ?$114.25 7 ? ? ? ? ?8100839745 ? ? ? ?98101 452 ?2 ? ? ? 2010-02-06 ? ? ?$28.00 ?0 ? ? ? ? ?8101142362 ? ? ? ?06032 452 ?2 ? ? ? 2010-02-09 ? ? ?$15.01 ?0 ? ? ? ? ?8100274453 ? ? ? ?06040 452 ?18 ? ? ?2010-02-13 ? ? ?$113.24 0 ? ? ? ? ?8100274453 ? ? ? ?06040 452 ?2 ? ? ? 2010-02-13 ? ? ?$31.80 ?0 ? ? ? ? ?8100274453 ? ? ? ?06040 Here is the code I've tried out to calculate sum of amt by id: import sys from itertools import groupby from operator import itemgetter t = () tot = [] for line in open ('test.txt','r'): ? ? ? ?aline = line.rstrip().split() ? ? ? ?a = aline[5] ? ? ? ?b = (aline[3].strip('$')) ? ? ? ?t = (a,b) ? ? ? ?t1 = str(t) ? ? ? ?tot.append(t1) ? ? ? ?print tot def summary(data, key=itemgetter(0), value=itemgetter(1)): ? ? ? ?for k, group in groupby(data, key): ? ? ? ? ? ? ? ?yield (k, sum(value(row) for row in group)) if __name__ == "__main__": ? ? ? ?for id, tot_spend in summary(tot, key=itemgetter(0), value=itemgetter(1)): ? ? ? ? ? ?print id, tot_spend Error: Traceback (most recent call last): ?File "", line 2, in ?File "", line 3, in summary TypeError: unsupported operand type(s) for +: 'int' and 'str' Of course I first have to commend you for including the full traceback with the code because it makes this entirely easy to answer. In general, the traceback tells you the most important stuff last, so I'll start with this line:? > TypeError: unsupported operand type(s) for +: 'int' and 'str' That tells us that the problem is you are trying to use + (addition) on an integer and a string - which you can't do because of the type mismatch (TypeError). The next line > File "", line 3, in summary tells us that the error occurred on line3 in summary: 1 | def summary(data, key=itemgetter(0), value=itemgetter(1)): 2 | ? ? ? ?for k, group in groupby(data, key): 3 | ? ? ? ? ? ? ? ?yield (k, sum(value(row) for row in group)) Well, there's no '+', but you do have 'sum', which uses addition under the hood. So how do you go about fixing it? Well, you change the value getting passed to sum to an integer (or other number): sum(int(value(row)) for row in group) Should either fix your problem, or throw a differen error if you try to convert a string like 'Hello' to an integer. (Alternatively, use float if you're interested in decimals) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Mar 7 06:11:25 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 6 Mar 2011 23:11:25 -0600 Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: <64268.66027.qm@web65408.mail.ac4.yahoo.com> References: <64268.66027.qm@web65408.mail.ac4.yahoo.com> Message-ID: On Sun, Mar 6, 2011 at 10:46 PM, nookasree ponamala wrote: > Thanks for the reply Wayne, but still it is not working, > > when I used int It throws the below error: > File "", line 2, in > File "", line 3, in summary > File "", line 3, in > ValueError: invalid literal for int() with base 10: "'" > It gives you a single-quote character that apparently you are trying to turn into a number. I'm not exactly sure what the problem is there - you should probably unwrap your generator expression into the equivalent loop(s) and either insert some strategic print statements or use a debugger, such as the python debugger. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 7 06:24:10 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 6 Mar 2011 21:24:10 -0800 Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: <64268.66027.qm@web65408.mail.ac4.yahoo.com> References: <64268.66027.qm@web65408.mail.ac4.yahoo.com> Message-ID: On Sun, Mar 6, 2011 at 8:46 PM, nookasree ponamala wrote: > Thanks for the reply Wayne, but still it is not working, > > when I used int It throws the below error: > File "", line 2, in > File "", line 3, in summary > File "", line 3, in > ValueError: invalid literal for int() with base 10: "'" > > I tried using float and the error is: > Traceback (most recent call last): > File "", line 2, in > File "", line 3, in summary > File "", line 3, in > ValueError: invalid literal for float(): ' > > Thanks, > Sree. > > I played with it a bit and simplified things a (little) bit: > b = (aline[3].strip('$')) > t = (a, float(b)) > tot.append(t) > print tot > You were converting the tuple to a string before adding it to the list; you don't need to do that, and it was concealing the real cause of your problem, which is that you either need to skip/get rid of the top line of your file, or write some error-handling code to deal with it. Currently, you're trying to convert the string 'amt' into a number, and you just can't do that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nookasree at yahoo.com Mon Mar 7 08:27:28 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Sun, 6 Mar 2011 23:27:28 -0800 (PST) Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: Message-ID: <628205.3486.qm@web65406.mail.ac4.yahoo.com> Thanks a lot?Marc. This works now. ? Sree. --- On Mon, 3/7/11, Marc Tompkins wrote: From: Marc Tompkins Subject: Re: [Tutor] calculate the sum of a variable - python To: "nookasree ponamala" Cc: "Wayne Werner" , tutor at python.org Date: Monday, March 7, 2011, 10:54 AM On Sun, Mar 6, 2011 at 8:46 PM, nookasree ponamala wrote: Thanks for the reply Wayne, but still it is not working, ? when I used int It throws the below error: ? File "", line 2, in ? File "", line 3, in summary ? File "", line 3, in ValueError: invalid literal for int() with base 10: "'" ? I tried using float and the error is: Traceback (most recent call last): ? File "", line 2, in ? File "", line 3, in summary ? File "", line 3, in ValueError: invalid literal for float(): ' ? Thanks, Sree. I played with it a bit and simplified things a (little) bit: ?????? b = (aline[3].strip('$')) ?????? t = (a, float(b)) ?????? tot.append(t) ?????? print tot You were converting the tuple to a string before adding it to the list; you don't need to do that, and it was concealing the real cause of your problem, which is that you either need to skip/get rid of the top line of your file, or write some error-handling code to deal with it.? Currently, you're trying to convert the string 'amt' into a number, and you just can't do that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 7 08:40:17 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 6 Mar 2011 23:40:17 -0800 Subject: [Tutor] calculate the sum of a variable - python In-Reply-To: <628205.3486.qm@web65406.mail.ac4.yahoo.com> References: <628205.3486.qm@web65406.mail.ac4.yahoo.com> Message-ID: On Sun, Mar 6, 2011 at 11:27 PM, nookasree ponamala wrote: > Thanks a lot Marc. This works now. > > Sree. > > Glad to hear it. Welcome to the list, by the way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vineethrakesh at gmail.com Mon Mar 7 08:54:30 2011 From: vineethrakesh at gmail.com (vineeth) Date: Mon, 07 Mar 2011 02:54:30 -0500 Subject: [Tutor] help with re module and parsing data Message-ID: <4D748F36.1000006@gmail.com> Hello all I am doing some analysis on my trace file. I am finding the lines Recvd-Content and Published-Content. I am able to find those lines but the re module as predicted just gives the word that is being searched. But I require the entire line similar to a grep in unix. Can some one tell me how to do this. I am doing the following way. import re file = open('file.txt','r') file2 = open('newfile.txt','w') LineFile = ' ' for line in file: LineFile += line StripRcvdCnt = re.compile('(P\w+\S\Content|Re\w+\S\Content)') FindRcvdCnt = re.findall(StripRcvdCnt, LineFile) for SrcStr in FindRcvdCnt: file2.write(SrcStr) Thanks Vin From kushal.kumaran+python at gmail.com Mon Mar 7 12:22:57 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 7 Mar 2011 16:52:57 +0530 Subject: [Tutor] help with re module and parsing data In-Reply-To: <4D748F36.1000006@gmail.com> References: <4D748F36.1000006@gmail.com> Message-ID: On Mon, Mar 7, 2011 at 1:24 PM, vineeth wrote: > Hello all I am doing some analysis on my trace file. I am finding the lines > Recvd-Content and Published-Content. I am able to find those lines but the > re module as predicted just gives the word that is being searched. But I > require the entire ?line similar to a grep in unix. Can some one tell me how > to do this. I am doing the following way. > > import re > file = open('file.txt','r') > file2 = open('newfile.txt','w') > > LineFile = ' ' > > for line in file: > ? ?LineFile += line > > StripRcvdCnt = re.compile('(P\w+\S\Content|Re\w+\S\Content)') > > FindRcvdCnt = re.findall(StripRcvdCnt, LineFile) > > for SrcStr in FindRcvdCnt: > ? ?file2.write(SrcStr) > Is there any particular reason why you're using regular expressions for this? You are already iterating over the lines in your first for loop. You can just make the tests you need there. for line in file: if 'Recvd-Content' in line or 'Published-Content' in line: Your regular expression seems like it will match a lot more strings than the two you mentioned earlier. Also, 'file' is a python built-in. It will be best to use a different name for your variable. -- regards, kushal From mailshuwei at gmail.com Mon Mar 7 13:15:12 2011 From: mailshuwei at gmail.com (shu wei) Date: Mon, 7 Mar 2011 06:15:12 -0600 Subject: [Tutor] How to sum weighted matrices Message-ID: Hello all, I am new to python and numpy. My question is how to sum up N weighted matrices. For example w=[1,2] (N=2 case) m1=[1 2 3, 3 4 5] m2=[3 4 5, 4 5 6] I want to get a matrix Y=w[1]*m1+w[2]*m2 by using a loop. My original problem is like this X=[1 2 3, 3 4 5, 4 5 6] a1=[1 2 3] 1st row of X m1=a1'*a1 a matirx a2=[3 4 5] 2nd row of X m2=a2'*a2 a3=[ 4 5 6] 3rd row of X m3=a3'*a3 I want to get Y1=w[1]*m1+w[2]*m2 Y2=w[1]*m2+w[2]*m3 So basically it is rolling and to sum up the weighted matries I have a big X, the rolling window is relatively small. I tried to use sq=np.array([x[i].reshape(-1,1)*x[i] for i in np.arange(0,len(x)]) # s=len(x) m=np.array([sq[i:i+t] for i in np.arange(0,s-t+1)]) # t is the len(w) then I was stuck, I tried to use a loop somethig like Y=np.array([np.sum(w[i]*m[j,i],axis=0) for i in np.arange(0,t)] ) Any suggestion is welcome. sue -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Mon Mar 7 14:24:36 2011 From: wescpy at gmail.com (wesley chun) Date: Mon, 7 Mar 2011 08:24:36 -0500 Subject: [Tutor] help with re module and parsing data In-Reply-To: References: <4D748F36.1000006@gmail.com> Message-ID: >> import re >> file = open('file.txt','r') >> file2 = open('newfile.txt','w') >> >> LineFile = ' ' >> >> for line in file: >> ? ?LineFile += line >> >> StripRcvdCnt = re.compile('(P\w+\S\Content|Re\w+\S\Content)') >> >> FindRcvdCnt = re.findall(StripRcvdCnt, LineFile) >> >> for SrcStr in FindRcvdCnt: >> ? ?file2.write(SrcStr) >> > > Is there any particular reason why you're using regular expressions > for this? ?You are already iterating over the lines in your first for > loop. ?You can just make the tests you need there. > > for line in file: > ?if 'Recvd-Content' in line or 'Published-Content' in line: > ? ? > > Your regular expression seems like it will match a lot more strings > than the two you mentioned earlier. > > Also, 'file' is a python built-in. ?It will be best to use a different > name for your variable. i have a few suggestions as well: 1) class names should be titlecased, not ordinary variables, so LineFile should be linefile, line_file, or lineFile. 2) you don't need to read in the file one line at-a-time. you can just do linefile = f.read() ... this reads the entire file in as one massive string. 3) you don't need to compile your regex (unless you will be using this pattern over and over within one execution of this script). you can just call findall() directly: findrcvdcnt = re.findall('(P\w+\S\Content|Re\w+\S\Content)', LineFile) hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ? http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From stefan_ml at behnel.de Mon Mar 7 14:28:15 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 07 Mar 2011 14:28:15 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: References: Message-ID: Mahesh Narayanamurthi, 07.03.2011 01:50: > I am thinking of implementing a BLAS package in pure python. I am wondering > if this is a good idea. My design goals are: > > [1] Efficient manipulation of Matrices and > Vectors using pure python objects and > python code. > [2] Targetted to run on Python3 > [3] Extensive use of defensive programming > style > [4] To serve as a reference design for > future High Performance Code in Python > [5] To serve as a reference material in > classroom courses on numerical computing > or for hobbyist programmers First question that comes to my mind: who would use this? The available packages are commonly not written in Python, but they are fast, which is why they are being used by Python programs. A quick web search brought up Tokyo, for example, which wraps BLAS in Cython: https://github.com/tokyo/tokyo I can see that it would be easier to teach the concepts based on code written in Python than based on the existing implementations. Even if there likely won't be a real use case, it may still be nice to have a pure Python implementation available, if it could serve as a drop-in replacement for faster implementations. I.e., you could present the inner workings based on the Python code, and then switch to a 'real' implementation for the actual computations. However, even if you say "efficient" above (and the algorithms may well be efficient), don't expect it to be fast. Python is great for orchestrating high performance computations. It's less great for doing them in plain Python code. Stefan From knacktus at googlemail.com Mon Mar 7 14:28:56 2011 From: knacktus at googlemail.com (Knacktus) Date: Mon, 07 Mar 2011 14:28:56 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: References: Message-ID: <4D74DD98.1020908@googlemail.com> Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi: > Hello, > > I am thinking of implementing a BLAS package in pure python. I am > wondering if this is a good idea. I don't think so. Usually people write extensions to the CPython implementation (when talking about performance, we need to talk about Python implementations like CPython, Jython or PyPy) in C to do high performance stuff. Pure CPython is (depeneding on the problem) magnitudes slower than C. Also, there's NumPy SciPy. Check those out. More comments below ... My design goals are: > > > [1] Efficient manipulation of Matrices and > Vectors using pure python objects and > python code. No, not efficient in terms of performance. > [2] Targetted to run on Python3 Good idea. NumPy and SciPy will be (are already?) ported. > [3] Extensive use of defensive programming > style > [4] To serve as a reference design for > future High Performance Code in Python The future of High Performance Python is probably PyPy. > [5] To serve as a reference material in > classroom courses on numerical computing > or for hobbyist programmers Good idea, as Python is clear and nice to read. > > Thanks, > Mahesh Narayanamurthi > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Mon Mar 7 14:45:47 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 07 Mar 2011 14:45:47 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: <4D74DD98.1020908@googlemail.com> References: <4D74DD98.1020908@googlemail.com> Message-ID: Knacktus, 07.03.2011 14:28: > Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi: >> Hello, >> >> I am thinking of implementing a BLAS package in pure python. I am >> wondering if this is a good idea. >> > My design goals are: >> >> [2] Targetted to run on Python3 > Good idea. NumPy and SciPy will be (are already?) ported. Yes, NumPy has been ported as of version 1.5. Not sure about the overall status of SciPy, their FAQ isn't up to date. >> [4] To serve as a reference design for >> future High Performance Code in Python > The future of High Performance Python is probably PyPy. PyPy has been "the future" ever since they started ;-). They have gotten faster, but it's is still far from being suitable for any kind of numerical high performance computing. That will continue to be the domain of C, Fortran and Cython for a while, and potentially including LuaJIT2 for certain use cases (usable from Python through Lupa, BTW). Stefan From fomcl at yahoo.com Mon Mar 7 16:02:44 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 7 Mar 2011 07:02:44 -0800 (PST) Subject: [Tutor] ctypes question Message-ID: <156862.38339.qm@web110711.mail.gq1.yahoo.com> Hi, I want to use a dll to read Spss data files. But when I use lib = ctypes.cdll.LoadLibary("d:/temp/spssio32.dll") I?get a WindowsError (cannot find module), even though the path exists. Why is that? Do I need to extend?some environment variable (add another?dir)? I am using Python 2.5 on Windows 2000, but I also unsuccessfully tried it?using Python 2.7 on Ubuntu 10 (however, I don't want to write the program on?a linux system because I'll be using it on windows?only).?I also got the same error when I tried some other dll's. Thanks in advance! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From pacificmorrowind at gmail.com Mon Mar 7 16:36:52 2011 From: pacificmorrowind at gmail.com (Pacific Morrowind) Date: Mon, 07 Mar 2011 07:36:52 -0800 Subject: [Tutor] ctypes question In-Reply-To: <156862.38339.qm@web110711.mail.gq1.yahoo.com> References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> Message-ID: <4D74FB94.8090303@gmail.com> Hi On 07/03/2011 7:02 AM, Albert-Jan Roskam wrote: > Hi, > I want to use a dll to read Spss data files. But when I use > lib = ctypes.cdll.LoadLibary("d:/temp/spssio32.dll") > I get a WindowsError (cannot find module), even though the path > exists. Why is that? Do I need to extend some environment variable > (add another dir)? I am using Python 2.5 on Windows 2000, but I also > unsuccessfully tried it using Python 2.7 on Ubuntu 10 (however, I > don't want to write the program on a linux system because I'll be > using it on windows only). I also got the same error when I tried some > other dll's. but that path doesn't actually exist... replace that path with either r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise the /t will be transformed into a tab. Nick > Thanks in advance! > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, > wine, public order, irrigation, roads, a fresh water system, and > public health, what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Mar 7 16:40:37 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 7 Mar 2011 10:40:37 -0500 Subject: [Tutor] ctypes question In-Reply-To: <4D74FB94.8090303@gmail.com> References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> Message-ID: On Mon, Mar 7, 2011 at 10:36 AM, Pacific Morrowind < pacificmorrowind at gmail.com> wrote: > Hi > > > On 07/03/2011 7:02 AM, Albert-Jan Roskam wrote: > > Hi, > > I want to use a dll to read Spss data files. But when I use > lib = ctypes.cdll.LoadLibary("d:/temp/spssio32.dll") > I get a WindowsError (cannot find module), even though the path exists. Why > is that? Do I need to extend some environment variable (add another dir)? I > am using Python 2.5 on Windows 2000, but I also unsuccessfully tried > it using Python 2.7 on Ubuntu 10 (however, I don't want to write the program > on a linux system because I'll be using it on windows only). I also got the > same error when I tried some other dll's. > > > but that path doesn't actually exist... replace that path with either > r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise the /t > will be transformed into a tab. > Nick > > Thanks in advance! > > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, wine, > public order, irrigation, roads, a fresh water system, and public health, > what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > "but that path doesn't actually exist... replace that path with either r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise the /t will be transformed into a tab. Nick" I don't think that is the problem. '\t' would transform to tab, but not '/t'. Right? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandru.ioan at eurocontrol.int Mon Mar 7 12:03:42 2011 From: alexandru.ioan at eurocontrol.int (IOAN Alexandru) Date: Mon, 7 Mar 2011 12:03:42 +0100 Subject: [Tutor] Running scripts/tkinter Message-ID: On windows XP pro. Ver. 2002 SP 3. I get the following: <> The same is for Python27. Please help me with some ideas. Tks. ____ ? This message and any files transmitted with it are legally privileged and intended for the sole use of the individual(s) or entity to whom they are addressed. If you are not the intended recipient, please notify the sender by reply and delete the message and any attachments from your system. Any unauthorised use or disclosure of the content of this message is strictly prohibited and may be unlawful. ? Nothing in this e-mail message amounts to a contractual or legal commitment on the part of EUROCONTROL, unless it is confirmed by appropriately signed hard copy. ? Any views expressed in this message are those of the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ole0.bmp Type: image/bmp Size: 62302 bytes Desc: Picture (Device Independent Bitmap) URL: From alan.gauld at btinternet.com Mon Mar 7 19:26:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Mar 2011 18:26:15 -0000 Subject: [Tutor] ctypes question References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> Message-ID: "Pacific Morrowind" wrote > but that path doesn't actually exist... replace that path with > either > r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise > the > /t will be transformed into a tab. You've got your / and \ mixed up. Forward slashes (/) are fine in Windows paths. It's back slashes(\) that need escaping or raw stringing. \t is tab... On the original ask - could it be a permissions issue? Does your app have acess to the file? Alan G. From waynejwerner at gmail.com Mon Mar 7 20:07:03 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 7 Mar 2011 13:07:03 -0600 Subject: [Tutor] Running scripts/tkinter In-Reply-To: References: Message-ID: On Mon, Mar 7, 2011 at 5:03 AM, IOAN Alexandru < alexandru.ioan at eurocontrol.int> wrote: > On windows XP pro. Ver. 2002 SP 3. I get the following: > > [image: Picture (Device Independent Bitmap)] > > The same is for Python27. > Please help me with some ideas. > Did you try reinstalling Python, like it suggests? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ole0.bmp Type: image/bmp Size: 62302 bytes Desc: not available URL: From eire1130 at gmail.com Mon Mar 7 22:17:13 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 7 Mar 2011 16:17:13 -0500 Subject: [Tutor] Running scripts/tkinter In-Reply-To: References: Message-ID: On Mon, Mar 7, 2011 at 6:03 AM, IOAN Alexandru < alexandru.ioan at eurocontrol.int> wrote: > On windows XP pro. Ver. 2002 SP 3. I get the following: > > [image: Picture (Device Independent Bitmap)] > > The same is for Python27. > Please help me with some ideas. > Tks. > > ____ > > > > This message and any files transmitted with it are legally privileged and > intended for the sole use of the individual(s) or entity to whom they are > addressed. If you are not the intended recipient, please notify the sender > by reply and delete the message and any attachments from your system. Any > unauthorised use or disclosure of the content of this message is strictly > prohibited and may be unlawful. > > > > Nothing in this e-mail message amounts to a contractual or legal commitment > on the part of EUROCONTROL, unless it is confirmed by appropriately signed > hard copy. > > > > Any views expressed in this message are those of the sender. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I believe this might have to do with adding Python, in this case C:\python32, to you PATH environment variables. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ole0.bmp Type: image/bmp Size: 62302 bytes Desc: not available URL: From steve at pearwood.info Mon Mar 7 22:44:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Mar 2011 08:44:36 +1100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: <4D74DD98.1020908@googlemail.com> References: <4D74DD98.1020908@googlemail.com> Message-ID: <201103080844.37036.steve@pearwood.info> On Tue, 8 Mar 2011 12:28:56 am Knacktus wrote: > Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi: > > Hello, > > > > I am thinking of implementing a BLAS package in pure python. I am > > wondering if this is a good idea. Sure, why not? Even if nobody uses it, it looks good on a resume and you will hopefully learn a lot. > I don't think so. Usually people write extensions to the CPython > implementation (when talking about performance, we need to talk about > Python implementations like CPython, Jython or PyPy) in C to do high > performance stuff. Pure CPython is (depeneding on the problem) > magnitudes slower than C. Typical pure Python code is between 10 and 100 times slower than C, but talking about implementations, it is the aim of the PyPy project to use Just In Time compilation and clever optimizations to meet *and exceed* the speed of static C compilers. In just a few years, with a handful of people working on it, and a tiny grant from the EU, they have already doubled the speed of CPython. If PyPy could get *half* the love and attention that CPython gets, who knows what they could accomplish? (If only Google had thrown some work into PyPy, instead of wasting time with Unladen Swallow that never went anywhere useful...) But the beauty of Python is that if a piece of code is too slow, you can rip it out into an extension written in C or Fortran while keeping the rest of the library in Python. See, for example, the re module, which has a front end written in Python and the regex engine in C. The itertools module is another good example. Using a few primitives written in C, itertools allows Python code to run efficiently and quickly. > Also, there's NumPy SciPy. Check those out. > > More comments below ... > > My design goals are: > > [1] Efficient manipulation of Matrices and > > Vectors using pure python objects and > > python code. > > No, not efficient in terms of performance. How do you know how efficient his code will be before he's even written it? [...] > The future of High Performance Python is probably PyPy. Exactly why a pure-Python library *may* be useful. Today it will be slow, running under CPython, but in five (unlikely) or ten years (possibly), it may be fast, running under PyPy. Or not. Who can tell what the future will bring? -- Steven D'Aprano From tktucker at gmail.com Mon Mar 7 22:49:12 2011 From: tktucker at gmail.com (Tom Tucker) Date: Mon, 7 Mar 2011 16:49:12 -0500 Subject: [Tutor] Init Script (RHEL 5 Linux) Message-ID: Hello. I am trying implement a *one time* execution of an init script. Any recommendation on how to fork or detach this script from the normal init 3 execution process so that it doesn't hold up other activities? Thanks Here is the high level logic. 1. Execute script 1. perform these activities 2. Check network connectivity 1. If connectivity: perform these activities 1. Delete init script os.remove(sys.argv[0]) 2. If no connectivity: - Sleep 15 seconds - Check connectivity again -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 7 23:15:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Mar 2011 09:15:47 +1100 Subject: [Tutor] Init Script (RHEL 5 Linux) In-Reply-To: References: Message-ID: <201103080915.47662.steve@pearwood.info> On Tue, 8 Mar 2011 08:49:12 am Tom Tucker wrote: > Hello. I am trying implement a *one time* execution of an init > script. Any recommendation on how to fork or detach this > script from the normal init 3 execution process so that it doesn't > hold up other activities? This mailing list is for beginners learning Python the language. While we're happy to help, chances are that most people here won't be able to answer your question. You may have better luck with the main Python mailing list, python-list at python.org, also available as a news group, comp.lang.python. But having said that, my guess would be to look at the subprocess module and see if that will do what you are hoping for. -- Steven D'Aprano From steve at pearwood.info Mon Mar 7 23:33:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 Mar 2011 09:33:06 +1100 Subject: [Tutor] help with re module and parsing data In-Reply-To: <4D748F36.1000006@gmail.com> References: <4D748F36.1000006@gmail.com> Message-ID: <201103080933.07192.steve@pearwood.info> On Mon, 7 Mar 2011 06:54:30 pm vineeth wrote: > Hello all I am doing some analysis on my trace file. I am finding the > lines Recvd-Content and Published-Content. I am able to find those > lines but the re module as predicted just gives the word that is > being searched. But I require the entire line similar to a grep in > unix. Can some one tell me how to do this. I am doing the following > way. If you want to match *lines*, then you need to process each line individually, not the whole file at once. Something like this: for line in open('file.txt'): if "Recvd-Content" in line or "Published-Content" in line: process_match(line) A simple substring test should be enough, that will be *really* fast. But if you need a more heavy-duty test, you can use a regex, but remember that regexes are usually slow. pattern = 'whatever...' for line in open('file.txt'): if re.search(pattern, line): process_match(line) Some further comments below: > import re > file = open('file.txt','r') > file2 = open('newfile.txt','w') > > LineFile = ' ' Why do you initialise "LineFile" to a single space, instead of the empty string? > for line in file: > LineFile += line Don't do that! Seriously, that is completely the wrong way. What this does is something like this: Set LineFile to " ". Read one line from the file. Make a copy of LineFile plus line 1. Assign that new string to LineFile. Delete the old contents of LineFile. Read the second line from the file. Make a copy of LineFile plus line 2. Assign that new string to LineFile. Delete the old contents of LineFile. Read the third line from the file. Make a copy of LineFile plus line 3. and so on... Can you see how much copying of data is being done? If there are 1000 lines in the file, the first line gets copied 1000 times, the second line 999 times, the third 998 times... See this essay for more about why this is s-l-o-w: http://www.joelonsoftware.com/articles/fog0000000319.html Now, it turns out that *some* versions of Python have a clever optimization which, *sometimes*, can speed that up. But you shouldn't rely on it. The better way to add many strings is: accumulator = [] for s in some_strings: accumulator.append(s) result = ''.join(accumulator) But in your case, when reading from a file, an even better way is to just read from the file in one chunk! LineFile = open('file.txt','r').read() -- Steven D'Aprano From jrhorn424 at gmail.com Tue Mar 8 02:28:38 2011 From: jrhorn424 at gmail.com (Jeff Horn) Date: Mon, 7 Mar 2011 20:28:38 -0500 Subject: [Tutor] [RFI] Resources for graphic modeling of dynamic systems Message-ID: Hi tutors! I have a very basic understanding of Python, and have played a bit with SymPy. I'd like to use Python to accomplish many of the same things that are done in Mathematica. Right now, I have a project that could benefit from a dynamic model. I envision defining a series of differential equations that describe a model, complete with manipulable parameters. I think I'd use a Python script to define the model and graph it with gnuplot or a similar tool. However, I have no idea about where to start building an interface with sliders to manipulate parameters graphically. Would any of you recommend particular resources? Perhaps this would necessitate becoming a nascent UI programmer, which is something I'd like to avoid as much as possible. For general examples of what I'm looking to produce, see: http://demonstrations.wolfram.com/ More specifically, I want to produce a model very much like the one here: http://demonstrations.wolfram.com/SolowGrowthModel/ -- Jeffrey Horn http://www.failuretorefrain.com/jeff/ From waynejwerner at gmail.com Tue Mar 8 03:16:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 7 Mar 2011 20:16:11 -0600 Subject: [Tutor] [RFI] Resources for graphic modeling of dynamic systems In-Reply-To: References: Message-ID: On Mon, Mar 7, 2011 at 7:28 PM, Jeff Horn wrote: > Hi tutors! > > I have a very basic understanding of Python, and have played a bit > with SymPy. I'd like to use Python to accomplish many of the same > things that are done in Mathematica. > > Right now, I have a project that could benefit from a dynamic model. I > envision defining a series of differential equations that describe a > model, complete with manipulable parameters. I think I'd use a Python > script to define the model and graph it with gnuplot or a similar > tool. However, I have no idea about where to start building an > interface with sliders to manipulate parameters graphically. > > Would any of you recommend particular resources? > > Perhaps this would necessitate becoming a nascent UI programmer, which > is something I'd like to avoid as much as possible. > > For general examples of what I'm looking to produce, see: > > http://demonstrations.wolfram.com/ > > More specifically, I want to produce a model very much like the one here: > > http://demonstrations.wolfram.com/SolowGrowthModel/ If you're interested in scientific programming, I would highly recommend the Python(X, Y) package available here: http://www.pythonxy.com/ It has a variety of tools to help you do as little GUI programming as possible. It also comes with the inestimable Matplotlib that is incredibly useful for drawing graphs like the ones you suggest. Although apparently you don't even need to worry about a GUI when you can just use matplotlib itself: http://matplotlib.sourceforge.net/users/screenshots.html#slider-demo HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.serrato at gmail.com Tue Mar 8 05:40:24 2011 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Mon, 7 Mar 2011 22:40:24 -0600 Subject: [Tutor] Does try-except "lock out scope" or similar? Message-ID: I wrote a short script to clean up a csv file but had trouble when date_time = time.strptime(date_string, "%m/%d/%y") would choke on intermittent Null characters in the file. I put it into a try-except, but then I found I couldn't do del row because I receive a "row is not defined" complaint or similar. So, how do I run time.strptime() without locking myself out. And, what is the pretty way to do all of this, because a couple hours later it looks pretty ugly. I mean it turns out I'm rewriting the file anyway so no need to delete the row. http://pastebin.ws/e0prlj Regards, Benjamin Serrato 682.472.8650 -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Tue Mar 8 05:52:51 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 08 Mar 2011 05:52:51 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: <201103080844.37036.steve@pearwood.info> References: <4D74DD98.1020908@googlemail.com> <201103080844.37036.steve@pearwood.info> Message-ID: <4D75B623.1020506@googlemail.com> Am 07.03.2011 22:44, schrieb Steven D'Aprano: > On Tue, 8 Mar 2011 12:28:56 am Knacktus wrote: >> Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi: >>> Hello, >>> >>> I am thinking of implementing a BLAS package in pure python. I am >>> wondering if this is a good idea. > > Sure, why not? Even if nobody uses it, it looks good on a resume and you > will hopefully learn a lot. > > >> I don't think so. Usually people write extensions to the CPython >> implementation (when talking about performance, we need to talk about >> Python implementations like CPython, Jython or PyPy) in C to do high >> performance stuff. Pure CPython is (depeneding on the problem) >> magnitudes slower than C. > > Typical pure Python code is between 10 and 100 times slower than C, but > talking about implementations, it is the aim of the PyPy project to use > Just In Time compilation and clever optimizations to meet *and exceed* > the speed of static C compilers. In just a few years, with a handful of > people working on it, and a tiny grant from the EU, they have already > doubled the speed of CPython. If PyPy could get *half* the love and > attention that CPython gets, who knows what they could accomplish? > > (If only Google had thrown some work into PyPy, instead of wasting time > with Unladen Swallow that never went anywhere useful...) > > But the beauty of Python is that if a piece of code is too slow, you can > rip it out into an extension written in C or Fortran while keeping the > rest of the library in Python. See, for example, the re module, which > has a front end written in Python and the regex engine in C. > > The itertools module is another good example. Using a few primitives > written in C, itertools allows Python code to run efficiently and > quickly. > > >> Also, there's NumPy SciPy. Check those out. >> >> More comments below ... >> >> My design goals are: >>> [1] Efficient manipulation of Matrices and >>> Vectors using pure python objects and >>> python code. >> >> No, not efficient in terms of performance. > > How do you know how efficient his code will be before he's even written > it? He doesn't have to write it, as it is very obvious, that no Python code on earth (even written by Guido himself ;-)) stands a chance compared to Fortran or C. Look at this: http://shootout.alioth.debian.org/u32/performance.php?test=spectralnorm CPython implementation runs 12 mins compared to 8 secs of a Fortran implementation. PyPy is about 100 secs, which is remarkable but still far off. > > [...] >> The future of High Performance Python is probably PyPy. > > Exactly why a pure-Python library *may* be useful. Today it will be > slow, running under CPython, but in five (unlikely) or ten years > (possibly), it may be fast, running under PyPy. > > Or not. Who can tell what the future will bring? > > From andreengels at gmail.com Tue Mar 8 07:22:56 2011 From: andreengels at gmail.com (Andre Engels) Date: Tue, 8 Mar 2011 07:22:56 +0100 Subject: [Tutor] Does try-except "lock out scope" or similar? In-Reply-To: References: Message-ID: On Tue, Mar 8, 2011 at 5:40 AM, Benjamin Serrato wrote: > I wrote a short script to clean up a csv file but had trouble when > date_time = time.strptime(date_string, "%m/%d/%y") > ?would choke on intermittent Null characters in the file. ?I put it into a > try-except, but then I found I couldn't do > del row > because I receive a "row is not defined" complaint or similar. ?So, how do I > run time.strptime() without locking myself out. And, what is the pretty way > to do all of this, because a couple hours later it looks pretty ugly. I mean > it turns out I'm rewriting the file anyway so no need to delete the row. > http://pastebin.ws/e0prlj > Regards, > Benjamin Serrato > 682.472.8650 To see the problem with your code, think about the following: Suppose that you go into the 'except' branch. What is the program going to do _after_ the code in the except branch has been run? The code will go on with the part after the try...except, and there will 'need' the variable row again. You will have to add 'continue' to the except, or put the code below it in an 'else'. Another issue I see is the 'del row' code itself - it has no real function, you are deleting something that will be deleted on the next execution step anyway. -- Andr? Engels, andreengels at gmail.com From ladymcse2000 at gmail.com Tue Mar 8 07:44:31 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Mon, 7 Mar 2011 22:44:31 -0800 Subject: [Tutor] Expanding a variable with subprocess on Windows Message-ID: I'm working on a Windows machine and want to use subprocess to run several commands from the command line. Normally with bat files or some of the other scripting languages on Windows, I would set up a variable with the path to the command like so: gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' Then call the command the variable to avoid typing in the full path. When I do this with subprocess it works: subprocess.Popen('c:/program files (x86)/gnu/gnupg/gpg2.exe', shell=True) However when I do this: gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' subprocess.Popen('gpg', shell=True) It fails to run gpg and is not expanding the variable. Is there a way to do this that I'm missing? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue Mar 8 08:38:17 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 08 Mar 2011 08:38:17 +0100 Subject: [Tutor] Expanding a variable with subprocess on Windows In-Reply-To: References: Message-ID: <1299569897.11911.5.camel@Nokia-N900> On Tue,? 8 Mar 2011, 07:44:31 CET, Becky Mcquilling wrote: > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > > subprocess.Popen('gpg', shell=True) > > It fails to run gpg and is not expanding the variable.? Is there a way > to do this that I'm missing? What you are doing is running Popen with a string 'gpg' instead of the variable gpg. The below should do the trick. subprocess.Popen(gpg, shell=True) # notice no single quotes Also you usually do not need a shell and I expect your use case runs fine without it. Greets sander -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladymcse2000 at gmail.com Tue Mar 8 09:15:57 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Tue, 8 Mar 2011 00:15:57 -0800 Subject: [Tutor] Expanding a variable with subprocess on Windows In-Reply-To: <1299569897.11911.5.camel@Nokia-N900> References: <1299569897.11911.5.camel@Nokia-N900> Message-ID: Thanks, Sander. That was simple enough, as I'm learning I sometimes get caught up in these all too silly mistakes. Becky On Mon, Mar 7, 2011 at 11:38 PM, Sander Sweers wrote: > On Tue, 8 Mar 2011, 07:44:31 CET, Becky Mcquilling < > ladymcse2000 at gmail.com> wrote: > > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > > gpg = 'c:/program files (x86)/gnu/gnupg/gpg2.exe' > > > > subprocess.Popen('gpg', shell=True) > > > > It fails to run gpg and is not expanding the variable. Is there a way > > to do this that I'm missing? > > What you are doing is running Popen with a string 'gpg' instead of the > variable gpg. The below should do the trick. > > subprocess.Popen(gpg, shell=True) # notice no single quotes > > Also you usually do not need a shell and I expect your use case runs fine > without it. > > Greets > sander > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 8 09:51:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2011 08:51:18 -0000 Subject: [Tutor] BLAS Implementation on Python References: <4D74DD98.1020908@googlemail.com><201103080844.37036.steve@pearwood.info> <4D75B623.1020506@googlemail.com> Message-ID: "Knacktus" wrote > He doesn't have to write it, as it is very obvious, that no Python > code on earth (even written by Guido himself ;-)) stands a chance > compared to Fortran or C. Look at this: There is one big proviso. The C or Fortran needs to be well written in the first place. It's quite possible to write code in Python that outperforms badly written C. And it is quite easy to write bad C! This is similar to the arguments in the 1960's/70's when languages like C first appeared. The assembler programmers all said you'd never replace assembler with C because assembler was an order of magnitude faster (and smaller because size mattered then!). But that was only true of well optimised assembler. Nowadays speed is hardly ever used as a reason for using assembler. Now the case between interpreted and compiled languages is slightly different, but as python compilers emerge the gap will continue to narrow. Will Python ever challenge C/assembler? Probably not in the low level domain but where we are talking about implementing complex algorithms it may well do. But its a long way off just now and if you need speed selectively rewriting in C is still the best bet. The skill is in selecting the bits to optimise. But a pure Python implementation will benefit from any improvements that are made going forward without significant rework. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Tue Mar 8 10:00:33 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 8 Mar 2011 01:00:33 -0800 (PST) Subject: [Tutor] ctypes question In-Reply-To: References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> Message-ID: <360962.43219.qm@web110704.mail.gq1.yahoo.com> Hi all, Thanks for your replies. It wasn't a permissions issue. Apparently, not the full path name should be used. When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? That's consistent with os.getcwd()) and then use the file name only, it works. See the Idle session below. Thought it'd be nice to share this with you. Best wishes, Albert-Jan Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2.4 >>> import ctypes >>> lib = ctypes.cdll.LoadLibrary("d:/temp/spss_io/win32/spssio32.dll") Traceback (most recent call last): File "", line 1, in lib = ctypes.cdll.LoadLibrary("d:/temp/spss_io/win32/spssio32.dll") File "C:\Python25\lib\ctypes\__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "C:\Python25\lib\ctypes\__init__.py", line 348, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Error 126] Kan opgegeven module niet vinden >>> import os >>> os.path.exists("d:/temp/spss_io/win32/spssio32.dll") True >>> os.chdir("d:/temp/spss_io/win32") >>> lib = ctypes.cdll.LoadLibrary("spssio32.dll") >>> dir(lib) ['_FuncPtr', '__class__', '__delattr__', '__dict__', '__doc__', '__getattr__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_handle', '_name'] >>> Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Alan Gauld To: tutor at python.org Sent: Mon, March 7, 2011 7:26:15 PM Subject: Re: [Tutor] ctypes question "Pacific Morrowind" wrote > but that path doesn't actually exist... replace that path with either > r"d:/temp/spssio32.dll" or with "d://temp//spssio32.dll"; otherwise the > /t will be transformed into a tab. You've got your / and \ mixed up. Forward slashes (/) are fine in Windows paths. It's back slashes(\) that need escaping or raw stringing. \t is tab... On the original ask - could it be a permissions issue? Does your app have acess to the file? Alan G. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 8 10:09:45 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 8 Mar 2011 09:09:45 +0000 (GMT) Subject: [Tutor] ctypes question In-Reply-To: <360962.43219.qm@web110704.mail.gq1.yahoo.com> References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> <360962.43219.qm@web110704.mail.gq1.yahoo.com> Message-ID: <4058.5066.qm@web86705.mail.ird.yahoo.com> > When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? > That's consistent with os.getcwd()) History. They are Unix commands (and possibly Multics/PDP before that!). cd has been the command in almost every CLI OS I've ever used from CP/M thru' OS/9, Unix, DOS, etc... The only exceptions being VAX/VMS(uses 'set def') and OS/390 on a mainframe which doesn't use a directory based file system. That doesn't mean Python shouldn't adopt a more consistent naming scheme it's just that the folks building it simply transferred the names of the commands that they were familiar with. Its a self perpetuating habit... :-) Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Mar 8 11:11:09 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 08 Mar 2011 11:11:09 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: References: <4D74DD98.1020908@googlemail.com><201103080844.37036.steve@pearwood.info> <4D75B623.1020506@googlemail.com> Message-ID: Alan Gauld, 08.03.2011 09:51: > "Knacktus" wrote > >> He doesn't have to write it, as it is very obvious, that no Python code >> on earth (even written by Guido himself ;-)) stands a chance compared to >> Fortran or C. Look at this: > > There is one big proviso. The C or Fortran needs to be well written > in the first place. It's quite possible to write code in Python that > outperforms badly written C. And it is quite easy to write bad C! It's seriously hard to write computational Python code that is faster than C code, though. It shifts a bit if you can take advantage of Python's dynamic container types, especially dicts, but that's rarely the case for mathematic computation code, which would usually deploy NumPy etc. in Python. Writing that in pure Python is bound to be incredibly slow, and likely still several hundred times slower than even a simple approach in C. There's a reason people use NumPy, C, Fortran and Cython for these things. Remember that the OP's topic was a BLAS implementation. The BLAS libraries are incredibly well optimised for all sorts of platforms, including GPUs. They are building blocks that C programmers can basically just plug into their code to run hugely fast computations. There is no way Python code will ever be able to get any close to that. Stefan From robert.clement at ed.ac.uk Tue Mar 8 11:25:32 2011 From: robert.clement at ed.ac.uk (Robert Clement) Date: Tue, 08 Mar 2011 10:25:32 +0000 Subject: [Tutor] binary string parsing Message-ID: <4D76041C.80503@ed.ac.uk> Hi I am receiving a string over a socket connection. The string may be either line and value delimited ascii, or formated binary. The skeleton of the code which handles the data is: buffer = socket.recv(1000) lines = buffer.split(linedelim) for line in lines: if datatype == 'binary': if len(line) == binaryrecordsize: values = unpack(formatin,line) else: print('error') else: values = line.split(signaldelim) My problem arises when handling data which may be either big or little endian. The endianess is handled properly when unpacking each line of data from the buffer but I was not sure how to handle the process if splitting the buffer into individual lines using the line delimiter. The problem was first encountered when unpacking a formated binary buffer which had \xBA\xBA as the line delimiter. The above code worked fine most of the time but occasionally an \xBA would crop up as the last byte of the line becasue the byte order was different than the default assumed for the buffer. Thanks Robert Clement -- 202 Crew Building West Mains Road Edinburgh UK, EH9 3JN phone +44 131 650 7732 The University of Edinburgh is a charitable body, registered in Scotland, with registration number SC005336. From joel.goldstick at gmail.com Tue Mar 8 12:14:45 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 8 Mar 2011 06:14:45 -0500 Subject: [Tutor] ctypes question In-Reply-To: <4058.5066.qm@web86705.mail.ird.yahoo.com> References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> <360962.43219.qm@web110704.mail.gq1.yahoo.com> <4058.5066.qm@web86705.mail.ird.yahoo.com> Message-ID: On Tue, Mar 8, 2011 at 4:09 AM, ALAN GAULD wrote: > > When I use os.chdir (by the way: why on earth isn't this called > os.setcwd()?? > > That's consistent with os.getcwd()) > > History. > They are Unix commands (and possibly Multics/PDP before that!). > cd has been the command in almost every CLI OS I've ever used from > CP/M thru' OS/9, Unix, DOS, etc... > > The only exceptions being VAX/VMS(uses 'set def') and OS/390 on > a mainframe which doesn't use a directory based file system. > > That doesn't mean Python shouldn't adopt a more consistent naming > scheme it's just that the folks building it simply transferred the names > of the commands that they were familiar with. Its a self perpetuating > habit... :-) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I'm glad to see you got the result you wanted. But, by moving your current working directory to the library's directory seems like it could cause other problems with the code. I don't do python on windows, and have unremembered a lot I used to know about windows. So, my question is, isn't there another way to do this? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Mar 8 13:23:20 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 8 Mar 2011 04:23:20 -0800 (PST) Subject: [Tutor] ctypes question In-Reply-To: References: <156862.38339.qm@web110711.mail.gq1.yahoo.com> <4D74FB94.8090303@gmail.com> <360962.43219.qm@web110704.mail.gq1.yahoo.com> <4058.5066.qm@web86705.mail.ird.yahoo.com> Message-ID: <484915.6005.qm@web110701.mail.gq1.yahoo.com> Hi Joel, I found this on stackoverflow*) os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH'] windll.LoadLibrary('mydll.dll') It extends the directory list of the environment variable 'path'. Now at least I've loaded the dll, but I still need to read up on ctypes an file handles. Any good pointers (no pun intended ;-) are welcome! *) http://stackoverflow.com/questions/2980479/python-ctypes-loading-dll-from-from-a-relative-path Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Joel Goldstick To: tutor at python.org Sent: Tue, March 8, 2011 12:14:45 PM Subject: Re: [Tutor] ctypes question On Tue, Mar 8, 2011 at 4:09 AM, ALAN GAULD wrote: > When I use os.chdir (by the way: why on earth isn't this called os.setcwd()?? >> That's consistent with os.getcwd()) > >History. >They are Unix commands (and possibly Multics/PDP before that!). >cd has been the command in almost every CLI OS I've ever used from >CP/M thru' OS/9, Unix, DOS, etc... > >The only exceptions being VAX/VMS(uses 'set def') and OS/390 on >a mainframe which doesn't use a directory based file system. > >That doesn't mean Python shouldn't adopt a more consistent naming >scheme it's just that the folks building it simply transferred the names >of the commands that they were familiar with. Its a self perpetuating >habit... :-) > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > I'm glad to see you got the result you wanted. But, by moving your current working directory to the library's directory seems like it could cause other problems with the code. I don't do python on windows, and have unremembered a lot I used to know about windows. So, my question is, isn't there another way to do this? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From vick1975 at intnet.mu Tue Mar 8 19:38:35 2011 From: vick1975 at intnet.mu (Vickram) Date: Tue, 8 Mar 2011 22:38:35 +0400 Subject: [Tutor] help Message-ID: <53E18B137A2543E6A79361DA917C6BDC@private> Hello I need help in translating a C++ code into python.. Can you help please? Please find attached the two codes. The python result is wrong because I may have misread the C++ code Thanks Vickram -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: testcosmo.py URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 8 20:00:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2011 19:00:55 -0000 Subject: [Tutor] BLAS Implementation on Python References: <4D74DD98.1020908@googlemail.com><201103080844.37036.steve@pearwood.info> <4D75B623.1020506@googlemail.com> Message-ID: "Stefan Behnel" wrote >>> He doesn't have to write it, as it is very obvious, that no Python >>> code >>> on earth (even written by Guido himself ;-)) stands a chance >>> compared to >>> Fortran or C. Look at this: >> >> There is one big proviso. The C or Fortran needs to be well written > > It's seriously hard to write computational Python code that is > faster than C code, though. Agreed, it was the assertion that "no Python code on earth...stands a chance..." that I was objecting to. There are many areas where the C code would have to be pathologically bad to be beaten by Python, but there are plenty of places where only slightly inefficient C code can be competitive relatie to Python. Alan G. From enalicho at gmail.com Tue Mar 8 20:50:14 2011 From: enalicho at gmail.com (Noah Hall) Date: Tue, 8 Mar 2011 19:50:14 +0000 Subject: [Tutor] help In-Reply-To: <53E18B137A2543E6A79361DA917C6BDC@private> References: <53E18B137A2543E6A79361DA917C6BDC@private> Message-ID: On Tue, Mar 8, 2011 at 6:38 PM, Vickram wrote: > The python result is wrong because I may have misread the C++ code Well, really, I suggest you read a tutorial on Python - you don't seem to be getting a hang on the basics, for example, there's no need for to use the float() function. From smokefloat at gmail.com Tue Mar 8 21:14:58 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Mar 2011 15:14:58 -0500 Subject: [Tutor] help In-Reply-To: References: <53E18B137A2543E6A79361DA917C6BDC@private> Message-ID: The first hundred pages of a thorough python tutorial, and a c++ tutorial should have you doing both of those quite well in a day or so. From knacktus at googlemail.com Tue Mar 8 21:19:47 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 08 Mar 2011 21:19:47 +0100 Subject: [Tutor] BLAS Implementation on Python In-Reply-To: References: <4D74DD98.1020908@googlemail.com><201103080844.37036.steve@pearwood.info> <4D75B623.1020506@googlemail.com> Message-ID: <4D768F63.7040201@googlemail.com> Am 08.03.2011 20:00, schrieb Alan Gauld: > > "Stefan Behnel" wrote >>>> He doesn't have to write it, as it is very obvious, that no Python code >>>> on earth (even written by Guido himself ;-)) stands a chance >>>> compared to >>>> Fortran or C. Look at this: >>> >>> There is one big proviso. The C or Fortran needs to be well written >> >> It's seriously hard to write computational Python code that is faster >> than C code, though. > > Agreed, it was the assertion that "no Python code on earth...stands > a chance..." that I was objecting to. > > There are many areas where the C code would have to be pathologically > bad to be beaten by Python, but there are plenty of places where only > slightly inefficient C code can be competitive relatie to Python. Maybe there're those areas, but the top posters question is about reimplementing BLAS, which is a highly optimized package for linear algebra. And in this area no pure Python code on earth on any currently available Python implementation stands a chance performance wise to one of the C or Fortran implementations. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Mar 9 00:14:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Mar 2011 23:14:11 -0000 Subject: [Tutor] help References: <53E18B137A2543E6A79361DA917C6BDC@private> Message-ID: "Vickram" wrote > I need help in translating a C++ code into python.. > Can you help please? > > The python result is wrong because I may have misread the C++ code The C++ code is really just C code, there is virtualy no C++ stuff there. But that aside your translation is pretty faithful (too faithful with all those float() conversions). When you say it is "wrong" what exactly do you mean? You get different values as output? By how much? It looks like you need to do a detailed step by step walk through of the code and see if you have missed an operator or polarity or maybe have an off-by-one error in a loop. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nookasree at yahoo.com Wed Mar 9 09:21:09 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Wed, 9 Mar 2011 00:21:09 -0800 (PST) Subject: [Tutor] Need help with dates in Python Message-ID: <837397.42866.qm@web65410.mail.ac4.yahoo.com> Hi, I need help in finding the minimum date and maximum date in a file. Here is my test file: s.no: dt1 amt id1 id2 452 2010-02-20 $23.26 059542 06107 452 2010-02-05 $20.78 059542 06107 451 2010-02-24 $5.99 059542 20151 452 2010-02-12 $114.25 839745 98101 452 2010-02-06 $28.00 839745 06032 451 2010-02-12 $57.00 839745 06269 I want to get the minimum and maximum dt1 for each id1 Required result: id1 mindate maxdate 059542 2010-02-24 2010-02-20 839745 2010-02-06 2010-02-12 Code: The code I tried. It doesn't work though. import sys import os t = () tot = [] maxyr = 2012 minyr = 2008 maxday = 31 minday = 1 maxmon = 12 minmon = 1 for line in open ('test2.txt','r'): data = line.rstrip().split() a = data[3] b = data[1] (year, month, day) = b.split('-') year = int(year) month = int(month) day = int(day) if year > maxyr: maxyr = year elif year < minyr: minyr = year if month > maxmon: maxmon = month elif month < minmon: minmon = month if day > maxday: maxday = day elif day < minday: minday = day max = (maxyr,maxmon,maxday) min = (minyr,minmon,minday) t = (a,b,max,min) tot.append(t) print t Could you pls. help me with this. Thanks Sree. From izzaddin.ruhulessin at gmail.com Wed Mar 9 09:29:03 2011 From: izzaddin.ruhulessin at gmail.com (C.Y. Ruhulessin) Date: Wed, 9 Mar 2011 09:29:03 +0100 Subject: [Tutor] Need help with dates in Python In-Reply-To: <837397.42866.qm@web65410.mail.ac4.yahoo.com> References: <837397.42866.qm@web65410.mail.ac4.yahoo.com> Message-ID: import datetime min = datetime.date(2008, 1, 1) max = datetime.date(2012, 12, 31) file = open ('test2.txt','r') line = file.readline()[-1] while line: # your code 2011/3/9 nookasree ponamala > Hi, > > I need help in finding the minimum date and maximum date in a file. > Here is my test file: > s.no: dt1 amt id1 id2 > 452 2010-02-20 $23.26 059542 06107 > 452 2010-02-05 $20.78 059542 06107 > 451 2010-02-24 $5.99 059542 20151 > 452 2010-02-12 $114.25 839745 98101 > 452 2010-02-06 $28.00 839745 06032 > 451 2010-02-12 $57.00 839745 06269 > > I want to get the minimum and maximum dt1 for each id1 > > Required result: > > id1 mindate maxdate > 059542 2010-02-24 2010-02-20 > 839745 2010-02-06 2010-02-12 > > Code: The code I tried. It doesn't work though. > > import sys > import os > t = () > tot = [] > maxyr = 2012 > minyr = 2008 > maxday = 31 > minday = 1 > maxmon = 12 > minmon = 1 > > for line in open ('test2.txt','r'): > data = line.rstrip().split() > a = data[3] > b = data[1] > (year, month, day) = b.split('-') > year = int(year) > month = int(month) > day = int(day) > if year > maxyr: > maxyr = year > elif year < minyr: > minyr = year > if month > maxmon: > maxmon = month > elif month < minmon: > minmon = month > if day > maxday: > maxday = day > elif day < minday: > minday = day > max = (maxyr,maxmon,maxday) > min = (minyr,minmon,minday) > t = (a,b,max,min) > tot.append(t) > print t > > Could you pls. help me with this. > > Thanks > Sree. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed Mar 9 09:46:13 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 9 Mar 2011 09:46:13 +0100 Subject: [Tutor] Need help with dates in Python In-Reply-To: <837397.42866.qm@web65410.mail.ac4.yahoo.com> References: <837397.42866.qm@web65410.mail.ac4.yahoo.com> Message-ID: On Wed, Mar 9, 2011 at 9:21 AM, nookasree ponamala wrote: > Hi, > > I need help in finding the minimum date and maximum date in a file. > Here is my test file: > s.no: ? dt1 ? ? amt ? ? id1 ? ? id2 > 452 ? ? 2010-02-20 ? ? ?$23.26 ? ? ?059542 ? ? ? ?06107 > 452 ? ? 2010-02-05 ? ? ?$20.78 ? ? ?059542 ? ? ? ?06107 > 451 ? ? 2010-02-24 ? ? ?$5.99 ? ? ? 059542 ? ? ? ?20151 > 452 ? ? 2010-02-12 ? ? ?$114.25 ? ? 839745 ? ? ? ?98101 > 452 ? ? 2010-02-06 ? ? ?$28.00 ? ? ?839745 ? ? ? ?06032 > 451 ? ? 2010-02-12 ? ? ?$57.00 ? ? ?839745 ? ? ? ?06269 > > I want to get the minimum and maximum dt1 for each id1 > > Required result: > > id1 mindate maxdate > 059542 ?2010-02-24 ? ? ?2010-02-20 > 839745 ?2010-02-06 ? ? ?2010-02-12 > > Code: The code I tried. It doesn't work though. > > import sys > import os > t = () > tot = [] > maxyr = 2012 > minyr = 2008 > maxday = 31 > minday = 1 > maxmon = 12 > minmon = 1 > > for line in open ('test2.txt','r'): > ? ? ? ?data = line.rstrip().split() > ? ? ? ?a = data[3] > ? ? ? ?b = data[1] > ? ? ? ?(year, month, day) = b.split('-') > ? ? ? ?year = int(year) > ? ? ? ?month = int(month) > ? ? ? ?day = int(day) > if year > maxyr: > ? ? ? ?maxyr = year > elif year < minyr: > ? ? ? ?minyr = year > if month > maxmon: > ? ? ? ?maxmon = month > ? ? ? ?elif month < minmon: > ? ? ? ?minmon = month > ? ? ? ?if day > maxday: > ? ? ? ?maxday = day > ? ? ? ?elif day < minday: > ? ? ? ?minday = day > ? ? ? ?max = (maxyr,maxmon,maxday) > ? ? ? ?min = (minyr,minmon,minday) > ? ? ? ?t = (a,b,max,min) > ? ? ? ?tot.append(t) > ? ? ? ?print t > > Could you pls. help me with this. I see several things go wrong. Here a list, which may well not be complete: * You want the mindate and maxdate for each id1, but you remember only a single minyr, maxyr etcetera. There's no way that that is going to work. * You initialize minyr etcetera to a date before the first date you will see, nd maxyr etcetera to a date after the last date. This means that you will never find an earlier respectively later one, so they would never be changed. You should do it exactly the other way around - minyr etcetera should be _later_ than any date that may occur, maxyr etcetera _earlier_. * You move "if year > maxyr" back to the left. This means that it is not part of the loop, but is executed (only) once _after_ the loop has been gone through * year < minyear should be "if", not "elif": it is possible that the new date is both the first _and_ the last date that has been found (this will be the case with the first date) * You change maxyear, maxmonth and maxday independently. That is not what you are trying to do - you want the last date, not the highest year, highest month and highest day (if the dates were 2001-12-01, 2011-11-03 and 2005-05-30, you want the maximum date to be 2011-11-03, not 2011-12-30). You should thus find a way to compare the *complete date* and then if it is later than the maxdate or earlier than the mindate change the *complete date* * At the end you show (well, in this case you don't because it is under "if month > maxmon") a quadruple consisting of id1, current date, lowest date and highest date - EACH time. You want only the triple and only after the last date of some value of id1 has been parsed (best to do that after all lines have been parsed) * The code as shown will lead to a syntax error anyway because you did not indent extra after "elif month < minmon:", "if day > maxday:" and "elif day < minday:". -- Andr? Engels, andreengels at gmail.com From pyflux at yahoo.com Wed Mar 9 17:52:16 2011 From: pyflux at yahoo.com (Okta Satria) Date: Thu, 10 Mar 2011 00:52:16 +0800 (SGT) Subject: [Tutor] PyQuery Message-ID: <583785.70441.qm@web77605.mail.sg1.yahoo.com> Dear All, I'm new in python programming. Now I'm learning about dictionary and PyQuery. Could someone help me to read this table please: http://id.wikipedia.org/wiki/Tabel_perbandingan_ukuran_jarum_hipodermik end the result is in nested dictionary like this: 'Jarum' : 'Guage', 'Perkiraan Diameter Luar' : ['mm', 'inchi', 'toleransi'], 'Perkiraan Diameter Dalam' : ['mm', 'inchi', 'toleransi'] then: Jarum -> Guage -> 10, 11, 12 and so on Perkiraan Diameter Luar -> mm -> 3.404, 3.048, 2.769 and so on Perkiraan Diameter Luar -> inchi -> 0.1340, 0.1200, 0.1090 and so on . . . I found this idea to learn dictionary. I'm learning from code :( Thanks Before . . . Best Regards, { 'p y f l u x' : [ '1 3 0 E 2 C 9' ] } -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Mar 9 19:09:55 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 09 Mar 2011 13:09:55 -0500 Subject: [Tutor] PyQuery In-Reply-To: <583785.70441.qm@web77605.mail.sg1.yahoo.com> References: <583785.70441.qm@web77605.mail.sg1.yahoo.com> Message-ID: <4D77C273.8010300@gmail.com> On 3/9/2011 11:52 AM, Okta Satria wrote: > > Dear All, > > I'm new in python programming. Now I'm learning about dictionary and > PyQuery. Could someone help me to read this table please: > > http://id.wikipedia.org/wiki/Tabel_perbandingan_ukuran_jarum_hipodermik > > end the result is in nested dictionary like this: > > 'Jarum' : 'Guage', 'Perkiraan Diameter Luar' : ['mm', 'inchi', > 'toleransi'], 'Perkiraan Diameter Dalam' : ['mm', 'inchi', 'toleransi'] > > then: > > Jarum -> Guage -> 10, 11, 12 and so on > Perkiraan Diameter Luar -> mm -> 3.404, 3.048, 2.769 and so on > Perkiraan Diameter Luar -> inchi -> 0.1340, 0.1200, 0.1090 and so on > . > This is a rather advanced question for a tutor list! It is also pretty vague. I took a look at the table and at PyQuery. It is hard for me to tell how PyQuery relates to that table. What have you tried? What results did you get? Why PyQuery as opposed to another html tool such as Beautiful Soup? The more you can tell us the easier it is for us to help. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From nookasree at yahoo.com Wed Mar 9 19:34:42 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Wed, 9 Mar 2011 10:34:42 -0800 (PST) Subject: [Tutor] Need help with dates in Python In-Reply-To: Message-ID: <43330.74448.qm@web65405.mail.ac4.yahoo.com> Hi, I'm new to Python programming. I've changed the code to below, but still it is not working, Could you pls. make the corrections in my code. import datetime t = () tot = [] min = datetime.date(2008, 1, 1) max = datetime.date(2012, 12, 31) for line in open ('test2.txt','r'): data = line.rstrip().split() a = data[9] b = data[4] (year, month, day) = b.split('-') year = int(year) month = int(month) day = int(day) t = (year,month,day) if t < max: maxyr = max if t > min: minyr = min t = (a,b,maxyr,minyr) tot.append(t) print t Thanks Sree. --- On Wed, 3/9/11, Andre Engels wrote: > From: Andre Engels > Subject: Re: [Tutor] Need help with dates in Python > To: "nookasree ponamala" > Cc: tutor at python.org > Date: Wednesday, March 9, 2011, 2:16 PM > On Wed, Mar 9, 2011 at 9:21 AM, > nookasree ponamala > wrote: > > Hi, > > > > I need help in finding the minimum date and maximum > date in a file. > > Here is my test file: > > s.no: ? dt1 ? ? amt ? ? id1 ? ? id2 > > 452 ? ? 2010-02-20 ? ? ?$23.26 ? ? ?059542 ? > ? ? ?06107 > > 452 ? ? 2010-02-05 ? ? ?$20.78 ? ? ?059542 ? > ? ? ?06107 > > 451 ? ? 2010-02-24 ? ? ?$5.99 ? ? ? 059542 ? > ? ? ?20151 > > 452 ? ? 2010-02-12 ? ? ?$114.25 ? ? 839745 ? > ? ? ?98101 > > 452 ? ? 2010-02-06 ? ? ?$28.00 ? ? ?839745 ? > ? ? ?06032 > > 451 ? ? 2010-02-12 ? ? ?$57.00 ? ? ?839745 ? > ? ? ?06269 > > > > I want to get the minimum and maximum dt1 for each > id1 > > > > Required result: > > > > id1 mindate maxdate > > 059542 ?2010-02-24 ? ? ?2010-02-20 > > 839745 ?2010-02-06 ? ? ?2010-02-12 > > > > Code: The code I tried. It doesn't work though. > > > > import sys > > import os > > t = () > > tot = [] > > maxyr = 2012 > > minyr = 2008 > > maxday = 31 > > minday = 1 > > maxmon = 12 > > minmon = 1 > > > > for line in open ('test2.txt','r'): > > ? ? ? ?data = line.rstrip().split() > > ? ? ? ?a = data[3] > > ? ? ? ?b = data[1] > > ? ? ? ?(year, month, day) = b.split('-') > > ? ? ? ?year = int(year) > > ? ? ? ?month = int(month) > > ? ? ? ?day = int(day) > > if year > maxyr: > > ? ? ? ?maxyr = year > > elif year < minyr: > > ? ? ? ?minyr = year > > if month > maxmon: > > ? ? ? ?maxmon = month > > ? ? ? ?elif month < minmon: > > ? ? ? ?minmon = month > > ? ? ? ?if day > maxday: > > ? ? ? ?maxday = day > > ? ? ? ?elif day < minday: > > ? ? ? ?minday = day > > ? ? ? ?max = (maxyr,maxmon,maxday) > > ? ? ? ?min = (minyr,minmon,minday) > > ? ? ? ?t = (a,b,max,min) > > ? ? ? ?tot.append(t) > > ? ? ? ?print t > > > > Could you pls. help me with this. > > I see several things go wrong. Here a list, which may well > not be complete: > > * You want the mindate and maxdate for each id1, but you > remember only > a single minyr, maxyr etcetera. There's no way that that is > going to > work. > * You initialize minyr etcetera to a date before the first > date you > will see, nd maxyr etcetera to a date after the last date. > This means > that you will never find an earlier respectively later one, > so they > would never be changed. You should do it exactly the other > way around > - minyr etcetera should be _later_ than any date that may > occur, maxyr > etcetera _earlier_. > * You move "if year > maxyr" back to the left. This > means that it is > not part of the loop, but is executed (only) once _after_ > the loop has > been gone through > * year < minyear should be "if", not "elif": it is > possible that the > new date is both the first _and_ the last date that has > been found > (this will be the case with the first date) > * You change maxyear, maxmonth and maxday independently. > That is not > what you are trying to do - you want the last date, not the > highest > year, highest month and highest day (if the dates were > 2001-12-01, > 2011-11-03 and 2005-05-30, you want the maximum date to be > 2011-11-03, > not 2011-12-30). You should thus find a way to compare the > *complete > date* and then if it is later than the maxdate or earlier > than the > mindate change the *complete date* > * At the end you show (well, in this case you don't because > it is > under "if month > maxmon") a quadruple consisting of > id1, current > date, lowest date and highest date - EACH time. You want > only the > triple and only after the last date of some value of id1 > has been > parsed (best to do that after all lines have been parsed) > * The code as shown will lead to a syntax error anyway > because you did > not indent extra after "elif month < minmon:", "if day > > maxday:" and > "elif day < minday:". > > > > > -- > Andr? Engels, andreengels at gmail.com > From ian.douglas at iandouglas.com Wed Mar 9 20:27:20 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Wed, 09 Mar 2011 11:27:20 -0800 Subject: [Tutor] Need help with dates in Python In-Reply-To: <43330.74448.qm@web65405.mail.ac4.yahoo.com> References: <43330.74448.qm@web65405.mail.ac4.yahoo.com> Message-ID: <4D77D498.3030506@iandouglas.com> I'm new to the language as well, but I think you're missing your indentation after each of your 'if' conditions? On 03/09/2011 10:34 AM, nookasree ponamala wrote: > if t< max: > maxyr = max<---------------- should be indented > if t> min: > minyr = min<---------------- should be indented > t = (a,b,maxyr,minyr) > tot.append(t) > print t -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Mar 9 21:02:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Mar 2011 07:02:30 +1100 Subject: [Tutor] Need help with dates in Python In-Reply-To: <43330.74448.qm@web65405.mail.ac4.yahoo.com> References: <43330.74448.qm@web65405.mail.ac4.yahoo.com> Message-ID: <4D77DCD6.3070705@pearwood.info> nookasree ponamala wrote: > Hi, > I'm new to Python programming. I've changed the code to below, but still it is not working, Could you pls. make the corrections in my code. If you are to be a programmer, you need to learn how to read the error messages you get. You probably would have seen an error something like this: >>> if True: ... pass File "", line 2 pass ^ IndentationError: expected an indented block or like this: >>> while True: ... pass ... if True: File "", line 3 if True: ^ IndentationError: unexpected indent This will tell you *exactly* what is wrong: you haven't indented the if block (see below), or possibly indented the wrong part. I'm not sure which, because you seem to have mixed spaces and tabs, or possibly my mail client Thunderbird is messing about with the indentation. In general, never ever mix spaces and tabs for indentation! Even when Python allows it, it becomes hard to maintain and harder to email it. If this is not your error, then please COPY and PASTE the FULL error you receive, do not retype it or summarize it in any way. > import datetime > t = () > tot = [] > min = datetime.date(2008, 1, 1) > max = datetime.date(2012, 12, 31) > for line in open ('test2.txt','r'): > data = line.rstrip().split() > a = data[9] > b = data[4] > (year, month, day) = b.split('-') > year = int(year) > month = int(month) > day = int(day) > t = (year,month,day) > if t < max: This is wrong. The if statement should be indented equally to the line above it. Only the if *block* should be indented further: if condition: # do not indent # indent this block do_something() elif another_condition: # outdent # indent this block do_something_else() and_more() even_more() else: # outdent # and indent the block again do_something_else() > maxyr = max > if t > min: > minyr = min And again here: at *least* one line must be indented after the if statement. > t = (a,b,maxyr,minyr) > tot.append(t) > print t -- Steven From eire1130 at gmail.com Wed Mar 9 21:56:40 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 9 Mar 2011 15:56:40 -0500 Subject: [Tutor] Need help with dates in Python In-Reply-To: <43330.74448.qm@web65405.mail.ac4.yahoo.com> References: <43330.74448.qm@web65405.mail.ac4.yahoo.com> Message-ID: On Wed, Mar 9, 2011 at 1:34 PM, nookasree ponamala wrote: > Hi, > I'm new to Python programming. I've changed the code to below, but still it > is not working, Could you pls. make the corrections in my code. > > import datetime > t = () > tot = [] > min = datetime.date(2008, 1, 1) > max = datetime.date(2012, 12, 31) > for line in open ('test2.txt','r'): > data = line.rstrip().split() > a = data[9] > b = data[4] > (year, month, day) = b.split('-') > year = int(year) > month = int(month) > day = int(day) > t = (year,month,day) > if t < max: > maxyr = max > if t > min: > minyr = min > t = (a,b,maxyr,minyr) > tot.append(t) > print t > > Thanks > Sree. > > --- On Wed, 3/9/11, Andre Engels wrote: > > > From: Andre Engels > > Subject: Re: [Tutor] Need help with dates in Python > > To: "nookasree ponamala" > > Cc: tutor at python.org > > Date: Wednesday, March 9, 2011, 2:16 PM > > On Wed, Mar 9, 2011 at 9:21 AM, > > nookasree ponamala > > wrote: > > > Hi, > > > > > > I need help in finding the minimum date and maximum > > date in a file. > > > Here is my test file: > > > s.no: dt1 amt id1 id2 > > > 452 2010-02-20 $23.26 059542 > > 06107 > > > 452 2010-02-05 $20.78 059542 > > 06107 > > > 451 2010-02-24 $5.99 059542 > > 20151 > > > 452 2010-02-12 $114.25 839745 > > 98101 > > > 452 2010-02-06 $28.00 839745 > > 06032 > > > 451 2010-02-12 $57.00 839745 > > 06269 > > > > > > I want to get the minimum and maximum dt1 for each > > id1 > > > > > > Required result: > > > > > > id1 mindate maxdate > > > 059542 2010-02-24 2010-02-20 > > > 839745 2010-02-06 2010-02-12 > > > > > > Code: The code I tried. It doesn't work though. > > > > > > import sys > > > import os > > > t = () > > > tot = [] > > > maxyr = 2012 > > > minyr = 2008 > > > maxday = 31 > > > minday = 1 > > > maxmon = 12 > > > minmon = 1 > > > > > > for line in open ('test2.txt','r'): > > > data = line.rstrip().split() > > > a = data[3] > > > b = data[1] > > > (year, month, day) = b.split('-') > > > year = int(year) > > > month = int(month) > > > day = int(day) > > > if year > maxyr: > > > maxyr = year > > > elif year < minyr: > > > minyr = year > > > if month > maxmon: > > > maxmon = month > > > elif month < minmon: > > > minmon = month > > > if day > maxday: > > > maxday = day > > > elif day < minday: > > > minday = day > > > max = (maxyr,maxmon,maxday) > > > min = (minyr,minmon,minday) > > > t = (a,b,max,min) > > > tot.append(t) > > > print t > > > > > > Could you pls. help me with this. > > > > I see several things go wrong. Here a list, which may well > > not be complete: > > > > * You want the mindate and maxdate for each id1, but you > > remember only > > a single minyr, maxyr etcetera. There's no way that that is > > going to > > work. > > * You initialize minyr etcetera to a date before the first > > date you > > will see, nd maxyr etcetera to a date after the last date. > > This means > > that you will never find an earlier respectively later one, > > so they > > would never be changed. You should do it exactly the other > > way around > > - minyr etcetera should be _later_ than any date that may > > occur, maxyr > > etcetera _earlier_. > > * You move "if year > maxyr" back to the left. This > > means that it is > > not part of the loop, but is executed (only) once _after_ > > the loop has > > been gone through > > * year < minyear should be "if", not "elif": it is > > possible that the > > new date is both the first _and_ the last date that has > > been found > > (this will be the case with the first date) > > * You change maxyear, maxmonth and maxday independently. > > That is not > > what you are trying to do - you want the last date, not the > > highest > > year, highest month and highest day (if the dates were > > 2001-12-01, > > 2011-11-03 and 2005-05-30, you want the maximum date to be > > 2011-11-03, > > not 2011-12-30). You should thus find a way to compare the > > *complete > > date* and then if it is later than the maxdate or earlier > > than the > > mindate change the *complete date* > > * At the end you show (well, in this case you don't because > > it is > > under "if month > maxmon") a quadruple consisting of > > id1, current > > date, lowest date and highest date - EACH time. You want > > only the > > triple and only after the last date of some value of id1 > > has been > > parsed (best to do that after all lines have been parsed) > > * The code as shown will lead to a syntax error anyway > > because you did > > not indent extra after "elif month < minmon:", "if day > > > maxday:" and > > "elif day < minday:". > > > > > > > > > > -- > > Andr? Engels, andreengels at gmail.com > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Other than some of the previous touched upon commentary, and going slightly beyond your question of "why doesn't this work" you can parse text to datetime objects directly in python by using the datetime.datetime.strptime function. In your case, it would look something like this: dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d'). This part, '%Y-%m-%d', is telling python how you should expect to see the datetimes in text version (4 digit year, 2 digit month, 2 digit day separated by dashes). You can then do comparisons directly the datetime object. Personally though, taking this to the next level, I would represent each line from the date you care about as a class, if you are familiar with how to use classes that is, with soemthing that looks like this: class id: > > def __init__(self,sno,dt1,amt,id1,id2): > > self.sno = sno > self.dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d') > self.amt = amt > self.id1 = id1 > self.id2 = id2 > > def print_all(self): > print self.sno, self.dt1, self.amt, self.id1, self.id2 Even if you aren't familiar with how to use classes, I would definitely consider using strptime instead of all those splits and whatnot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Wed Mar 9 23:42:58 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Wed, 9 Mar 2011 17:42:58 -0500 Subject: [Tutor] Need help with dates in Python In-Reply-To: References: <43330.74448.qm@web65405.mail.ac4.yahoo.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF9601A2B@EMARC112VS01.exchad.jpmchase.net> My major problem is your use of datetime. Why are you comparing each day/month/year manually? import datetime >>d = datetime.datetime(2001,01,15) >>c = datetime.datetime(2001,01,14) >>d > c True that makes your entire program look like: max = datetime.date(1900, 1, 1) min = datetime.date(2500, 12, 31) for line in open ('test2.txt','r'): data = line.rstrip().split() a = data[9] b = data[4] (year, month, day) = b.split('-') date = datetime.date(year,month,day) if date > max: max = date if date < min: min = date print 'blah' + str(min) + str(max) + 'blah' Not sure exactly how you are printing, but hopefully you get the point. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of James Reynolds Sent: Wednesday, March 09, 2011 2:57 PM To: nookasree ponamala Cc: tutor at python.org Subject: Re: [Tutor] Need help with dates in Python On Wed, Mar 9, 2011 at 1:34 PM, nookasree ponamala > wrote: Hi, I'm new to Python programming. I've changed the code to below, but still it is not working, Could you pls. make the corrections in my code. import datetime t = () tot = [] min = datetime.date(2008, 1, 1) max = datetime.date(2012, 12, 31) for line in open ('test2.txt','r'): data = line.rstrip().split() a = data[9] b = data[4] (year, month, day) = b.split('-') year = int(year) month = int(month) day = int(day) t = (year,month,day) if t < max: maxyr = max if t > min: minyr = min t = (a,b,maxyr,minyr) tot.append(t) print t Thanks Sree. --- On Wed, 3/9/11, Andre Engels > wrote: > From: Andre Engels > > Subject: Re: [Tutor] Need help with dates in Python > To: "nookasree ponamala" > > Cc: tutor at python.org > Date: Wednesday, March 9, 2011, 2:16 PM > On Wed, Mar 9, 2011 at 9:21 AM, > nookasree ponamala > > wrote: > > Hi, > > > > I need help in finding the minimum date and maximum > date in a file. > > Here is my test file: > > s.no: dt1 amt id1 id2 > > 452 2010-02-20 $23.26 059542 > 06107 > > 452 2010-02-05 $20.78 059542 > 06107 > > 451 2010-02-24 $5.99 059542 > 20151 > > 452 2010-02-12 $114.25 839745 > 98101 > > 452 2010-02-06 $28.00 839745 > 06032 > > 451 2010-02-12 $57.00 839745 > 06269 > > > > I want to get the minimum and maximum dt1 for each > id1 > > > > Required result: > > > > id1 mindate maxdate > > 059542 2010-02-24 2010-02-20 > > 839745 2010-02-06 2010-02-12 > > > > Code: The code I tried. It doesn't work though. > > > > import sys > > import os > > t = () > > tot = [] > > maxyr = 2012 > > minyr = 2008 > > maxday = 31 > > minday = 1 > > maxmon = 12 > > minmon = 1 > > > > for line in open ('test2.txt','r'): > > data = line.rstrip().split() > > a = data[3] > > b = data[1] > > (year, month, day) = b.split('-') > > year = int(year) > > month = int(month) > > day = int(day) > > if year > maxyr: > > maxyr = year > > elif year < minyr: > > minyr = year > > if month > maxmon: > > maxmon = month > > elif month < minmon: > > minmon = month > > if day > maxday: > > maxday = day > > elif day < minday: > > minday = day > > max = (maxyr,maxmon,maxday) > > min = (minyr,minmon,minday) > > t = (a,b,max,min) > > tot.append(t) > > print t > > > > Could you pls. help me with this. > > I see several things go wrong. Here a list, which may well > not be complete: > > * You want the mindate and maxdate for each id1, but you > remember only > a single minyr, maxyr etcetera. There's no way that that is > going to > work. > * You initialize minyr etcetera to a date before the first > date you > will see, nd maxyr etcetera to a date after the last date. > This means > that you will never find an earlier respectively later one, > so they > would never be changed. You should do it exactly the other > way around > - minyr etcetera should be _later_ than any date that may > occur, maxyr > etcetera _earlier_. > * You move "if year > maxyr" back to the left. This > means that it is > not part of the loop, but is executed (only) once _after_ > the loop has > been gone through > * year < minyear should be "if", not "elif": it is > possible that the > new date is both the first _and_ the last date that has > been found > (this will be the case with the first date) > * You change maxyear, maxmonth and maxday independently. > That is not > what you are trying to do - you want the last date, not the > highest > year, highest month and highest day (if the dates were > 2001-12-01, > 2011-11-03 and 2005-05-30, you want the maximum date to be > 2011-11-03, > not 2011-12-30). You should thus find a way to compare the > *complete > date* and then if it is later than the maxdate or earlier > than the > mindate change the *complete date* > * At the end you show (well, in this case you don't because > it is > under "if month > maxmon") a quadruple consisting of > id1, current > date, lowest date and highest date - EACH time. You want > only the > triple and only after the last date of some value of id1 > has been > parsed (best to do that after all lines have been parsed) > * The code as shown will lead to a syntax error anyway > because you did > not indent extra after "elif month < minmon:", "if day > > maxday:" and > "elif day < minday:". > > > > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Other than some of the previous touched upon commentary, and going slightly beyond your question of "why doesn't this work" you can parse text to datetime objects directly in python by using the datetime.datetime.strptime function. In your case, it would look something like this: dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d'). This part, '%Y-%m-%d', is telling python how you should expect to see the datetimes in text version (4 digit year, 2 digit month, 2 digit day separated by dashes). You can then do comparisons directly the datetime object. Personally though, taking this to the next level, I would represent each line from the date you care about as a class, if you are familiar with how to use classes that is, with soemthing that looks like this: class id: def __init__(self,sno,dt1,amt,id1,id2): self.sno = sno self.dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d') self.amt = amt self.id1 = id1 self.id2 = id2 def print_all(self): print self.sno, self.dt1, self.amt, self.id1, self.id2 Even if you aren't familiar with how to use classes, I would definitely consider using strptime instead of all those splits and whatnot. This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyflux at yahoo.com Thu Mar 10 02:52:54 2011 From: pyflux at yahoo.com (Okta Satria) Date: Thu, 10 Mar 2011 09:52:54 +0800 (SGT) Subject: [Tutor] PyQuery In-Reply-To: <4D77C273.8010300@gmail.com> Message-ID: <426616.67791.qm@web77606.mail.sg1.yahoo.com> I have basic understanding of dictionary and urllib. http://id.wikipedia.org/wiki/Tabel_perbandingan_ukuran_jarum_hipodermik I extracted the html file from that site by using urllib library. Then, I read PyQuery, it's JQuery-Like. So, I want to extract the content of the table and I want the result in dictionary. Column Headers are the keys, and its data is the value. I hope you could gime an idea to extract it [ and the code if possible :) ] Best Regards, pyflux -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Thu Mar 10 12:49:51 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 10 Mar 2011 06:49:51 -0500 Subject: [Tutor] PyQuery In-Reply-To: <426616.67791.qm@web77606.mail.sg1.yahoo.com> References: <4D77C273.8010300@gmail.com> <426616.67791.qm@web77606.mail.sg1.yahoo.com> Message-ID: pseudo: for line in file: query = {} columnheader = line[0] headercontent = line[1] query[columnheader] = [header1content] -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Thu Mar 10 16:53:49 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 10 Mar 2011 16:53:49 +0100 Subject: [Tutor] How to sum weighted matrices In-Reply-To: References: Message-ID: Numpy apart, you can use lists and loops: >>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix2 = [[3, 2, 1], [6, 5, 4], [9, 8, 7]] >>> result = [] >>> w = [1, 2] >>> for x in range(len(matrix)): row = [] for y in range(len(matrix[x])): row.append((w[0]*matrix[x][y])+(w[1]*matrix2[x][y])) result.append(row) >>> result [[7, 6, 5], [16, 15, 14], [25, 24, 23]] >>> But I think this isn't pythonic way, so maybe someone else can help you 2011/3/7 shu wei > Hello all, > > I am new to python and numpy. > My question is how to sum up N weighted matrices. > For example w=[1,2] (N=2 case) > m1=[1 2 3, > 3 4 5] > > m2=[3 4 5, > 4 5 6] > I want to get a matrix Y=w[1]*m1+w[2]*m2 by using a loop. > > My original problem is like this > X=[1 2 3, > 3 4 5, > 4 5 6] > > a1=[1 2 3] 1st row of X > m1=a1'*a1 a matirx > a2=[3 4 5] 2nd row of X > m2=a2'*a2 > a3=[ 4 5 6] 3rd row of X > m3=a3'*a3 > > I want to get Y1=w[1]*m1+w[2]*m2 > Y2=w[1]*m2+w[2]*m3 > So basically it is rolling and to sum up the weighted matries > I have a big X, the rolling window is relatively small. > > I tried to use > > sq=np.array([x[i].reshape(-1,1)*x[i] for i in np.arange(0,len(x)]) # > s=len(x) > m=np.array([sq[i:i+t] for i in np.arange(0,s-t+1)]) # t is the len(w) > > then I was stuck, I tried to use a loop somethig like > Y=np.array([np.sum(w[i]*m[j,i],axis=0) for i in np.arange(0,t)] ) > Any suggestion is welcome. > > sue > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Thu Mar 10 20:35:36 2011 From: fal at libero.it (Francesco Loffredo) Date: Thu, 10 Mar 2011 20:35:36 +0100 Subject: [Tutor] Need help with dates in Python In-Reply-To: <837397.42866.qm@web65410.mail.ac4.yahoo.com> References: <837397.42866.qm@web65410.mail.ac4.yahoo.com> Message-ID: <4D792808.3020100@libero.it> On 09/03/2011 9.21, nookasree ponamala wrote: > Hi, > > I need help in finding the minimum date and maximum date in a file. > Here is my test file: > s.no: dt1 amt id1 id2 > 452 2010-02-20 $23.26 059542 06107 > 452 2010-02-05 $20.78 059542 06107 > 451 2010-02-24 $5.99 059542 20151 > 452 2010-02-12 $114.25 839745 98101 > 452 2010-02-06 $28.00 839745 06032 > 451 2010-02-12 $57.00 839745 06269 > > I want to get the minimum and maximum dt1 for each id1 > > Required result: > > id1 mindate maxdate > 059542 2010-02-24 2010-02-20 > 839745 2010-02-06 2010-02-12 > > Code: The code I tried. It doesn't work though. I noticed that your dates are formatted in a way that makes it easy to compare them as strings. This allows you not only to do without splitting dates into year, month and day, but also to do without the datetime module: I'm also, AFAIK, the first one to address your need for the min and max date FOR EACH ID1, not in the whole file. . ids = {} # create an empty dictionary to store results . for L in open("test.txt", "r"): . S = L.split() # allow direct access to fields . if S[3] in ids: . mindate, maxdate = ids[S[3]] # current stored minimum and maximum date . if S[1] < mindate: . mindate = S[1] . if S[1] > maxdate: . maxdate = S[1] . ids[S[3]] = (mindate, maxdate) # new stored min and max . else: . ids[S[3]] = (S[1], S[1]) # initialize storage for the current id1, with min and max in a tuple . #leave print formatting as an exercise to the reader (but you can do without it!) . print ids Hope this helps... Francesco ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 10.0.1204 / Database dei virus: 1497/3495 - Data di rilascio: 09/03/2011 From nookasree at yahoo.com Thu Mar 10 22:52:27 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Thu, 10 Mar 2011 13:52:27 -0800 (PST) Subject: [Tutor] Need help with dates in Python In-Reply-To: Message-ID: <181315.39639.qm@web65412.mail.ac4.yahoo.com> Hi All: ? Thanks for all of your answers. I could solve this problem using strptime (datetime.datetime.strptime(dt1, '%Y-%m-%d') and correct indentation. ? As I am new to python programming, I don't know how to use classes yet, still learning. ? Thanks, Sree. ? ? ? --- On Thu, 3/10/11, James Reynolds wrote: From: James Reynolds Subject: Re: [Tutor] Need help with dates in Python To: "nookasree ponamala" Cc: "Andre Engels" , tutor at python.org Date: Thursday, March 10, 2011, 2:26 AM On Wed, Mar 9, 2011 at 1:34 PM, nookasree ponamala wrote: Hi, I'm new to Python programming. I've changed the code to below, but still it is not working, Could you pls. make the corrections in my code. import datetime t = () tot = [] min = datetime.date(2008, 1, 1) max = datetime.date(2012, 12, 31) for line in open ('test2.txt','r'): ? ? ? ?data = line.rstrip().split() ? ? ? ?a = data[9] ? ? ? ?b = data[4] ? ? ? ?(year, month, day) = b.split('-') ? ? ? ?year = int(year) ? ? ? ?month = int(month) ? ? ? ?day = int(day) ? ? ? ?t = (year,month,day) ? ? ? ? ? ? ? ?if t < max: ? ? ? ? ? ? ? ?maxyr = max ? ? ? ? ? ? ? ?if t > min: ? ? ? ? ? ? ? ?minyr = min ? ? ? ? ? ? ? ?t = (a,b,maxyr,minyr) ? ? ? ? ? ? ? ?tot.append(t) ? ? ? ? ? ? ? ?print t Thanks Sree. --- On Wed, 3/9/11, Andre Engels wrote: > From: Andre Engels > Subject: Re: [Tutor] Need help with dates in Python > To: "nookasree ponamala" > Cc: tutor at python.org > Date: Wednesday, March 9, 2011, 2:16 PM > On Wed, Mar 9, 2011 at 9:21 AM, > nookasree ponamala > wrote: > > Hi, > > > > I need help in finding the minimum date and maximum > date in a file. > > Here is my test file: > > s.no: ? dt1 ? ? amt ? ? id1 ? ? id2 > > 452 ? ? 2010-02-20 ? ? ?$23.26 ? ? ?059542 ? > ? ? ?06107 > > 452 ? ? 2010-02-05 ? ? ?$20.78 ? ? ?059542 ? > ? ? ?06107 > > 451 ? ? 2010-02-24 ? ? ?$5.99 ? ? ? 059542 ? > ? ? ?20151 > > 452 ? ? 2010-02-12 ? ? ?$114.25 ? ? 839745 ? > ? ? ?98101 > > 452 ? ? 2010-02-06 ? ? ?$28.00 ? ? ?839745 ? > ? ? ?06032 > > 451 ? ? 2010-02-12 ? ? ?$57.00 ? ? ?839745 ? > ? ? ?06269 > > > > I want to get the minimum and maximum dt1 for each > id1 > > > > Required result: > > > > id1 mindate maxdate > > 059542 ?2010-02-24 ? ? ?2010-02-20 > > 839745 ?2010-02-06 ? ? ?2010-02-12 > > > > Code: The code I tried. It doesn't work though. > > > > import sys > > import os > > t = () > > tot = [] > > maxyr = 2012 > > minyr = 2008 > > maxday = 31 > > minday = 1 > > maxmon = 12 > > minmon = 1 > > > > for line in open ('test2.txt','r'): > > ? ? ? ?data = line.rstrip().split() > > ? ? ? ?a = data[3] > > ? ? ? ?b = data[1] > > ? ? ? ?(year, month, day) = b.split('-') > > ? ? ? ?year = int(year) > > ? ? ? ?month = int(month) > > ? ? ? ?day = int(day) > > if year > maxyr: > > ? ? ? ?maxyr = year > > elif year < minyr: > > ? ? ? ?minyr = year > > if month > maxmon: > > ? ? ? ?maxmon = month > > ? ? ? ?elif month < minmon: > > ? ? ? ?minmon = month > > ? ? ? ?if day > maxday: > > ? ? ? ?maxday = day > > ? ? ? ?elif day < minday: > > ? ? ? ?minday = day > > ? ? ? ?max = (maxyr,maxmon,maxday) > > ? ? ? ?min = (minyr,minmon,minday) > > ? ? ? ?t = (a,b,max,min) > > ? ? ? ?tot.append(t) > > ? ? ? ?print t > > > > Could you pls. help me with this. > > I see several things go wrong. Here a list, which may well > not be complete: > > * You want the mindate and maxdate for each id1, but you > remember only > a single minyr, maxyr etcetera. There's no way that that is > going to > work. > * You initialize minyr etcetera to a date before the first > date you > will see, nd maxyr etcetera to a date after the last date. > This means > that you will never find an earlier respectively later one, > so they > would never be changed. You should do it exactly the other > way around > - minyr etcetera should be _later_ than any date that may > occur, maxyr > etcetera _earlier_. > * You move "if year > maxyr" back to the left. This > means that it is > not part of the loop, but is executed (only) once _after_ > the loop has > been gone through > * year < minyear should be "if", not "elif": it is > possible that the > new date is both the first _and_ the last date that has > been found > (this will be the case with the first date) > * You change maxyear, maxmonth and maxday independently. > That is not > what you are trying to do - you want the last date, not the > highest > year, highest month and highest day (if the dates were > 2001-12-01, > 2011-11-03 and 2005-05-30, you want the maximum date to be > 2011-11-03, > not 2011-12-30). You should thus find a way to compare the > *complete > date* and then if it is later than the maxdate or earlier > than the > mindate change the *complete date* > * At the end you show (well, in this case you don't because > it is > under "if month > maxmon") a quadruple consisting of > id1, current > date, lowest date and highest date - EACH time. You want > only the > triple and only after the last date of some value of id1 > has been > parsed (best to do that after all lines have been parsed) > * The code as shown will lead to a syntax error anyway > because you did > not indent extra after "elif month < minmon:", "if day > > maxday:" and > "elif day < minday:". > > > > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ Tutor maillist ?- ?Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Other than some of the previous touched upon commentary, and going slightly beyond your question of "why doesn't this work" you can parse text to datetime objects directly in python by using the datetime.datetime.strptime function. In your case, it would look something like this: dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d'). This part,?'%Y-%m-%d', is telling python how you should expect to see the datetimes in text version (4 digit year, 2 digit month, 2 digit day?separated?by dashes). You can then do comparisons directly the datetime object. Personally though, taking this to the next level, I would represent each line from the date you care about as a class, if you are familiar with how to use classes that is, with soemthing that looks like this: class id: ?? ? ?? ?def __init__(self,sno,dt1,amt,id1,id2): ?? ? ? ? ?? ? ? ?self.sno = sno ?? ? ? ?self.dt1 = datetime.datetime.strptime(dt1, '%Y-%m-%d') ?? ? ? ?self.amt = amt ?? ? ? ?self.id1 = id1 ?? ? ? ?self.id2 = id2 ?? ? ? ? ?? ?def print_all(self): ?? ? ? ?print self.sno, self.dt1, self.amt, self.id1, self.id2 Even if you aren't familiar with how to use classes, I would?definitely?consider using strptime instead of all those splits and whatnot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Mar 11 04:23:54 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 10 Mar 2011 22:23:54 -0500 Subject: [Tutor] very odd math problem Message-ID: Hi all, I am trying to get a list of ordered pairs from the below function. In my code, evaluate is more exciting, but the evaluate here will at least let this run. The below runs fine, with one exception: somehow, it is saying that -2+2.0 is 4.x, where x is a huge decimal involving E-16 (in other words, a really tiny number). Does anyone have any idea what is going on here? def getCoords(f, e1, e2, step=.1): #returns a list of (x,y) tuples from e1 to e2 at the given accuracy (step) time=0 i=0 coords=[] while time<=e2: print "time="+str(e1)+"+"+str(i)+"=" time=e1+i print time #watch this line when above is -2+2.0 coords.append((time, evaluate(f, time))) i=i+1*step return coords def evaluate(x,y): return x*y -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Fri Mar 11 06:05:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Mar 2011 16:05:34 +1100 Subject: [Tutor] very odd math problem In-Reply-To: References: Message-ID: <4D79AD9E.6030802@pearwood.info> Alex Hall wrote: > Hi all, > I am trying to get a list of ordered pairs from the below function. In > my code, evaluate is more exciting, but the evaluate here will at > least let this run. The below runs fine, with one exception: somehow, > it is saying that -2+2.0 is 4.x, where x is a huge decimal involving > E-16 (in other words, a really tiny number). Does anyone have any idea > what is going on here? Let's reword the description of the problem... "2.0 - 2 is a really tiny number close to 4e-16" Welcome to the wonders of floating point maths! Repeat after me: Floats are not real numbers... floats are not real numbers... floats are not real numbers... everything you learned about arithmetic in school only *approximately* applies to floats. Half :) and half :( First off, anything involving e-16 isn't a "huge decimal", it's a tiny decimal, very close to zero, no matter what the x is: 0.0000000000000004x Also, although you say "-2 + 2.0" in a comment, that's not actually what you calculate. I know this even though I don't know what you calculate, because I can test -2 + 2.0 and see that it is exactly zero: >>> -2 + 2.0 == 0 True Somewhere in your calculation you're probably calculating something which *looks* like 2.0 but isn't. Here's an example: >>> x = 2 + 1e-14 >>> print(x) 2.0 >>> x == 2.0 False but you can see the difference by printing the float with more decimal places than shown by the default view: >>> repr(x) '2.00000000000001' Another problem: you calculate your values by repeated addition. This is the wrong way to do it, because each addition has a tiny little error, and repeating them just compounds error upon error. Here's an example: >>> x = 0.0 >>> for i in range(10): ... x += 0.1 ... >>> x == 1.0 False >>> print(x) 1.0 >>> repr(x) '0.99999999999999989' The right way is to do it like this: >>> x = 0.0 >>> for i in range(1, 11): ... x = i*0.1 ... >>> x == 1.0 True This ensures that errors don't compound. Some further resources: http://floating-point-gui.de/ http://introcs.cs.princeton.edu/91float/ David Goldberg used to have a fantastic (although quite technical) discussion of floating point issues, "What Every Computer Scientist Should Know About Floating-Point Arithmetic": http://docs.sun.com/source/806-3568/ncg_goldberg.html Unfortunately, since Oracle bought Sun, they've removed the article. Bastards. If you can find a copy of Apple's old "Apple Numeric Manual" (2nd Edition), it has a fantastic introduction by William Kahan. Even though the book is about Apple's SANE, a lot will apply to other floating point systems as well. Google on William Kahan and read his stuff :) -- Steven From knacktus at googlemail.com Fri Mar 11 06:57:45 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 11 Mar 2011 06:57:45 +0100 Subject: [Tutor] very odd math problem In-Reply-To: References: Message-ID: <4D79B9D9.6000504@googlemail.com> Am 11.03.2011 04:23, schrieb Alex Hall: > Hi all, > I am trying to get a list of ordered pairs from the below function. In > my code, evaluate is more exciting, but the evaluate here will at > least let this run. The below runs fine, with one exception: somehow, > it is saying that -2+2.0 is 4.x, where x is a huge decimal involving > E-16 (in other words, a really tiny number). Does anyone have any idea > what is going on here? You can find some great posts at a thread about decimal floating point numbers some weeks ago for background reading. Or (and) look at this: http://docs.python.org/tutorial/floatingpoint.html#floating-point-arithmetic-issues-and-limitations Now my guess is: i is calculated as a sum of floats of step 0.1. That means you have in the base 2 representation an approximation of 0.1, not "exactly" 0.1, but something like 0.10000000000000123123. When i reaches approximately 2.0, it is actually 2.00000000000000000342374 (or what ever). On the other hand, e1 can be represented precisely if it's 2.0 in the base 2 representation. But the sum of e1 and i is actually your tiny number. That's why 2.0 - 2.0 is exactly 0.0, but (20*0.1 - 2.0 is not). To elaborate, you could add some lines to your code: def getCoords(f, e1, e2, step=.1): time=0 i=0 coords=[] while time<=e2: print "time="+str(e1)+"+"+str(i)+"=" print type(e1) print type(i) time=e1+i time_2 = e1 + e2 print "%s, %.24f" % (time, time) # app 0.0 print "%s, %.24f" % (time_2, time_2) # exact 0.0 coords.append((time, evaluate(f, time))) i=i+1*step return coords The reason why Python prints i as 2.0 in the first print statement is probably due to some internal auto-rounding when using str(). See the last paragraph of the link above. No idea, what's exactly going on under the hood. HTH, Jan > > def getCoords(f, e1, e2, step=.1): > #returns a list of (x,y) tuples from e1 to e2 at the given accuracy (step) > time=0 > i=0 > coords=[] > while time<=e2: > print "time="+str(e1)+"+"+str(i)+"=" > time=e1+i > print time #watch this line when above is -2+2.0 > coords.append((time, evaluate(f, time))) > i=i+1*step > return coords > > def evaluate(x,y): return x*y From knacktus at googlemail.com Fri Mar 11 07:00:01 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 11 Mar 2011 07:00:01 +0100 Subject: [Tutor] very odd math problem In-Reply-To: <4D79AD9E.6030802@pearwood.info> References: <4D79AD9E.6030802@pearwood.info> Message-ID: <4D79BA61.8050203@googlemail.com> Am 11.03.2011 06:05, schrieb Steven D'Aprano: > Alex Hall wrote: >> Hi all, >> I am trying to get a list of ordered pairs from the below function. In >> my code, evaluate is more exciting, but the evaluate here will at >> least let this run. The below runs fine, with one exception: somehow, >> it is saying that -2+2.0 is 4.x, where x is a huge decimal involving >> E-16 (in other words, a really tiny number). Does anyone have any idea >> what is going on here? > > > Let's reword the description of the problem... > > "2.0 - 2 is a really tiny number close to 4e-16" > > Welcome to the wonders of floating point maths! Repeat after me: > > Floats are not real numbers... floats are not real numbers... > floats are not real numbers... everything you learned about > arithmetic in school only *approximately* applies to floats. > > Half :) and half :( > > First off, anything involving e-16 isn't a "huge decimal", it's a tiny > decimal, very close to zero, no matter what the x is: > > 0.0000000000000004x > > Also, although you say "-2 + 2.0" in a comment, that's not actually what > you calculate. I know this even though I don't know what you calculate, > because I can test -2 + 2.0 and see that it is exactly zero: > > >>> -2 + 2.0 == 0 > True > > Somewhere in your calculation you're probably calculating something > which *looks* like 2.0 but isn't. Here's an example: > > >>> x = 2 + 1e-14 > >>> print(x) > 2.0 > >>> x == 2.0 > False > > but you can see the difference by printing the float with more decimal > places than shown by the default view: > > >>> repr(x) > '2.00000000000001' > > > Another problem: you calculate your values by repeated addition. This is > the wrong way to do it, because each addition has a tiny little error, > and repeating them just compounds error upon error. Here's an example: > > > >>> x = 0.0 > >>> for i in range(10): > ... x += 0.1 > ... > >>> x == 1.0 > False > >>> print(x) > 1.0 > >>> repr(x) > '0.99999999999999989' > > > The right way is to do it like this: > > > >>> x = 0.0 > >>> for i in range(1, 11): > ... x = i*0.1 > ... > >>> x == 1.0 > True > > This ensures that errors don't compound. > > > Some further resources: > > http://floating-point-gui.de/ > http://introcs.cs.princeton.edu/91float/ > > David Goldberg used to have a fantastic (although quite technical) > discussion of floating point issues, "What Every Computer Scientist > Should Know About Floating-Point Arithmetic": > > http://docs.sun.com/source/806-3568/ncg_goldberg.html > > Unfortunately, since Oracle bought Sun, they've removed the article. > Bastards. > > If you can find a copy of Apple's old "Apple Numeric Manual" (2nd > Edition), it has a fantastic introduction by William Kahan. Even though > the book is about Apple's SANE, a lot will apply to other floating point > systems as well. > > Google on William Kahan and read his stuff :) > > > Damn, you're fast!! ;-)) From una at unabuna.com Fri Mar 11 02:12:24 2011 From: una at unabuna.com (Una Murphy) Date: Thu, 10 Mar 2011 17:12:24 -0800 Subject: [Tutor] fourier transform (fwd) Message-ID: <4617C6A4-A151-4A0D-8BA1-969CED0780A0@unabuna.com> Hi Jeff Got your info off the web . Was wondering if you tutor people in FFT ? I am looking for someone in the SF bay area. Thank you Una From smerkyd at aol.com Fri Mar 11 04:29:35 2011 From: smerkyd at aol.com (apple owner) Date: Thu, 10 Mar 2011 22:29:35 -0500 Subject: [Tutor] Help on reading a plain file of names Message-ID: <3652B3CB-709E-48CE-BC4A-C05BD6B5CD8E@aol.com> Hello there, I am new to python and I am trying to open a plain text file of names and to see the number of names that start with specific letters and display them in a bar graph. I have python version 3.2 and have the graphics.py package as well. If anybody out there knows how I could do this, with specific examples, please email me back, it would be much appreciated. LIke i said, i'm new to python, but very curious and willing to learn it. From distortgiygas at gmail.com Fri Mar 11 09:12:53 2011 From: distortgiygas at gmail.com (DistortGiygas) Date: Fri, 11 Mar 2011 00:12:53 -0800 Subject: [Tutor] Using the console module. Message-ID: Python users, what's the best option for someone trying to emulate or use the curses module on the Windows platform? I've been fooling around with the console module: effbot.org/zone/console-handbook.htm But for the life of me, I can't figure out how to detect a KeyRelease. Could anyone share some insight, and maybe an example of how to code it? :( PS: I'm fairly new to programming. From alan.gauld at btinternet.com Fri Mar 11 09:22:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 08:22:31 -0000 Subject: [Tutor] fourier transform (fwd) References: <4617C6A4-A151-4A0D-8BA1-969CED0780A0@unabuna.com> Message-ID: "Una Murphy" wrote > Got your info off the web . Was wondering if you tutor people in > FFT ? I am looking for someone in the SF bay area. We are a tutor group for teaching the Python programming language. You probably want a math tutor group. If however you want to implement a FFT solution using Python we may be able to help, although specialised modules already exist which should do most of the work for you. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 11 09:31:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 08:31:02 -0000 Subject: [Tutor] very odd math problem References: <4D79AD9E.6030802@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Another problem: you calculate your values by repeated addition. > This is the wrong way to do it, because each addition has a tiny > little error, and repeating them just compounds error upon error. > Here's an example: > > >>> x = 0.0 > >>> for i in range(10): > ... x += 0.1 > ... > >>> x == 1.0 > False This much I follow. > The right way is to do it like this: > > >>> x = 0.0 > >>> for i in range(1, 11): > ... x = i*0.1 > ... > >>> x == 1.0 > True But this I don't understand. Why would you use a loop when the final value is just the final multiplication. Since you know the final value in advance (you need it to create the loop!) why not just do the final multiplication directly: x = 10*0.1 I think I'm missing something? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 11 09:36:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 08:36:10 -0000 Subject: [Tutor] Help on reading a plain file of names References: <3652B3CB-709E-48CE-BC4A-C05BD6B5CD8E@aol.com> Message-ID: "apple owner" wrote > I am new to python and I am trying to open a plain > text file of names and to see the number of names > that start with specific letters and display them > in a bar graph. OK, Lets break that down so that we can understand what exactly puzzles you: 1) Can you open a text file and read it? 2) Can you figure out if a string(a name) startwith a specific latter? 3) Can you build a collection based ion the starting letter - a dictionary maybe? 4) Can you display the dictionary keys and values on a graph? Can you try to solve each part of the problem separately and then put the pieces together for your final solution? Try posting back with specific questions and example code where you have tried to solve the problem. That makes it easier for us to se where you are having trouble. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Fri Mar 11 09:39:14 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Mar 2011 08:39:14 +0000 Subject: [Tutor] Using the console module. In-Reply-To: References: Message-ID: <4D79DFB2.7060305@timgolden.me.uk> On 11/03/2011 08:12, DistortGiygas wrote: > Python users, what's the best option for someone trying to emulate or > use the curses module on the Windows platform? > I've been fooling around with the console module: > effbot.org/zone/console-handbook.htm > > But for the life of me, I can't figure out how to detect a KeyRelease. > Could anyone share some insight, and maybe an example of how to code it? :( If your starting point is in fact curses, then you're probably better off using a curses-alike for Windows. Christopher Gohlke maintains binaries for one such: http://www.lfd.uci.edu/~gohlke/pythonlibs/ (search for "curses") TJG From steve at pearwood.info Fri Mar 11 12:30:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Mar 2011 22:30:50 +1100 Subject: [Tutor] very odd math problem In-Reply-To: References: <4D79AD9E.6030802@pearwood.info> Message-ID: <4D7A07EA.1020200@pearwood.info> Alan Gauld wrote: > Why would you use a loop when the final value is just > the final multiplication. Since you know the final value > in advance (you need it to create the loop!) why not > just do the final multiplication directly: > > x = 10*0.1 > > I think I'm missing something? The context was generating a list of values, not just the final value. But the result can be generalized to other situations. Consider some function that calculates a result x by an iterative process. You don't care about the intermediate results, but you do have to step through them on the way to the final result: x = initial_value while condition: x += increment(x) When possible, it is better to re-write the formula to avoid repeatedly adding an increment to x. The problem is, if each addition has potential error of dx, then N additions have potential error N*dx -- you can't assume that errors will always cancel. If N is large, so is the expected error. If it isn't possible to re-write it, then you have to take care to control for the error, which is hard. This is why good maths software tends to be horrible code, and why pretty code tends to make terrible maths software :( Another source of errors is catastrophic cancellation, when intermediate terms in a calculation cancel so badly that the end result is *completely* wrong. To see an especially extreme example, here's a torture test for summation by Tim Peters: >>> sum([1, 1e100, 1, -1e100] * 10000) 0.0 This sum *should* add up to 20000: 1 + 1e100 + 1 - 1e100 + 1 ... + 1e100 + 1 - 1e100 = 1 + 1 + 1 + ... + 1 = 20000 but due to round-off error at each step, it cancels to zero: >>> sum([1, 1e100, 1, -1e100] * 10000) 0.0 The math module starting in Python 2.6 has a specialised high-precision sum function that can cope: >>> import math >>> math.fsum([1, 1e100, 1, -1e100] * 10000) 20000.0 -- Steven From davea at ieee.org Fri Mar 11 12:40:13 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 11 Mar 2011 06:40:13 -0500 Subject: [Tutor] very odd math problem In-Reply-To: References: <4D79AD9E.6030802@pearwood.info> Message-ID: <4D7A0A1D.1010507@ieee.org> On 01/-10/-28163 02:59 PM, Alan Gauld wrote: > > "Steven D'Aprano" wrote > >> > >> The right way is to do it like this: >> >> >>> x = 0.0 >> >>> for i in range(1, 11): >> ... x = i*0.1 >> ... >> >>> x == 1.0 >> True > > But this I don't understand. > Why would you use a loop when the final value is just > the final multiplication. Since you know the final value > in advance (you need it to create the loop!) why not > just do the final multiplication directly: > > x = 10*0.1 > > I think I'm missing something? > What you missed was the original context, where other work was being done in the loop, and where the accuracy of the "accumulator" was being misunderstood. Steven's point was that doing repeated sums of a quantized value is going to lead to a cumulative error, which can be minimized by using integers and scaling. DaveA From oberoc at gmail.com Fri Mar 11 13:52:36 2011 From: oberoc at gmail.com (Tino Dai) Date: Fri, 11 Mar 2011 07:52:36 -0500 Subject: [Tutor] very odd math problem In-Reply-To: <4D79AD9E.6030802@pearwood.info> References: <4D79AD9E.6030802@pearwood.info> Message-ID: > Some further resources: > > http://floating-point-gui.de/ > http://introcs.cs.princeton.edu/91float/ > > David Goldberg used to have a fantastic (although quite technical) > discussion of floating point issues, "What Every Computer Scientist Should > Know About Floating-Point Arithmetic": > > http://docs.sun.com/source/806-3568/ncg_goldberg.html > > Found the sun article that Steve was talking about: http://replay.waybackmachine.org/20090227080227/http://docs.sun.com/source/806-3568/ncg_goldberg.html HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From mdekauwe at gmail.com Fri Mar 11 14:09:06 2011 From: mdekauwe at gmail.com (Martin De Kauwe) Date: Sat, 12 Mar 2011 00:09:06 +1100 Subject: [Tutor] Code structure help Message-ID: Hi, Note I have cross posted this as I have only just found this mailing list and perhaps it is the more appropriate place (I am not sure)? I have been working on re-writing a model in python. However I am not sure how easy on the eye my final structure is and would appreciate any constructive comments/suggestions. So broadly the model estimates how plants grow using a number of related sub functions which I have grouped into classes and they all live in separate files. My main issue at the moment is I think I have a lot of verbose class instances but I really can't see a better way to do it. Is there a better way? How do other people do similar things? I am talking largely about the instances in the method run_sim I have left some of the bones of the code out but this is basically what would it looks like. thanks, Martin import constants as const from file_parser import ConfigFileParser from plant_growth import PlantGrowth from print_outputs import PrintOutput from litter import LitterFlows from decomp import DecompFactors from soil_cnflows import CarbonFlows, NitrogenFlows from nmineralisation import Mineralisation from update_pools import CarbonPools, NitrogenPools ...etc... class ModelName(object): def __init__(self, cfg_fname=None): """ Set everything up Read meterological forcing file, any user adjusted files. If there is anything in the user file then adjust the model parameters, control or initial state attributes that are used within the code. """ # sweep the cmd line options, args = cmdline_parser() # quit if asked only to dump default paramater files if options.DUMP_INPUT == True: ...call some stuff... # read in user defined variables (stored in dictionaries) pars = ConfigFileParser(cfg_fname=cfg_fname) (control, params, state, files, fluxes, met_data) = pars.main() # objects holding model state, fluxes, etc self.met_data = met_data self.control = control self.params = params self.state = state self.fluxes = fluxes # instances of other model parts.. self.pr = PrintOutput(self.params, self.state, self.fluxes, self.control, self.files, dump=False) # start date of simulation self.date = self.simulation_start_date() ...etc.... def run_sim(self): mi = Mineralisation(self.control, self.params, self.state, self.fluxes) cf = CarbonFlows(self.control, self.params, self.state, self.fluxes) nf = NitrogenFlows(self.control, self.params, self.state, self.fluxes) de = Derive(self.control, self.params, self.state, self.fluxes) dc = DecompFactors(self.control, self.params, self.state, self.fluxes) lf = LitterFlows(self.control, self.params, self.state, self.fluxes) pg = PlantGrowth(self.control, self.params, self.state, self.fluxes, self.met_data) cpl = CarbonPools(self.control, self.params, self.state, self.fluxes) npl = NitrogenPools(self.control, self.params, self.state, self.fluxes) for i in self.met_data.doy: project_day = i - 1 # N:C ratios leafnc, rootnc = self.leaf_root_ncratio() # litterfall rate: C and N fluxes lf.flows(leafnc, rootnc) # plant growth pg.grow(project_day, self.date, leafnc) # calculate model decay rates dc.decay_rates() # soil model fluxes cf.calculate_cflows() nf.calculate_nflows() # N uptake and loss mi.calculate_mineralisation() # soil model - update pools cact, cslo, cpas = cpl.calculate_cpools() npl.calculate_npools(cact, cslo, cpas) if self.control.print_options == 1: self.pr.print_state() self.pr.print_fluxes() self.increment_date() if self.control.print_options == 2: self.pr.print_state() self.pr.print_fluxes() # house cleaning, close ouput files self.pr.tidy_up() -------------- next part -------------- An HTML attachment was scrubbed... URL: From cocron at gmail.com Fri Mar 11 14:28:55 2011 From: cocron at gmail.com (cocron at gmail.com) Date: Fri, 11 Mar 2011 14:28:55 +0100 Subject: [Tutor] Python help on unicode needed.... Message-ID: Hello Danny, Can you perhaps help me on a python Unicode issue? I have an audio collection of many chinese titles on my music Database. I would like to rename all music titles in the directories and subdirectories to either their ascii values (preceeding with a certain character/s like ?xx-? or just delete the chinese characters from the dir name and file names. Do you have a simple solution for the batch renaming issue? Many thanks in advance Istv?n many thanks! -- <<<< the more you give, the more you have >>>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 11 15:28:57 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 11 Mar 2011 14:28:57 +0000 (GMT) Subject: [Tutor] very odd math problem In-Reply-To: <4D7A0A1D.1010507@ieee.org> References: <4D79AD9E.6030802@pearwood.info> <4D7A0A1D.1010507@ieee.org> Message-ID: <246483.1601.qm@web86701.mail.ird.yahoo.com> > >> The right way is to do it like this: > >> > >> >>> x = 0.0 > >> >>> for i in range(1, 11): > >> ... x = i*0.1 > > But this I don't understand. > > Why would you use a loop when the final value is just > > What you missed was the original context, where other work was being > done in the loop, and where the accuracy of the "accumulator" was being > misunderstood. Ah yes, I confess I didn't read the OPs code in detail, I was more interested in Steven's reply. If other things are happening in the loop then that explains things. Thanks Dave. Alan G. From __peter__ at web.de Fri Mar 11 15:57:20 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Mar 2011 15:57:20 +0100 Subject: [Tutor] Code structure help References: Message-ID: Martin De Kauwe wrote: > Note I have cross posted this as I have only just found this mailing list > and perhaps it is the more appropriate place (I am not sure)? I think your question is appropriate for both lists, it just wasn't sexy enough for anyone on c.l.py to answer ;) > I have been working on re-writing a model in python. However I am not sure > how easy on the eye my final structure is and would appreciate any > constructive comments/suggestions. So broadly the model estimates how > plants grow using a number of related sub functions which I have grouped > into classes and they all live in separate files. My main issue at the > moment is I think I have a lot of verbose class instances but I really > can't see a better way to do it. Is there a better way? How do other > people do similar things? I am talking largely about the instances in the > method run_sim Random remarks: > pg = PlantGrowth(self.control, self.params, self.state, > self.fluxes, self.met_data) I'd prefer your code to be even more verbose here; no two-letter variables for anything that is non-generic. > # plant growth > pg.grow(project_day, self.date, leafnc) With the construction in mind that is actually > # plant growth > plant_growth.grow(project_day, self.date, leafnc) but plant_grows.grow() does not make a lot of sense, and the comment is superfluous as it just undoes the abbreviation instead of explaining what is going on. > for i in self.met_data.doy: > project_day = i - 1 > self.increment_date() I'd iterate over the project_day-s directly if possible for project_day in self.project_days(): ... > # calculate model decay rates > dc.decay_rates() A lot of methods don't take any arguments and return nothing. I'm guessing that they modify the state that you passed to the initializer. I prefer these modifications to be explicit if feasible, e. g. state = dc.decay_rates(state) where of course state is a placeholder for the actual variables that are necessary to do the calculations. The big picture? I'll leave that for someone else. From davea at ieee.org Fri Mar 11 16:05:56 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 11 Mar 2011 10:05:56 -0500 Subject: [Tutor] very odd math problem In-Reply-To: <4D7A07EA.1020200@pearwood.info> References: <4D79AD9E.6030802@pearwood.info> <4D7A07EA.1020200@pearwood.info> Message-ID: <4D7A3A54.5010009@ieee.org> On 01/-10/-28163 02:59 PM, Steven D'Aprano wrote: > Alan Gauld wrote: > >> Why would you use a loop when the final value is just >> the final multiplication. Since you know the final value >> in advance (you need it to create the loop!) why not >> just do the final multiplication directly: >> >> x = 10*0.1 >> >> I think I'm missing something? > > The context was generating a list of values, not just the final value. > But the result can be generalized to other situations. Consider some > function that calculates a result x by an iterative process. You don't > care about the intermediate results, but you do have to step through > them on the way to the final result: > > x = initial_value > while condition: > x += increment(x) > > > When possible, it is better to re-write the formula to avoid repeatedly > adding an increment to x. The problem is, if each addition has potential > error of dx, then N additions have potential error N*dx -- you can't > assume that errors will always cancel. If N is large, so is the expected > error. > > > I like to think of this as the social security problem, as that was the context in which I first saw it. When figuring social security withholding tax (USA), the employer is not allowed to just figure it on the basis of the current wage amount. If he did, the amount deducted would be rounded/truncated to the penny, and those partial pennies could add up to an enormous amount. Instead he figures the total soc.sec. tax on the pay for the year, and from that subtracts the amount withheld in all previous checks. So the total is always within a fractional penny of the correct amount. Any time you can't store the intermediate amount exactly, you need to decide how/if to eliminate accumulating residuals. DaveA From mdekauwe at gmail.com Fri Mar 11 17:06:47 2011 From: mdekauwe at gmail.com (mdekauwe) Date: Fri, 11 Mar 2011 08:06:47 -0800 (PST) Subject: [Tutor] Code structure help In-Reply-To: References: Message-ID: <31126370.post@talk.nabble.com> (...snip...) I think your question is appropriate for both lists, it just wasn't sexy enough for anyone on c.l.py to answer ;) what is not sexy about modelling plant carbon uptake ;P Random remarks: > pg = PlantGrowth(self.control, self.params, self.state, > self.fluxes, self.met_data) I'd prefer your code to be even more verbose here; no two-letter variables for anything that is non-generic. ok so a more thorough name then? I had seen class instances used before with single letters > # plant growth > pg.grow(project_day, self.date, leafnc) With the construction in mind that is actually Sorry don't get this? > # plant growth > plant_growth.grow(project_day, self.date, leafnc) but plant_grows.grow() does not make a lot of sense, and the comment is superfluous as it just undoes the abbreviation instead of explaining what is going on. Yep sorry I haven't gone through and finished all the comments, some of them were placeholders! Agreed grow isn't the best name > # calculate model decay rates > dc.decay_rates() A lot of methods don't take any arguments and return nothing. I'm guessing that they modify the state that you passed to the initializer. I prefer these modifications to be explicit if feasible, e. g. state = dc.decay_rates(state) where of course state is a placeholder for the actual variables that are necessary to do the calculations. yes well i guess that is one of the issues - two objects state and fluxes are modified throughout. So you think it is better to pass these to the methods rather than to the class constructors? If i do it that way I potentially have to then pass it throughout a number of methods in other classes. The way I set it up, I could call it though the self statement, e.g. self.fluxes.some_variable in a various class methods. The big picture? I'll leave that for someone else. thanks _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- View this message in context: http://old.nabble.com/-Tutor--Code-structure-help-tp31124923p31126370.html Sent from the Python - tutor mailing list archive at Nabble.com. From yasar11732 at gmail.com Fri Mar 11 17:12:21 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Fri, 11 Mar 2011 18:12:21 +0200 Subject: [Tutor] New person greets you all! Message-ID: Hi, First of all, I want to greet you all since this is the first time I will be using this mail groups. I consider myself being familiar with programming logic, structures in general. I do/did lots of PHP programming. I know python and PHP is pretty much different things, I am saying this just to show yourself my level of understanding on programming. I am not computer major or anything, but I am highly interested in. Today, I decided to make a chat application using python. I have chosen python because I know its powerfull and easy to use. The first step for me to go should be, clearly, begin learning how to use it :) My question is, where would you recommend for me to read tutorials, see example etc. What is the best approach would be? From knacktus at googlemail.com Fri Mar 11 19:18:29 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 11 Mar 2011 19:18:29 +0100 Subject: [Tutor] New person greets you all! In-Reply-To: References: Message-ID: <4D7A6775.8030402@googlemail.com> Am 11.03.2011 17:12, schrieb Ya?ar Arabac?: > Hi, > > First of all, I want to greet you all since this is the first time I > will be using this mail groups. > > I consider myself being familiar with programming logic, structures in > general. I do/did lots of PHP programming. I know python and PHP is > pretty much different things, I am saying this just to show yourself my > level of understanding on programming. I am not computer major or > anything, but I am highly interested in. > > Today, I decided to make a chat application using python. I have chosen > python because I know its powerfull and easy to use. The first step for > me to go should be, clearly, begin learning how to use it :) > > My question is, where would you recommend for me to read tutorials, see > example etc. What is the best approach would be? The official Python tutorial is a good start. You get familiar with the Python documentation as well. http://docs.python.org/py3k/ (Find the link to the tutorial on this page.) A classic and famous tutorial is here: http://www.alan-g.me.uk/ If you have any questions about this, you're lucky to be on this list, because the author of this ressource is very active here. (One of or the founder of the list?) Another classic is "Dive into Python". You can find it easily with google. There're two versions, Python 2.x and 3.x. By the way, I would recommend starting with Python 3.2. Some 3rd party libs and web frameworks are not ported yet, but for your chat app you should be very happy with Python 3.2. Recently, a tutorial with a bit of a different style has been finished. I haven't done it and the style is not my cup of tea, but some people like it a lot. It's called "Learning Python the hard way". Google for the url... Now, welcome to the beach of programming! Jan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From tiagotmc at gmail.com Fri Mar 11 19:26:01 2011 From: tiagotmc at gmail.com (Tiago Cunha) Date: Fri, 11 Mar 2011 15:26:01 -0300 Subject: [Tutor] Help on reading a plain file of names In-Reply-To: References: <3652B3CB-709E-48CE-BC4A-C05BD6B5CD8E@aol.com> Message-ID: I would suggest to use the NLTK package. Try methods like nltk.endswith() or nltk.startswith() On Fri, Mar 11, 2011 at 5:36 AM, Alan Gauld wrote: > "apple owner" wrote > > > I am new to python and I am trying to open a plain >> text file of names and to see the number of names >> that start with specific letters and display them >> in a bar graph. >> > > OK, Lets break that down so that we can understand > what exactly puzzles you: > > 1) Can you open a text file and read it? > 2) Can you figure out if a string(a name) startwith a specific latter? > 3) Can you build a collection based ion the starting letter - a dictionary > maybe? > 4) Can you display the dictionary keys and values on a graph? > > Can you try to solve each part of the problem separately > and then put the pieces together for your final solution? > > Try posting back with specific questions and example code > where you have tried to solve the problem. That makes it > easier for us to se where you are having trouble. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Mar 11 19:26:12 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 11 Mar 2011 12:26:12 -0600 Subject: [Tutor] New person greets you all! In-Reply-To: References: Message-ID: 2011/3/11 Ya?ar Arabac? > Hi, > > First of all, I want to greet you all since this is the first time I will > be using this mail groups. > Welcome! > I consider myself being familiar with programming logic, structures in > general. I do/did lots of PHP programming. I know python and PHP is pretty > much different things, I am saying this just to show yourself my level of > understanding on programming. I am not computer major or anything, but I am > highly interested in. > I think you'll find that your level of experience is similar to many people here. > Today, I decided to make a chat application using python. I have chosen > python because I know its powerfull and easy to use. The first step for me > to go should be, clearly, begin learning how to use it :) > > My question is, where would you recommend for me to read tutorials, see > example etc. What is the best approach would be? Since you say that you're familiar with basic programming concepts, I would recommend the official tutorial available here: http://python.org/doc/ Since you're just beginning, I will also mention a trap that catches many beginners - currently there are two versions of Python out, 2.x and 3.x - that are incompatible with each other in many of the beginner examples you will see. Currently, there are a fair number of 3rd party libraries that have been ported to 3.x, with many more conversions underway. But many (most?) of the 3rd party packages have not yet been ported. I will recommend two options: either to start learning with 3.x, and then if in the future you find a package that has not been ported yet, you can use Python 3to2 to convert your code. Alternatively, you could start with Python 2.x and use from __future__ import print_function, division, unicode_literals which will give you some of the behavior that is present in Python 3. You stated that you want to develop a chat application, and it's perfectly possible to create a chat application using the tools that are currently available in Python 3. Also, in the inevitable event that you run into problems, remember to post the full error message along with what you did, what you expected to happen, and what happened instead. Usually it's also a good idea to copy and paste your code. Good luck, and happy coding, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tiagotmc at gmail.com Fri Mar 11 19:41:10 2011 From: tiagotmc at gmail.com (Tiago Cunha) Date: Fri, 11 Mar 2011 15:41:10 -0300 Subject: [Tutor] New person greets you all! In-Reply-To: <4D7A6775.8030402@googlemail.com> References: <4D7A6775.8030402@googlemail.com> Message-ID: Hello, I am not a computer major, either. I am a Linguistics doctorate Student. I worked with the basics of programming (C, prolog...). And now using Python for Natural Language Processing. My interests are probably very different from yours, but I got intimate by Wesley Chun's Core Python Programming. Tiago Cunha On Fri, Mar 11, 2011 at 3:18 PM, Knacktus wrote: > Am 11.03.2011 17:12, schrieb Ya?ar Arabac?: > >> Hi, >> >> First of all, I want to greet you all since this is the first time I >> will be using this mail groups. >> >> I consider myself being familiar with programming logic, structures in >> general. I do/did lots of PHP programming. I know python and PHP is >> pretty much different things, I am saying this just to show yourself my >> level of understanding on programming. I am not computer major or >> anything, but I am highly interested in. >> >> Today, I decided to make a chat application using python. I have chosen >> python because I know its powerfull and easy to use. The first step for >> me to go should be, clearly, begin learning how to use it :) >> >> My question is, where would you recommend for me to read tutorials, see >> example etc. What is the best approach would be? >> > > The official Python tutorial is a good start. You get familiar with the > Python documentation as well. > http://docs.python.org/py3k/ > (Find the link to the tutorial on this page.) > > A classic and famous tutorial is here: > http://www.alan-g.me.uk/ > If you have any questions about this, you're lucky to be on this list, > because the author of this ressource is very active here. (One of or the > founder of the list?) > > Another classic is "Dive into Python". You can find it easily with google. > There're two versions, Python 2.x and 3.x. By the way, I would recommend > starting with Python 3.2. Some 3rd party libs and web frameworks are not > ported yet, but for your chat app you should be very happy with Python 3.2. > > Recently, a tutorial with a bit of a different style has been finished. I > haven't done it and the style is not my cup of tea, but some people like it > a lot. It's called "Learning Python the hard way". Google for the url... > > Now, welcome to the beach of programming! > > Jan > > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nookasree at yahoo.com Fri Mar 11 20:09:11 2011 From: nookasree at yahoo.com (nookasree ponamala) Date: Fri, 11 Mar 2011 11:09:11 -0800 (PST) Subject: [Tutor] Need help with dates in Python In-Reply-To: <4D792808.3020100@libero.it> Message-ID: <73306.31264.qm@web65411.mail.ac4.yahoo.com> Thanks for your help Francesco. This works. Sree. --- On Fri, 3/11/11, Francesco Loffredo wrote: > From: Francesco Loffredo > Subject: Re: [Tutor] Need help with dates in Python > To: tutor at python.org > Date: Friday, March 11, 2011, 1:05 AM > On 09/03/2011 9.21, nookasree > ponamala wrote: > > Hi, > > > > I need help in finding the minimum date and maximum > date in a file. > > Here is my test file: > > s.no:??? dt1??? > amt??? id1??? id2 > > 452? ???2010-02-20? ? > ? $23.26? ? ? 059542? ? ? > ? 06107 > > 452? ???2010-02-05? ? > ? $20.78? ? ? 059542? ? ? > ? 06107 > > 451? ???2010-02-24? ? > ? $5.99? ? ???059542? > ? ? ? 20151 > > 452? ???2010-02-12? ? > ? $114.25? ???839745? ? > ? ? 98101 > > 452? ???2010-02-06? ? > ? $28.00? ? ? 839745? ? ? > ? 06032 > > 451? ???2010-02-12? ? > ? $57.00? ? ? 839745? ? ? > ? 06269 > > > > I want to get the minimum and maximum dt1 for each > id1 > > > > Required result: > > > > id1 mindate maxdate > > 059542??? 2010-02-24??? > 2010-02-20??? ??? > > 839745??? 2010-02-06??? > 2010-02-12 > > > > Code: The code I tried. It doesn't work though. > > I noticed that your dates are formatted in a way that makes > it easy to compare them as strings. > This allows you not only to do without splitting dates into > year, month and day, but also to do without the datetime > module: > I'm also, AFAIK, the first one to address your need for the > min and max date FOR EACH ID1, not in the whole file. > > .? ? ids = {}? # create an empty dictionary > to store results > .? ? for L in open("test.txt", "r"): > .? ? ? S = L.split()? # allow direct > access to fields > .? ? ? if S[3] in ids: > .? ? ? ? mindate, maxdate = > ids[S[3]]? # current stored minimum and maximum date > .? ? ? ? if S[1] < mindate: > .? ? ? ? ? mindate = S[1] > .? ? ? ? if S[1] > maxdate: > .? ? ? ? ? maxdate = S[1] > .? ? ? ? ids[S[3]] = (mindate, > maxdate)? # new stored min and max > .? ? ? else: > .? ? ? ? ids[S[3]] = (S[1], S[1])? > # initialize storage for the current id1, with min and max > in a tuple > .? ? #leave print formatting as an exercise to > the reader (but you can do without it!) > .? ? print ids > > Hope this helps... > Francesco > > > ----- > Nessun virus nel messaggio. > Controllato da AVG - www.avg.com > Versione: 10.0.1204 / Database dei virus: 1497/3495 -? > Data di rilascio: 09/03/2011 > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Mar 11 21:36:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 20:36:15 -0000 Subject: [Tutor] Help on reading a plain file of names References: <3652B3CB-709E-48CE-BC4A-C05BD6B5CD8E@aol.com> Message-ID: "Tiago Cunha" wrote >I would suggest to use the NLTK package. > > Try methods like nltk.endswith() or nltk.startswith() NLTK is probably overkill. The standard string methods startswith() and endswith() are probably adequate for this case. Alan G. From alan.gauld at btinternet.com Fri Mar 11 21:41:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 20:41:17 -0000 Subject: [Tutor] Using the console module. References: Message-ID: "DistortGiygas" wrote > Python users, what's the best option for someone trying to emulate > or > use the curses module on the Windows platform? Write a GUI? Unlike Unix you know that you can run a GUI on windows so why not just write one. Its probably easier than using curses! > But for the life of me, I can't figure out how to detect a > KeyRelease. You need the key release rather than the keypress? I'm not sure curses can do that. I'm no curses expert though, but I've never seen it done. Console terminals don't always have the same level of fine grained events that a GUI has... For keypresses see the curses example in my tutorial (under event handling). But you still need a Windows version. PS. If you really need it you could try the Cygwin version of Python which comes with curses support... But then your users need cygwin installed too. But that might not be an issue... And if its for personal use, well, every Python Windows programmer should have cygwin installed! ;-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From susana.delgado_s at utzmg.edu.mx Fri Mar 11 21:59:20 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Fri, 11 Mar 2011 14:59:20 -0600 Subject: [Tutor] CSV to Excel Message-ID: Hello list!! I'm trying to write a CSV file to work it with Excel. My python script is working, the issue is: when I import the file from excel the data comes with quotes at the beginnig and ending of the row. I don't want to have these quotes. What is wrong with my code? import os, csv from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk( "C:\\" ): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(".shp")) writer = csv.writer(open('csv2.csv', "wb")) campos = ['Ruta,Archivo,.prj'] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) n = os.path.splitext(filepath) p = n[0]+'.prj' if os.path.exists(p): aRow = [""+filepath+","+filename+",1"] writer.writerow(aRow) else: aRow1 = [""+filepath+","+filename+",0"] writer.writerow(aRow1) print "El archivo esta listo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Mar 11 22:10:48 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 11 Mar 2011 21:10:48 +0000 Subject: [Tutor] CSV to Excel In-Reply-To: References: Message-ID: <4D7A8FD8.8010503@timgolden.me.uk> On 11/03/2011 8:59 PM, Susana Iraiis Delgado Rodriguez wrote: > Hello list!! > > I'm trying to write a CSV file to work it with Excel. My python script is > working, the issue is: when I import the file from excel the data comes with > quotes at the beginnig and ending of the row. I don't want to have these > quotes. What is wrong with my code? Essentially, the work is being done twice. The .writerow method expects a list which it will convert into a quoted, comma-separated string. You're giving it a list whose one element is a quoted, comma-separated string. Just pass it a list instead: writer.writerow (['Ruta', 'Archivo', '.prj']) ... writer.writerow ([filepath, filename, 1]) (BTW, my naive knowledge of Spanish suggests that you're confusing the two identical-sounding English words: "root" -> "raiz" and "route" -> "ruta"). TJG From joel.goldstick at gmail.com Fri Mar 11 22:13:32 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 11 Mar 2011 16:13:32 -0500 Subject: [Tutor] CSV to Excel In-Reply-To: References: Message-ID: On Fri, Mar 11, 2011 at 3:59 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Hello list!! > > I'm trying to write a CSV file to work it with Excel. My python script is > working, the issue is: when I import the file from excel the data comes with > quotes at the beginnig and ending of the row. I don't want to have these > quotes. What is wrong with my code? > > import os, csv > from osgeo import ogr,gdal,osr > from dbf import * > gdal.AllRegister() > file_list = [] > folders = None > for root, folders, files in os.walk( "C:\\" ): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(".shp")) > writer = csv.writer(open('csv2.csv', "wb")) > campos = ['Ruta,Archivo,.prj'] > writer.writerow(campos) > for row, filepath in enumerate(file_list, start=1): > (ruta, filename) = os.path.split(filepath) > n = os.path.splitext(filepath) > p = n[0]+'.prj' > if os.path.exists(p): > aRow = [""+filepath+","+filename+",1"] > I think your problem is in the line above. If you remove the extra quotes the problem goes away >>> filepath = 'filepath' >>> filename = 'filename' >>> aRow = [filepath,filename,1] >>> aRow ['filepath', 'filename', 1] writer.writerow(aRow) > else: > aRow1 = [""+filepath+","+filename+",0"] > writer.writerow(aRow1) > print "El archivo esta listo" > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 11 22:13:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Mar 2011 21:13:50 -0000 Subject: [Tutor] New person greets you all! References: <4D7A6775.8030402@googlemail.com> Message-ID: "Knacktus" wrote > The official Python tutorial is a good start. You get familiar with > the Python documentation as well. > http://docs.python.org/py3k/ > (Find the link to the tutorial on this page.) If you can already program thats the best starting point. For many folks its all they need. > A classic and famous tutorial is here: > http://www.alan-g.me.uk/ Thanks for the kind words :-) However it is really aimed at true beginners.... It tries to get you to the stage where the official documentation makes sense! :-) > Another classic is "Dive into Python". You can find it easily with > google. This is probably a better followup to the official tutorial for an experienced programmer than mine. And remember to ask questions here as you go! PS. I didn't found this group but I did join it near the beginning and started writing my tutorial using the common questions here to direct a lot of the content. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From yasar11732 at gmail.com Fri Mar 11 23:44:52 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Sat, 12 Mar 2011 00:44:52 +0200 Subject: [Tutor] New person greets you all! In-Reply-To: References: Message-ID: I see all of you guys suggest that starting with 3.x. I was wondering what is setback of starting with 2.7 since my linux distro (openSUSE 11.4) comes with it and it would be pretty painfull for me to update to 3.x because lots of my applications in my computer depends on it. So is it worth the trouble of updating? If that is really necessary, I think I can find some help in OpenSuse forums. From emile at fenx.com Sat Mar 12 00:35:19 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 11 Mar 2011 15:35:19 -0800 Subject: [Tutor] New person greets you all! In-Reply-To: References: Message-ID: On 3/11/2011 2:44 PM Ya?ar Arabac? said... > I see all of you guys suggest that starting with 3.x. I was wondering > what is setback of starting with 2.7 since my linux distro (openSUSE > 11.4) comes with it and it would be pretty painfull for me to update to > 3.x because lots of my applications in my computer depends on it. So is > it worth the trouble of updating? No. In fact, someone made the point earlier today, either here or on the main list, that linux administration scripts play nicer with 2.7 vs 3.x related somehow to unicode. Further, many useful third party libraries have not yet been ported to 3.x, so many of us (me included) haven't yet made the jump to 3.x. Just be aware that the two exist and the info you find on the net may not apply. Emile From dineshbvadhia at hotmail.com Sat Mar 12 00:39:06 2011 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 11 Mar 2011 15:39:06 -0800 Subject: [Tutor] Sorting multiple sequences Message-ID: I want to sort two sequences with different data types but both with an equal number of elements eg. f = [0.21, 0.68, 0.44, ..., 0.23] i = [6, 18, 3, ..., 45] The obvious solution is to use zip ie. pairs = zip(f,i) followed by pairs.sort(). This is fine but my sequences contain 10,000+ elements and the sort is performed thousands of times. Is there a faster solution? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Mar 12 00:57:57 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 11 Mar 2011 15:57:57 -0800 Subject: [Tutor] Sorting multiple sequences In-Reply-To: References: Message-ID: On 3/11/2011 3:39 PM Dinesh B Vadhia said... > I want to sort two sequences with different data types but both with an > equal number of elements eg. > f = [0.21, 0.68, 0.44, ..., 0.23] > i = [6, 18, 3, ..., 45] > The obvious solution is to use zip ie. pairs = zip(f,i) followed by > pairs.sort(). This is fine but my sequences contain 10,000+ elements and > the sort is performed thousands of times. Is there a faster solution? Sort only once? If you describe your situation better you may get more helpful responses, but if you really want to sort 1000's of times I doubt there's anything mush faster that pairs.sort()... Emile From steve at pearwood.info Sat Mar 12 01:16:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Mar 2011 11:16:30 +1100 Subject: [Tutor] Sorting multiple sequences In-Reply-To: References: Message-ID: <4D7ABB5E.9080506@pearwood.info> Dinesh B Vadhia wrote: > I want to sort two sequences with different data types but both with an equal number of elements eg. > > f = [0.21, 0.68, 0.44, ..., 0.23] > i = [6, 18, 3, ..., 45] > > The obvious solution is to use zip ie. pairs = zip(f,i) followed by pairs.sort(). This is fine It doesn't sound fine to me. Sorting pairs of items is *not* the same as sorting each sequence separately, except by accident. Even with the small example shown, you can see this: >>> f = [0.21, 0.68, 0.44, 0.23] >>> i = [6, 18, 3, 45] >>> sorted(f); sorted(i) # sorting individually [0.21, 0.23, 0.44, 0.68] [3, 6, 18, 45] >>> pairs = sorted(zip(f, i)) # sorting as pairs >>> print(pairs) [(0.21, 6), (0.23, 45), (0.44, 3), (0.68, 18)] >>> list(zip(*pairs)) # Split the pairs into separate sequences. [(0.21, 0.23, 0.44, 0.68), (6, 45, 3, 18)] In Python, the fastest way to sort multiple sequences is to sort multiple sequences. No tricks, nothing fancy, just: f.sort() i.sort() Don't use sorted() unless you have to keep the unsorted list as well, because sorted makes a copy of the data. In other words, don't do this: f = sorted(f) # No! Bad! but you can do this: old_f = f f = sorted(f) > but my sequences contain 10,000+ elements and the sort is performed thousands of times. Is there a faster solution? Ten thousand elements is not very many. Why do you need to sort thousands of times? What are you doing with the data that it needs repeated sorting? Python's sort routine is implemented in C, highly optimized, and is extremely fast. It is especially fast if the data is already almost sorted. So if you have a list of sorted data, and you add one item to the end, and re-sort, that will be *extremely* fast. There is literally nothing you can write in pure Python that will even come close to the speed of Python's sort. Unless you have profiled your application and discovered that sorting is the bottleneck making the app too slow, you are engaged in premature optimization. Don't try and guess what makes your code slow, measure! -- Steven From liamrotut at gmail.com Sat Mar 12 03:19:23 2011 From: liamrotut at gmail.com (s s) Date: Fri, 11 Mar 2011 19:19:23 -0700 Subject: [Tutor] Resources Message-ID: Hello, I was wondering where I should go to improve my python skills. I have finished the official tutorial and the tutorials on the official python website. From bermanrl at cfl.rr.com Sat Mar 12 03:25:24 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 11 Mar 2011 21:25:24 -0500 Subject: [Tutor] Resources In-Reply-To: References: Message-ID: <4D7AD994.6040704@cfl.rr.com> On 03/11/2011 09:19 PM, s s wrote: > Hello, I was wondering where I should go to improve my python skills. > I have finished the official tutorial and the tutorials on the > official python website. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Look at this page and pick your challenge. Have a great time. http://sixrevisions.com/resources/10-puzzle-websites-to-sharpen-your-programming-skills/ HTH, Robert From ladymcse2000 at gmail.com Sat Mar 12 07:39:39 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Fri, 11 Mar 2011 22:39:39 -0800 Subject: [Tutor] Help with python-gnupg Message-ID: If anyone is familiar with python-gnupg, I am having some difficulty with the syntax. I've tried the following: f = open('c:/test/filename.txt', 'r') datae = gpg.encrypt_file(f.read(), 'ladymcse at gmail.com', output=open('c:/gpg_test/data.gpg2', 'w')) or file_to_encrypt = open('c:/gpg_test/data.gpg2', 'w') datae = gpg(f.read(), 'ladymcse at gmail.com', output=file_to_encrypt) Either way, I can't get the output written to a file, it gives me an error: Traceback (most recent call last): File "", line 1, in datae = gpg.encrypt_file(f.read(), 'beckymcq at google.com', output=open('c:/test/data.gpg2', 'w')) File "C:\Python27\lib\site-packages\gnupg.py", line 583, in encrypt_file if os.path.exists(output): File "C:\Python27\lib\genericpath.py", line 18, in exists os.stat(path) TypeError: coercing to Unicode: need string or buffer, file found Any thoughts? Would reallly appreciate the help. If you aren't familiar with this and know of resources, it would be awesome. Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Mar 12 07:50:59 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Mar 2011 01:50:59 -0500 Subject: [Tutor] Help with python-gnupg In-Reply-To: References: Message-ID: Show the entire code, and error for both usages. The usages and a single error message for them both may be enough for someone not to try them out, and who can help you, if they knew more about the problem. Not everyone here will be an expert, but we do read direct code vs direct error, if we've been paying attention. Plus, we can try the whole code out, and see what you're trying to do altogether instead of in a specific portion that may misrepresent the whole of the problem. From smokefloat at gmail.com Sat Mar 12 07:55:10 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Mar 2011 01:55:10 -0500 Subject: [Tutor] Help with python-gnupg In-Reply-To: References: Message-ID: On Sat, Mar 12, 2011 at 1:39 AM, Becky Mcquilling wrote: > If anyone is familiar with python-gnupg, I am having some difficulty with > the syntax. ?I've tried the following: > f = open('c:/test/filename.txt', 'r') > datae = gpg.encrypt_file(f.read(), 'ladymcse at gmail.com', > output=open('c:/gpg_test/data.gpg2', 'w')) > > or > file_to_encrypt = open('c:/gpg_test/data.gpg2', 'w') > datae = gpg(f.read(), 'ladymcse at gmail.com', output=file_to_encrypt) > Either way, I can't get the output written to a file, it gives me an error: > Traceback (most recent call last): > ??File "", line 1, in > ?? ?datae = gpg.encrypt_file(f.read(), 'beckymcq at google.com', > output=open('c:/test/data.gpg2', 'w')) > ??File "C:\Python27\lib\site-packages\gnupg.py", line 583, in encrypt_file > ?? ?if os.path.exists(output): > ??File "C:\Python27\lib\genericpath.py", line 18, in exists > ?? ?os.stat(path) > TypeError: coercing to Unicode: need string or buffer, file found This seems to say it needs a string or buffer, but a file was found. Which says to me, you need to convert the file that is found to a string before passing it as a parameter to a function. It might be that output needs to be a string before it is used, so read the file and string it. It's just a guess from what I see though. > Any thoughts? ?Would reallly appreciate the help. > If you aren't familiar with this and know of resources, it would be awesome. > > Becky > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From smokefloat at gmail.com Sat Mar 12 08:07:26 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Mar 2011 02:07:26 -0500 Subject: [Tutor] Help with python-gnupg In-Reply-To: References: Message-ID: As a matter of fact, looking at them with know knowledge of the module, it says it's a typeerror, and that it expects string or buffer, but gets file. If this is the same error in both instances, then it's that output needs to be a string or buffer, so just string either the datae variable, or the output variable. From smokefloat at gmail.com Sat Mar 12 08:07:45 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Mar 2011 02:07:45 -0500 Subject: [Tutor] Help with python-gnupg In-Reply-To: References: Message-ID: On Sat, Mar 12, 2011 at 2:07 AM, David Hutto wrote: > As a matter of fact, looking at them with know *no* knowledge of the > module, it says it's a typeerror, and that it expects string or > buffer, but gets file. If this is the same error in both instances, > then it's that output needs to be a string or buffer, so just string > either the datae variable, or the output variable. > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From steve at pearwood.info Sat Mar 12 09:14:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Mar 2011 19:14:44 +1100 Subject: [Tutor] Help with python-gnupg In-Reply-To: References: Message-ID: <4D7B2B74.2090105@pearwood.info> Becky Mcquilling wrote: > If anyone is familiar with python-gnupg, I am having some difficulty with > the syntax. I've tried the following: When dealing with third party packages, unless it is an extremely well-known package like numpy or nltk, it is usually a good idea to link to the project's home page. Do you mean this project? http://packages.python.org/python-gnupg/ Reading the documentation, I think either of these should work: #1 encrypt data in a file input_file = open('c:/test/filename.txt', 'r') # notice that you open the file, but do not read from it. encrypted_data = gpg.encrypt_file(input_file, 'ladymcse at gmail.com', output='c:/gpg_test/data.gpg2') #2 encrypt data from a string data = open('c:/test/filename.txt', 'r').read() encrypted_data = gpg.encrypt_file(data, 'ladymcse at gmail.com', output='c:/gpg_test/data.gpg2') It looks like the problem you have is that you are passing the output file object, instead of just the file name. If this doesn't solve your problem, please post the exact error message in full, including the traceback, with the exact code you are using. -- Steven From dineshbvadhia at hotmail.com Sat Mar 12 09:18:30 2011 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 12 Mar 2011 00:18:30 -0800 Subject: [Tutor] Sorting multiple sequences Message-ID: The two sequences are pairs and have to be sorted as such. There are in fact hundreds of thousands of pairs of sequences (with different elements) with each sequence containing 10,000+ elements. Looks like pairs = sorted(zip(g,h)) is the best option? Dinesh Message: 6 Date: Sat, 12 Mar 2011 11:16:30 +1100 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] Sorting multiple sequences Message-ID: <4D7ABB5E.9080506 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Dinesh B Vadhia wrote: > I want to sort two sequences with different data types but both with an equal number of elements eg. > > f = [0.21, 0.68, 0.44, ..., 0.23] > i = [6, 18, 3, ..., 45] > > The obvious solution is to use zip ie. pairs = zip(f,i) followed by pairs.sort(). This is fine It doesn't sound fine to me. Sorting pairs of items is *not* the same as sorting each sequence separately, except by accident. Even with the small example shown, you can see this: >>> f = [0.21, 0.68, 0.44, 0.23] >>> i = [6, 18, 3, 45] >>> sorted(f); sorted(i) # sorting individually [0.21, 0.23, 0.44, 0.68] [3, 6, 18, 45] >>> pairs = sorted(zip(f, i)) # sorting as pairs >>> print(pairs) [(0.21, 6), (0.23, 45), (0.44, 3), (0.68, 18)] >>> list(zip(*pairs)) # Split the pairs into separate sequences. [(0.21, 0.23, 0.44, 0.68), (6, 45, 3, 18)] In Python, the fastest way to sort multiple sequences is to sort multiple sequences. No tricks, nothing fancy, just: f.sort() i.sort() Don't use sorted() unless you have to keep the unsorted list as well, because sorted makes a copy of the data. In other words, don't do this: f = sorted(f) # No! Bad! but you can do this: old_f = f f = sorted(f) > but my sequences contain 10,000+ elements and the sort is performed thousands of times. Is there a faster solution? Ten thousand elements is not very many. Why do you need to sort thousands of times? What are you doing with the data that it needs repeated sorting? Python's sort routine is implemented in C, highly optimized, and is extremely fast. It is especially fast if the data is already almost sorted. So if you have a list of sorted data, and you add one item to the end, and re-sort, that will be *extremely* fast. There is literally nothing you can write in pure Python that will even come close to the speed of Python's sort. Unless you have profiled your application and discovered that sorting is the bottleneck making the app too slow, you are engaged in premature optimization. Don't try and guess what makes your code slow, measure! -- Steven -------------- next part -------------- An HTML attachment was scrubbed... URL: From admatkin at umail.iu.edu Sat Mar 12 04:05:41 2011 From: admatkin at umail.iu.edu (Adrian Atkinson) Date: Fri, 11 Mar 2011 22:05:41 -0500 Subject: [Tutor] On off Toggle Message-ID: class Television(object): def __init__(self,__channel,volume,is_on): self.volume = volume self.is_on = "Power is off" power = self.is_on def toggle_power(self): if choice == "1" and power == self.is_on : power = "Power is Now on" elif choice =="1" and power =="Power is Now on" : power = self.is_on print power def instructions(): print "0 - Exit" print "1 - Toggle Power" print "2 - Change Channel" print "3 - Raise Volume" print "4 - Lower Volume" #Main choice = "" while choice != 0: choice = raw_input("Can I have a selection number? : ") tv = Television(0,50,"is_on") tv.toggle_power() I'm trying to make a toggle to turn the power on and off in the toggle_power method but I cannot figure this out. Any help would be greatly appreciated -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Mar 12 11:08:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2011 10:08:51 -0000 Subject: [Tutor] On off Toggle References: Message-ID: "Adrian Atkinson" wrote > class Television(object): While using a class is not in itself a bad idea it looks like you have much more fundamental issues to deal with so I'd suggest dropping the class for now and just write some functions using global variables to store the data. You can then move that into a class later if you need to. It will simplify the problem because you have a mixture of OO issues and basic programming issues. Lets fix the basics befoere worrying about the OO bits. > def __init__(self,__channel,volume,is_on): > self.volume = volume > self.is_on = "Power is off" > power = self.is_on Its usually better not to use strings for this kind of task. is_on is a boolean type value - its either on or its off so is better rep[resented by a number or a simple True/False boolean variable. Power in this case does nothing because after you assign it you throw it away when you leave the function. This is one of the areas where using globals would help simplify the problem. > def toggle_power(self): > > if choice == "1" and power == self.is_on : > power = "Power is Now on" > elif choice =="1" and power =="Power is Now on" : > power = self.is_on > print power I have no idea what you think is happening here. Can you describe in plain English how you think this should work? When you call Toggle Power what would you expect the program to do? What would be printed and what would the data look like? > choice = "" > while choice != 0: > choice = raw_input("Can I have a selection number? : ") > tv = Television(0,50,"is_on") > tv.toggle_power() Be careful about data types. choice starts as a string(empty) then is compared to a number(0) then is set to a string using raw_input(). Also you instantiate the tv object by passing 2 values but the constructor expects 3... > I'm trying to make a toggle to turn the power on and off in the > toggle_power > method but I cannot figure this out. Any help would be greatly > appreciated First express exactly what you want the toggle to do in English. Think about the data and the printed output - they are quite different things. Then come back to us for more help. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokefloat at gmail.com Sat Mar 12 11:22:44 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Mar 2011 05:22:44 -0500 Subject: [Tutor] On off Toggle In-Reply-To: References: Message-ID: You want toggle_power to turn on or off. class Television(object): def __init__(self): pass def toggle_power(self, choice): if choice == 0: poweroff() if choice == 1: poweron() # you set a choice that won't work unless user says choice = 1000 #you giv an off on status Off = 0 On = 1 You start the loop instance while choice != 0: #Ask for input 0 or 1 choice = raw_input("Power on = 1, power off = 0 . Press 1, or 0 : ") #give an instance for the class tv = Television() #give class and function instance to call toggle_power tv.toggle_power(choice) once the function is called, the choice is passed to the function and the poweron(), or poweroff() function is called. From wallenpb at gmail.com Sat Mar 12 15:59:51 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Mar 2011 08:59:51 -0600 Subject: [Tutor] Resources In-Reply-To: References: Message-ID: These are quite good, The Building Skills Books, these are online. http://homepage.mac.com/s_lott/books/index.html Tarleton Area Amateur Radio Club On Fri, Mar 11, 2011 at 20:19, s s wrote: > Hello, I was wondering where I should go to improve my python skills. > I have finished the official tutorial and the tutorials on the > official python website. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorje.kawabata at gmail.com Sat Mar 12 17:20:24 2011 From: dorje.kawabata at gmail.com (Dorje Kawabata) Date: Sat, 12 Mar 2011 11:20:24 -0500 Subject: [Tutor] What's an IndentationError & How Do I Fix It Message-ID: I'm using the python interpreter and entered the following code: >>> for page in range(1,6): ... search_results.append(twitter_search.search(q="#prayforjapan", rpp=100, page=page)) And received this: File "", line 2 search_results.append(twitter_search.search(q="#prayforjapan", rpp=100, page=page)) IndentationError: expected an indented block I'm learning python as my first language since coding Basic in 6th grade (over 30 years ago). I assume that in a text editor I would simply indent the code. *My question is how do I fix this in the interpreter? What do I type?* I'm running python 2.7.1, Mac OS 10.6.6, from the terminal. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Mar 12 17:32:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 Mar 2011 03:32:23 +1100 Subject: [Tutor] What's an IndentationError & How Do I Fix It In-Reply-To: References: Message-ID: <4D7BA017.2050300@pearwood.info> Dorje Kawabata wrote: > IndentationError: expected an indented block > > I'm learning python as my first language since coding Basic in 6th grade > (over 30 years ago). I assume that in a text editor I would simply indent > the code. > > *My question is how do I fix this in the interpreter? What do I type?* The same thing you would type in an editor: the tab key. Or if you prefer, you can type 4 spaces (or 8, so long as it is consistent) instead. -- Steven From yasar11732 at gmail.com Sat Mar 12 17:33:20 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Sat, 12 Mar 2011 18:33:20 +0200 Subject: [Tutor] What's an IndentationError & How Do I Fix It In-Reply-To: References: Message-ID: You could use any amount of spaces before your code. Just to remember being consisted, as every level of spaces counts as different code block. When you want to get out of indentation, just enter a line without indenting it. 12-03-2011 18:20, Dorje Kawabata yazm??: > I'm using the python interpreter and entered the following code: > > >>> for page in range(1,6): > ... search_results.append(twitter_search.search(q="#prayforjapan", > rpp=100, page=page)) > And received this: > File "", line 2 > search_results.append(twitter_search.search(q="#prayforjapan", > rpp=100, page=page)) > > IndentationError: expected an indented block > > I'm learning python as my first language since coding Basic in 6th grade > (over 30 years ago). I assume that in a text editor I would simply > indent the code. > > *My question is how do I fix this in the interpreter? What do I type?* > > I'm running python 2.7.1, Mac OS 10.6.6, from the terminal. > > Thanks in advance. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From dorje.kawabata at gmail.com Sat Mar 12 17:47:51 2011 From: dorje.kawabata at gmail.com (Dorje Kawabata) Date: Sat, 12 Mar 2011 11:47:51 -0500 Subject: [Tutor] What's an IndentationError & How Do I Fix It In-Reply-To: References: Message-ID: Perfect. Thanks for both how to make them and on how to not make them. 2011/3/12 Ya?ar Arabac? > You could use any amount of spaces before your code. Just to remember being > consisted, as every level of spaces counts as different code block. > > When you want to get out of indentation, just enter a line without > indenting it. > 12-03-2011 18:20, Dorje Kawabata yazm??: > >> I'm using the python interpreter and entered the following code: >> >> >>> for page in range(1,6): >> ... search_results.append(twitter_search.search(q="#prayforjapan", >> rpp=100, page=page)) >> And received this: >> File "", line 2 >> search_results.append(twitter_search.search(q="#prayforjapan", >> rpp=100, page=page)) >> >> IndentationError: expected an indented block >> >> I'm learning python as my first language since coding Basic in 6th grade >> (over 30 years ago). I assume that in a text editor I would simply >> indent the code. >> >> *My question is how do I fix this in the interpreter? What do I type?* >> >> I'm running python 2.7.1, Mac OS 10.6.6, from the terminal. >> >> Thanks in advance. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Sat Mar 12 19:54:02 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sat, 12 Mar 2011 20:54:02 +0200 Subject: [Tutor] what is 2.7 equiavelent of apihelper Message-ID: Hi, I am following "div into pyton" to learn python, because I like to dive into learning something :) I was following it, and got an error. Here is what I have done: Python 2.7 (r27:82500, Aug 07 2010, 16:54:59) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from apihelper import info Traceback (most recent call last): File "", line 1, in ImportError: No module named apihelper >>> a=5 >>> info(a) Traceback (most recent call last): File "", line 1, in NameError: name 'info' is not defined Appereantly, my python doesn't have a apihelper library. I was wondering if there is something else in 2.7 can be used instead of apihelper. Best Regards, Ya?ar Arabac? From alan.gauld at btinternet.com Sat Mar 12 21:31:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Mar 2011 20:31:05 -0000 Subject: [Tutor] what is 2.7 equiavelent of apihelper References: Message-ID: "Ya?ar Arabac?" wrote > >>> from apihelper import info > ImportError: No module named apihelper > Appereantly, my python doesn't have a apihelper library. Neither does anyone elses. Its a module defined in the book. A quick Google search suggests you will find the code in section 4.1.1. Here is the link I looked at... http://www.grabner-online.de/div_into/html/ch04s01s01.html HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From amonroe at columbus.rr.com Sun Mar 13 07:51:51 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 13 Mar 2011 01:51:51 -0500 Subject: [Tutor] Simplistic drive simulation Message-ID: <471493984816.20110313015151@columbus.rr.com> I'm trying to mentally plan out the most bare bones drive simulation possible, but I have this nagging feeling that I'm missing something. I was just going to start with, say, 16 or 64 "blocks", then randomly add and delete ficticious "files" (which won't have any actual content - I'm just trying to do the block management portion). For instance: drive=[None * 16] add 3 files A,B,C AAABBBCCC....... delete file B AAA...CCC....... add file D AAADDDCCCDD..... etc. 1. Is there some more clever way of tracking this than the very naive approach: toc = { A: [0, 1, 2], D: [3, 4, 5, 9, 10], C: [6, 7, 8] } ? 2. Is there some more clever way of adding files beyond the very naive brute force approach (pseudocode): block=0 while file still has more to write: while drive[block]!=none: block += 1 drive[block] = file.pop(0) toc[file].append(block) Neither of these seem like they'd scale very well (say, up to the resolution of your screen, with one block per pixel). The end goal is just a basic do-nothing light show that simulates fragmentation/defragmentation as eye candy. Alan From ladymcse2000 at gmail.com Sun Mar 13 08:43:58 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sat, 12 Mar 2011 23:43:58 -0800 Subject: [Tutor] Help with python-gnupg In-Reply-To: <4D7B2B74.2090105@pearwood.info> References: <4D7B2B74.2090105@pearwood.info> Message-ID: Thanks, everyone: Your suggestions worked. I will make sure to include full information next time. Becky On Sat, Mar 12, 2011 at 12:14 AM, Steven D'Aprano wrote: > Becky Mcquilling wrote: > >> If anyone is familiar with python-gnupg, I am having some difficulty with >> the syntax. I've tried the following: >> > > When dealing with third party packages, unless it is an extremely > well-known package like numpy or nltk, it is usually a good idea to link to > the project's home page. Do you mean this project? > > http://packages.python.org/python-gnupg/ > > Reading the documentation, I think either of these should work: > > > #1 encrypt data in a file > input_file = open('c:/test/filename.txt', 'r') > # notice that you open the file, but do not read from it. > encrypted_data = gpg.encrypt_file(input_file, 'ladymcse at gmail.com', > output='c:/gpg_test/data.gpg2') > > > #2 encrypt data from a string > data = open('c:/test/filename.txt', 'r').read() > encrypted_data = gpg.encrypt_file(data, 'ladymcse at gmail.com', > output='c:/gpg_test/data.gpg2') > > It looks like the problem you have is that you are passing the output file > object, instead of just the file name. > > > If this doesn't solve your problem, please post the exact error message in > full, including the traceback, with the exact code you are using. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vineethrakesh at gmail.com Sun Mar 13 08:58:55 2011 From: vineethrakesh at gmail.com (Vineeth Mohan) Date: Sun, 13 Mar 2011 03:58:55 -0400 Subject: [Tutor] passing by reference Message-ID: <4D7C793F.5070501@gmail.com> Hi, How are variables in python passed. By value or by referrence? For example if we consider a simple function below wherein the value of a does not get modified in the main function. def addition(a,b): a = a+1 return a+b if __name__ == '__main__': a = 10 b = 15 addition(a,b) Is the following the only way to pass by reference? or is there any other way def addition(x): x.a = x.a+1 return x.a+x.b class variables(object): a = 10 b = 15 if __name__ == '__main__': obj = variables() addition(obj) print obj.a From alan.gauld at btinternet.com Sun Mar 13 10:11:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Mar 2011 09:11:50 -0000 Subject: [Tutor] Simplistic drive simulation References: <471493984816.20110313015151@columbus.rr.com> Message-ID: "R. Alan Monroe" wrote > I was just going to start with, say, 16 or 64 "blocks", then > randomly > add and delete ficticious "files" > 1. Is there some more clever way of tracking this than the very > naive > approach: > toc = { > A: [0, 1, 2], > D: [3, 4, 5, 9, 10], > C: [6, 7, 8] > } ? Obviously yes, there is. Just read up on the various types of filesystems on Wikipedia for examples. What you are doing is pretty close to the original DOS FAT filesystem although even it did a bit more than you describe. But you can add more and more complexity through FAT2, NTFS, HPFS, and eventually wind up with the highly complex file systems used on supercomputers like the Cray and in dedicated Network Storage Arrays such as those used by EMC etc > 2. Is there some more clever way of adding files beyond the very > naive > brute force approach (pseudocode): > block=0 > while file still has more to write: > while drive[block]!=none: > block += 1 > drive[block] = file.pop(0) > toc[file].append(block) You can keep tables of contents to map fee disk space in terms of block cluster size so that you try to write the file into the smallest contigious chunk into which it will fit. There are also various algorithms for trweating the blocks as groups and then slicing the groups into mini groups as the space gets consumed. Most Operating System text books contain chapters on file management. > Neither of these seem like they'd scale very well (say, up to the > resolution of your screen, with one block per pixel). The end goal > is > just a basic do-nothing light show that simulates > fragmentation/defragmentation as eye candy. For that purpose the basic style you are using will be adequate. You are only talking about 2-5 million pixels at most on typical monitors. Usually more like 1.5 million on a laptop. And you are not too worried about speed, in fact too fast a display would just be wasted as most chanmges would never be seen! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Mar 13 10:25:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Mar 2011 09:25:22 -0000 Subject: [Tutor] passing by reference References: <4D7C793F.5070501@gmail.com> Message-ID: "Vineeth Mohan" wrote > How are variables in python passed. By value or by referrence? Neither, and trying to force a comparison to these traditional styles will always lead to an exercise in frustration as you find cases which don't quite fit.. Variables in Python are names that refer to objects. Some objects are mutable others immutable. Python functions take names as their parameters. Those names refer to objects. Whether those objects can be changed from inside the function depends upon the mutability of the oject to which the name refers. > example if we consider a simple function below wherein the value of > a does not get modified in the main function. > > def addition(a,b): > a = a+1 > return a+b In fact the value of a does get modified. What does not get modified is the original object that a referred to when the function was called. When you do a = a+1 you make the name 'a' point to a completely new object and that is what is returned. > Is the following the only way to pass by reference? or is there any > other way > > def addition(x): > x.a = x.a+1 > return x.a+x.b You could pass a list too: def addition(p): p[0] += 1 return p[0]+p[1] Basically any kind of mutable object will work. There are several more detailed explanations in the archives of this list if you search for them. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Mar 13 14:06:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Mar 2011 00:06:56 +1100 Subject: [Tutor] passing by reference In-Reply-To: <4D7C793F.5070501@gmail.com> References: <4D7C793F.5070501@gmail.com> Message-ID: <4D7CC170.3020609@pearwood.info> Vineeth Mohan wrote: > Hi, > > How are variables in python passed. By value or by referrence? Neither. What makes you think that value and reference are the only two choices? See this Wikipedia article for a list of at least a dozen different argument passing techniques: http://en.wikipedia.org/wiki/Evaluation_strategy Three months ago I answered a similar question. You could do worse than read this: http://www.mail-archive.com/tutor%40python.org/msg46612.html > Is the following the only way to pass by reference? or is there any > other way To mimic the behaviour of pass-by-reference, it is more common to pass a single-element list: >>> def modify(arg): ... arg[0] = 23 ... >>> var = [42] >>> modify(var) >>> assert var[0] == 23 >>> but using instance attributes also works. -- Steven From yasar11732 at gmail.com Sun Mar 13 20:30:47 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sun, 13 Mar 2011 21:30:47 +0200 Subject: [Tutor] Static Variable in Functions Message-ID: Hi, As I am starting to learn python, I follow dive into python. As I read object section, I came across something called class attributes and data attributes. Because of the reason that class attributes look and behave exactly like static variables in other languages (as I have used in php for example.) That made me think that, there should be static variables for functions too (or lets call them function variables?!?). Doing a little bit research on that, I see that there is no static variable for functions but we can make things behave like that as introduced here: http://www.daniweb.com/software-development/python/threads/33025 def egg(static={"count":0}): static["count"]+=1 return static["count"] print egg() print egg() # >>> 1 # >>> 2 Author of this post says that we can use mutable variables like this as static function variables. I was wondering what are mutable variables and what is rationale behind them. From ryanh.net at gmail.com Sun Mar 13 18:16:14 2011 From: ryanh.net at gmail.com (Ryan Hussain) Date: Sun, 13 Mar 2011 13:16:14 -0400 Subject: [Tutor] defining / calling arguments on a compiled script? Message-ID: Hello, I was wondering if there is a solution to add arguments to a compiled python script, compiled with py2exe? For example I would like to do something such as running my script named "demo.exe -a". With the -a argument I would like to run a function. How can I define arguments in my script? -- /////////////////////////////////// *Ryan Hussain* ryanh at xvisionstudios.com www.xvisionstudios.com www.vimeo.com/xvisionstudios -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sun Mar 13 22:08:26 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 13 Mar 2011 16:08:26 -0500 Subject: [Tutor] defining / calling arguments on a compiled script? In-Reply-To: References: Message-ID: On Sun, Mar 13, 2011 at 12:16 PM, Ryan Hussain wrote: > Hello, > > I was wondering if there is a solution to add arguments to a compiled > python script, compiled with py2exe? For example I would like to do > something such as running my script named "demo.exe -a". With the -a > argument I would like to run a function. How can I define arguments in my > script? Have you tried using sys.argv? http://docs.python.org/library/sys.html#sys.argv HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 13 22:12:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Mar 2011 21:12:43 -0000 Subject: [Tutor] defining / calling arguments on a compiled script? References: Message-ID: "Ryan Hussain" wrote > I was wondering if there is a solution to add arguments to a > compiled python > script, compiled with py2exe? Assuming you still have the original source code then there is no difference to it being compiled with py2exe than if it weren't You just read the command line arguments using sys.argv as usual. If you are not familiar with that read the second half of the "Talking to the User" topic in my tutorial... If OTOH you only have the exe and no access to the source then I suspect you are beat. You can't really change the exe file directly to read arguments (without being a guru level hacker that is! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Mar 13 22:21:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Mar 2011 21:21:26 -0000 Subject: [Tutor] Static Variable in Functions References: Message-ID: "Yasar Arabaci" wrote > exactly like static variables in other languages (as I have used in > php static in other languages usually refers to variables declared on the memory heap rather than the stack, and therefore they retain their value between calls. Python tends to operate at a higher level than that and so does things in other ways. > little bit research on that, I see that there is no static variable > for functions but we can make things behave like that as introduced > here: > > def egg(static={"count":0}): > static["count"]+=1 > return static["count"] Yes, you can do that, see the other post earlier today for more on how parameters work in Python. However, you should also look at generators and the yield keyword. These probably provide a neater way of doing what you seem to want... > Author of this post says that we can use mutable variables like this > as static function variables. I was wondering what are mutable > variables and what is rationale behind them. mutable just means modifiable. You cannot modify a number, string or tuple for example (you need to create new objects) but you can modify a list, dictionary or class instance. The latter are mutable, the former immutable. You must use an immutable object as the key in a dictionary. These are not Python terms they are standard computing science terms. As such you can usually find good explanations on Wikipedia. In general Python uses quite pure computing science concepts and so wikipedia is a good source of background reading on most Python concepts. (eg lambda, generator, iterator, slicing etc) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Mar 14 04:21:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Mar 2011 14:21:46 +1100 Subject: [Tutor] Static Variable in Functions In-Reply-To: References: Message-ID: <4D7D89CA.7050505@pearwood.info> Ya?ar Arabac? wrote: > Author of this post says that we can use mutable variables like this as > static function variables. I was wondering what are mutable variables > and what is rationale behind them. It sounds like you are reading about Python with the mind-set of a C programmer. Python is not C. Python does not have variables in the same sense that C has. Python uses a different assignment model: instead of variables with a fixed type at a fixed memory location, Python's assignment model is that you have objects, and names in namespaces. The distinction is important because you can have names without objects, objects without names, and objects with more than one name. A name without an object is a runtime error, not a compile-time error: >>> spam # A name without an object Traceback (most recent call last): File "", line 1, in NameError: name 'spam' is not defined But an object without a name is perfectly fine. Anonymous objects are very frequent in Python, so frequent that you've probably already used them without realising. This line creates four objects but only one name: >>> t = [42, 'ham and eggs', 1.5] The name 't' is bound to the list object. The objects 42, 'ham and eggs' and 1.5 (an int, a str and a float) are anonymous -- they have no names. But you can give them names at any time: >>> breakfast = t[1] # bind a name to the object in the list >>> n = len(breakfast) # and pass it to a function or you can continue to use them anonymously: >>> n = len(t[1]) It's not clear what "variable" would mean in Python unless it refers to the combination of a name bound to an object. I often use "variable" in that sense myself, but it's a bad habit, because it can confuse people who have an idea of what a variable is that is different from what Python does. In Python, it is *objects* which are either mutable (changeable) or immutable (fixed), not names. All names are mutable in the sense that you can re-bind or delete them: >>> x = 12345 # the name x is bound to the object 12345 >>> x = "two" # and now the name is bound to a different object >>> del x # and now the name x is gone But the objects themselves are inherently either mutable or immutable, regardless of the name. You cannot change the mutability of the object by changing the assignment, only by using a different object. Consider lists and tuples, which are both sequences of objects, but lists are mutable and tuples are not: >>> items = [1, 2, 3] # The list can be changed in place. >>> items[2] = 4 >>> print(items) [1, 2, 4] So "the variable is mutable". But if we re-bind the name to a different object: >>> items = tuple(items) >>> print(items) (1, 2, 4) >>> items[2] = 8 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment "the variable is immutable". Notice that it is the *object* that does not support item assignment. The *name* does not get a say about whether the object is mutable or not: the tuple will always be immutable, no matter what name it is bound to. Most of the common built-in Python objects are immutable: ints floats complex numbers strings (both Unicode and byte strings) tuples bools (True and False) None frozensets while a few are mutable: lists dicts sets Custom types created with the class statement are mutable, unless you take special efforts to make them immutable. For example, the Fraction class is written to be immutable: >>> from fractions import Fraction as F >>> f = F(1, 3) >>> f Fraction(1, 3) >>> f.denominator 3 >>> f.denominator = 5 Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute -- Steven From yasar11732 at gmail.com Mon Mar 14 06:55:43 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Mon, 14 Mar 2011 07:55:43 +0200 Subject: [Tutor] Static Variable in Functions In-Reply-To: <4D7D89CA.7050505@pearwood.info> References: <4D7D89CA.7050505@pearwood.info> Message-ID: Wow. That was a great explanation indeed. Thanks a lot. After reading this, I discovered something like this, and found it pretty insteresting indeed: >>> a=["a"] >>> b=[a] >>> a.append("c") >>> b [['a', 'c']] >>> a.append("d") >>> b [['a', 'c', 'd']] Apperantly, I can change something (which is mutable) inside a list without even touching the list itself :) From alan.gauld at btinternet.com Mon Mar 14 09:56:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Mar 2011 08:56:50 -0000 Subject: [Tutor] Static Variable in Functions References: <4D7D89CA.7050505@pearwood.info> Message-ID: "Yasar Arabaci" wrote > >>> a=["a"] > >>> b=[a] > >>> a.append("c") > >>> b > [['a', 'c']] > > Apperantly, I can change something (which is mutable) inside a list > without even touching the list itself :) But the point is that you *are* touching the list. In this case you have two names referring to the same list. You can modify that list (because it is mutable) via either name, it makes no difference because they both refer to the same list. So a.append() is exactly the same operation as b.append() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From enalicho at gmail.com Mon Mar 14 10:22:26 2011 From: enalicho at gmail.com (Noah Hall) Date: Mon, 14 Mar 2011 09:22:26 +0000 Subject: [Tutor] Static Variable in Functions In-Reply-To: References: <4D7D89CA.7050505@pearwood.info> Message-ID: On Mon, Mar 14, 2011 at 8:56 AM, Alan Gauld wrote: > "Yasar Arabaci" wrote >> Apperantly, I can change something (which is mutable) inside ?a list >> without even touching the list itself :) > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() Actually, in this case it's not - a.append() is the same as b[0].append() ;) From mwlodarczak at gmail.com Mon Mar 14 10:22:43 2011 From: mwlodarczak at gmail.com (Marcin Wlodarczak) Date: Mon, 14 Mar 2011 10:22:43 +0100 Subject: [Tutor] Static Variable in Functions In-Reply-To: References: <4D7D89CA.7050505@pearwood.info> Message-ID: <4D7DDE63.8040403@gmail.com> Alan Gauld wrote: > "Yasar Arabaci" wrote > >> >>> a=["a"] >> >>> b=[a] >> >>> a.append("c") >> >>> b >> [['a', 'c']] >> >> Apperantly, I can change something (which is mutable) inside a list >> without even touching the list itself :) > > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() In this case it is not exactly the same since he said b = [a], not b = a. So b.append('c') would produce [['a'], 'c']. Best, Marcin From andreengels at gmail.com Mon Mar 14 10:23:47 2011 From: andreengels at gmail.com (Andre Engels) Date: Mon, 14 Mar 2011 10:23:47 +0100 Subject: [Tutor] Static Variable in Functions In-Reply-To: References: <4D7D89CA.7050505@pearwood.info> Message-ID: On Mon, Mar 14, 2011 at 9:56 AM, Alan Gauld wrote: > "Yasar Arabaci" wrote > >> >>> a=["a"] >> >>> b=[a] >> >>> a.append("c") >> >>> b >> [['a', 'c']] >> >> Apperantly, I can change something (which is mutable) inside ?a list >> without even touching the list itself :) > > But the point is that you *are* touching the list. > In this case you have two names referring to the same list. > You can modify that list (because it is mutable) via either name, it > makes no difference because they both refer to the same list. > > So a.append() is exactly the same operation as b.append() No, they are not the same list. b is (a name of) a list with one element, that one element being the list (denoted by) a. That's not the same as a itself. -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Mon Mar 14 11:15:16 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 14 Mar 2011 10:15:16 +0000 (GMT) Subject: [Tutor] Static Variable in Functions In-Reply-To: References: <4D7D89CA.7050505@pearwood.info> Message-ID: <380486.78018.qm@web86704.mail.ird.yahoo.com> Apologies to all, I didn't notice the [] around a. But the basic point remains that the list that he is appending to is the same list as b refers to, albeit indirectly. He is still "touching" the list. Although not directly modifying the list to which b refers, since it still only holds one member, the list to which a refers.... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Original Message ---- > From: Andre Engels > To: Alan Gauld > Cc: tutor at python.org > Sent: Monday, 14 March, 2011 9:23:47 > Subject: Re: [Tutor] Static Variable in Functions > > On Mon, Mar 14, 2011 at 9:56 AM, Alan Gauld wrote: > > "Yasar Arabaci" wrote > > > >> >>> a=["a"] > >> >>> b=[a] > >> >>> a.append("c") > >> >>> b > >> [['a', 'c']] > >> > >> Apperantly, I can change something (which is mutable) inside a list > >> without even touching the list itself :) > > > > But the point is that you *are* touching the list. > > In this case you have two names referring to the same list. > > You can modify that list (because it is mutable) via either name, it > > makes no difference because they both refer to the same list. > > > > So a.append() is exactly the same operation as b.append() > > No, they are not the same list. b is (a name of) a list with one > element, that one element being the list (denoted by) a. That's not > the same as a itself. > > -- > Andr? Engels, andreengels at gmail.com > From plcrawford at crimson.ua.edu Mon Mar 14 20:08:30 2011 From: plcrawford at crimson.ua.edu (paige crawford) Date: Mon, 14 Mar 2011 14:08:30 -0500 Subject: [Tutor] Reading in data files Message-ID: Hey, How do I read in a data file that has comments then remove the comments to get to the numbers? The numbers in the data file needs to be read into a list. There are also comments next to the numbers. The file looks something like this # DO NOT MODIFY # # This file is for the eyebrows # # Read in these numbers # # # 3 # This is the amount of items in each list, m 30 # number 1 10 # number 3 -110 # number 9 39 40 30 48 390 # extra data -------------- next part -------------- An HTML attachment was scrubbed... URL: From kongfranon at gmail.com Mon Mar 14 20:41:19 2011 From: kongfranon at gmail.com (Mike Franon) Date: Mon, 14 Mar 2011 15:41:19 -0400 Subject: [Tutor] multiple if and or statement Message-ID: HI, I had a question, when running this small snippet of test code: a = ['test1', 'flag', 'monday'] for i in a: if i == 'test1' or 'test2': print 'true' It always prints true $ ./testing.py true true true I know I am missing something, but in reality it should only print true once correct? Thanks in advance From kb1pkl at aim.com Mon Mar 14 20:53:15 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 14 Mar 2011 15:53:15 -0400 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: <4D7E722B.8050004@aim.com> On 03/14/2011 03:41 PM, Mike Franon wrote: > HI, > > I had a question, when running this small snippet of test code: > > > > a = ['test1', 'flag', 'monday'] > > for i in a: > if i == 'test1' or 'test2': if i == 'test1' or i == 'test2' > print 'true' > I know I am missing something, but in reality it should only print > true once correct? You are missing something. Before, you're simply testing the existence of 'test2'. And since 'test2' is an immediate value (so to speak), it always exists. -- Corey Richardson From adam.jtm30 at gmail.com Mon Mar 14 20:54:54 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Mon, 14 Mar 2011 19:54:54 +0000 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: <4D7E728E.7010108@gmail.com> On 14/03/11 19:41, Mike Franon wrote: > HI, > > I had a question, when running this small snippet of test code: > > > > a = ['test1', 'flag', 'monday'] > > for i in a: > if i == 'test1' or 'test2': > print 'true' > > > It always prints true > > > $ ./testing.py > true > true > true > > > I know I am missing something, but in reality it should only print > true once correct? Any string that isn't blank ie '' is true. In your test you've asked whether i == 'test1' is true or 'test2' is true not i == 'test2' is true. I hope that's not too confusing, I can make it clearer if you're having a problem. Adam. From marc.tompkins at gmail.com Mon Mar 14 20:57:24 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Mar 2011 12:57:24 -0700 Subject: [Tutor] Reading in data files In-Reply-To: References: Message-ID: On Mon, Mar 14, 2011 at 12:08 PM, paige crawford wrote: > Hey, > > > How do I read in a data file that has comments then remove the comments to > get to the numbers? The numbers in the data file needs to be read into a > list. There are also comments next to the numbers. The file looks something > like this > > # DO NOT MODIFY > # > # This file is for the eyebrows > # > # Read in these numbers > # > # > # > > 3 # This is the amount of items in each list, m > > 30 # number 1 > 10 # number 3 > -110 # number 9 > > 39 40 30 > > 48 390 # extra data > > Those lines with multiple numbers (e.g. "39 40 30") - do you want to add 39, 40, and 30 to the list, or "39 40 30"? If you want to add the whole line as a unit, then just read each line, split() at the #, strip() the first part, and add it to the list. If you want them to be separate numbers, then read each line, split() at the #, split() the first part by spaces, and add each item to the list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 14 21:00:35 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Mar 2011 13:00:35 -0700 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: On Mon, Mar 14, 2011 at 12:41 PM, Mike Franon wrote: > HI, > > I had a question, when running this small snippet of test code: > > > > a = ['test1', 'flag', 'monday'] > > for i in a: > if i == 'test1' or 'test2': > print 'true' > > > It always prints true > > > $ ./testing.py > true > true > true > > > I know I am missing something, but in reality it should only print > true once correct? > > No. The string 'test2' (actually, ALL non-empty strings) evaluates to True, so your condition will always be met. Try this: > if (i == 'test1') or (i == 'test2'): > or: > if i in ('test1', 'test2'): > -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 14 21:05:45 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Mar 2011 13:05:45 -0700 Subject: [Tutor] Reading in data files In-Reply-To: References: Message-ID: On Mon, Mar 14, 2011 at 1:02 PM, Marc Tompkins wrote: > On Mon, Mar 14, 2011 at 12:59 PM, paige crawford < > plcrawford at crimson.ua.edu> wrote: > >> How do I split them by spaces? >> >> Google "Python split". > > That might have been a bit abrupt... but (in general) the Tutor list is happy to help point you in the right direction, not do your homework for you. I even gave you a big hint by writing it as split() in my original message. (It's a string function.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kongfranon at gmail.com Mon Mar 14 21:13:41 2011 From: kongfranon at gmail.com (Mike Franon) Date: Mon, 14 Mar 2011 16:13:41 -0400 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: Thank you everyone who responded, very fast responses I am impressed. OK now I see where I went wrong and had to do if (i == 'test1') or (i=='test2'): I guess I was thinking if I do a = ['test1', 'flag', 'monday'] for i in a: It would check each item in the list one at a time like a loop I was thinking, so the first time it would test for 'test1', and the second time it would test for 'flag', did not realize it would test the entire list all at once. On Mon, Mar 14, 2011 at 4:00 PM, Marc Tompkins wrote: > On Mon, Mar 14, 2011 at 12:41 PM, Mike Franon wrote: >> >> HI, >> >> I had a question, when running this small snippet of test code: >> >> >> >> a = ['test1', 'flag', 'monday'] >> >> for i in a: >> ? ?if i == 'test1' or 'test2': >> ? ? ? print 'true' >> >> >> It always prints true >> >> >> $ ./testing.py >> true >> true >> true >> >> >> I know I am missing something, but in reality it should only print >> true once correct? >> > No.? The string 'test2' (actually, ALL non-empty strings) evaluates to True, > so your condition will always be met. > Try this: >> >> if (i == 'test1') or (i == 'test2'): > > or: >> >> if i in ('test1', 'test2'): > > > From emile at fenx.com Mon Mar 14 21:32:01 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 14 Mar 2011 13:32:01 -0700 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: On 3/14/2011 1:13 PM Mike Franon said... > Thank you everyone who responded, very fast responses I am impressed. > > OK now I see where I went wrong Well, no, I don't think so. Your first test was: if i=='test1' or 'test2': which evaluates as true if _either_ i=='test1' _or_ 'test2' so, the first test is i=='test1' and the second test if simply 'test2'. Try the following: if 'test2': print "non-empty strings evaluate as true" if not "": print "the not of an empty string evaluates true" HTH, Emile > and had to do > > > if (i == 'test1') or (i=='test2'): > > > I guess I was thinking if I do > > > a = ['test1', 'flag', 'monday'] > for i in a: > > It would check each item in the list one at a time like a loop I was > thinking, so the first time it would test for 'test1', and the second > time it would test for 'flag', did not realize it would test the > entire list all at once. From bgailer at gmail.com Mon Mar 14 21:53:59 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Mar 2011 15:53:59 -0500 Subject: [Tutor] multiple if and or statement In-Reply-To: References: Message-ID: <4D7E8067.2080106@gmail.com> On 3/14/2011 3:13 PM, Mike Franon wrote: > Thank you everyone who responded, very fast responses I am impressed. > > OK now I see where I went wrong and had to do > > > if (i == 'test1') or (i=='test2'): > > > I guess I was thinking if I do > > > a = ['test1', 'flag', 'monday'] > for i in a: > > It would check each item in the list one at a time like a loop I was > thinking, so the first time it would test for 'test1', and the second > time it would test for 'flag', That is correct. Each iteration of the loop assigns one list element to a. if (i == 'test1') or (i=='test2'): is one way to do what you want. Another is if i in ('test1', 'test2'): Instead of a tuple of values you could also provide a list, a set or a dictionary. -- Bob Gailer 919-636-4239 Chapel Hill NC From yasar11732 at gmail.com Mon Mar 14 22:15:53 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Mon, 14 Mar 2011 23:15:53 +0200 Subject: [Tutor] How to use a str object, to find the class in exact name? Message-ID: Hi I am trying to do something like this: #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] class calculate: def bundle(self): print __class__ command_dispatcher() What I need this to do is, take a raw input, split it into parts and execute class args[0] and method args[1] using args[2:] as an argument. But what I have done isn't working. This is the error I get: :!/home/yasar/best_buy/main.py >>>calculate bundle Traceback (most recent call last): File "/home/yasar/best_buy/main.py", line 10, in command_dispatcher() File "/home/yasar/best_buy/main.py", line 6, in command_dispatcher args[0].args[1] AttributeError: 'str' object has no attribute 'args' shell returned 1 From ramit.prasad at jpmchase.com Mon Mar 14 22:38:16 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Mon, 14 Mar 2011 17:38:16 -0400 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF98DABA3@EMARC112VS01.exchad.jpmchase.net> Take a look at: http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Yasar Arabaci Sent: Monday, March 14, 2011 4:16 PM To: tutor at python.org Subject: [Tutor] How to use a str object, to find the class in exact name? Hi I am trying to do something like this: #!/usr/bin/env python def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") args[0].args[1] class calculate: def bundle(self): print __class__ command_dispatcher() What I need this to do is, take a raw input, split it into parts and execute class args[0] and method args[1] using args[2:] as an argument. But what I have done isn't working. This is the error I get: :!/home/yasar/best_buy/main.py >>>calculate bundle Traceback (most recent call last): File "/home/yasar/best_buy/main.py", line 10, in command_dispatcher() File "/home/yasar/best_buy/main.py", line 6, in command_dispatcher args[0].args[1] AttributeError: 'str' object has no attribute 'args' shell returned 1 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From steve at pearwood.info Mon Mar 14 23:14:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Mar 2011 09:14:09 +1100 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: Message-ID: <4D7E9331.7020202@pearwood.info> Ya?ar Arabac? wrote: > Hi > > I am trying to do something like this: If you are trying to write a mini-language, the ``cmd`` and ``shlex`` modules in the standard library may be useful to you. > #!/usr/bin/env python > def command_dispatcher(): > "Takes comman line arguments and executes regardin method" > command = raw_input(">>>") > args = command.split(" ") > args[0].args[1] The error you get tells you exactly what is wrong: AttributeError: 'str' object has no attribute 'args' When you split the line, you get a list of strings. You extract the first string using args[0], and then look up the attribute "args" on that string, and finally look up the second element of that result. But strings don't have an attribute called args. Try this instead: getattr(args[0], args[1]) When you do that, you'll run into a bunch of new and exciting errors, starting with the fact that nothing appears to happen. Try it and see. What you will eventually need to do is: * create a class instance and store it somewhere * call the method on the class instance * print its output none of which is yet done by your script. So far, all it does it try to look up a method on a class, then throw the result away without doing anything :) > class calculate: > def bundle(self): > print __class__ > command_dispatcher() calculate.bundle won't do anything except fail, because __class__ is not a local variable. It's better to have the methods return a result, rather than print, and then have the command_dispatcher responsible for printing it. That lets you chain methods to make more powerful functions. Good luck, and have fun! -- Steven From steve at pearwood.info Mon Mar 14 23:23:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Mar 2011 09:23:28 +1100 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF98DABA3@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF98DABA3@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D7E9560.7030002@pearwood.info> Prasad, Ramit wrote: > Take a look at: > http://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python And then please don't do it. eval and exec should be treated as the last resort, and then only if you really know what you are doing. They are slow, and dangerous, especially if there is *any* chance that the input strings could be coming from an untrusted user. -- Steven From steve at pearwood.info Mon Mar 14 23:37:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Mar 2011 09:37:28 +1100 Subject: [Tutor] Reading in data files In-Reply-To: References: Message-ID: <4D7E98A8.2030508@pearwood.info> Marc Tompkins wrote: > On Mon, Mar 14, 2011 at 1:02 PM, Marc Tompkins wrote: > >> On Mon, Mar 14, 2011 at 12:59 PM, paige crawford < >> plcrawford at crimson.ua.edu> wrote: >> >>> How do I split them by spaces? >>> >>> Google "Python split". >> That might have been a bit abrupt... but (in general) the Tutor list is > happy to help point you in the right direction, not do your homework for > you. I even gave you a big hint by writing it as split() in my original > message. (It's a string function.) That's a bit harsh. Telling somebody about the existence and use of a built-in function isn't "doing your homework for you" unless the homework is "Write down what the string.split method does", in which case, the teacher is too lazy for words :) Paige, you are reading lines one at a time from a file. Each line is a string. You can split the strings on any delimiter using the split method: >>> mystr = "breakfast = spam and eggs -- spam spam spam glorious SPAM!!!" >>> mystr.split("--") ['breakfast = spam and eggs ', ' spam spam spam glorious SPAM!!!'] >>> mystr.split("=") ['breakfast ', ' spam and eggs -- spam spam spam glorious SPAM!!!'] The result is a list of substrings. You can then assign them to new variables and process them further. You may also find the string strip() method useful for getting rid of spaces around substrings. You can also look up functions and methods in the interactive interpreter using the help() function. If your Python is configured correctly, at the Python prompt, you can say: help() to start the help system, or go directly to a particular method or function, e.g.: help(len) # help about the ``len`` built-in function help(''.split) # help about the string split method Notice that you don't include parentheses after the function or method. -- Steven From yasar11732 at gmail.com Mon Mar 14 23:41:00 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Tue, 15 Mar 2011 00:41:00 +0200 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: <4D7E9331.7020202@pearwood.info> References: <4D7E9331.7020202@pearwood.info> Message-ID: Before being able to see 3rd answer, I did something like this and it worked for me: #!/usr/bin/env python # -*- encoding:utf-8 -*- def command_dispatcher(): "Takes comman line arguments and executes regardin method" command = raw_input(">>>") args = command.split(" ") query_string = ".".join(args[0:2]) method_args = ",".join(args[2:]) try: exec query_string+"("+method_args+")" except NameError: print "You are trying to get somethin that is not exist!" class calculate: @staticmethod def bundle(): print "your best bundle is -->" command_dispatcher() But after reading 3rd answer regarding the danger of exec, I had my doubts, Now I will try to implement what second person said about getattr, and will return here with result. And What I want to do is a small economy application. It will work this way: user add a product name, rate how much it like it over 10, and enter its price. [repeated as many times as wanted] user will enter h(is|er) budget. user will use "calcute bundle" to show much of each product s?he should buy user will repeat any step as long as s?he likes. 15-03-2011 00:14, Steven D'Aprano yazm??: > Ya?ar Arabac? wrote: >> Hi >> >> I am trying to do something like this: > > > If you are trying to write a mini-language, the ``cmd`` and ``shlex`` > modules in the standard library may be useful to you. > > >> #!/usr/bin/env python >> def command_dispatcher(): >> "Takes comman line arguments and executes regardin method" >> command = raw_input(">>>") >> args = command.split(" ") >> args[0].args[1] > > > The error you get tells you exactly what is wrong: > > AttributeError: 'str' object has no attribute 'args' > > > When you split the line, you get a list of strings. You extract the > first string using args[0], and then look up the attribute "args" on > that string, and finally look up the second element of that result. But > strings don't have an attribute called args. > > Try this instead: > > getattr(args[0], args[1]) > > When you do that, you'll run into a bunch of new and exciting errors, > starting with the fact that nothing appears to happen. Try it and see. > > What you will eventually need to do is: > > * create a class instance and store it somewhere > * call the method on the class instance > * print its output > > none of which is yet done by your script. So far, all it does it try to > look up a method on a class, then throw the result away without doing > anything :) > > >> class calculate: >> def bundle(self): >> print __class__ >> command_dispatcher() > > > calculate.bundle won't do anything except fail, because __class__ is not > a local variable. > > It's better to have the methods return a result, rather than print, and > then have the command_dispatcher responsible for printing it. That lets > you chain methods to make more powerful functions. > > > Good luck, and have fun! > > > From steve at pearwood.info Mon Mar 14 23:55:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Mar 2011 09:55:12 +1100 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: <4D7E9331.7020202@pearwood.info> Message-ID: <4D7E9CD0.2040700@pearwood.info> Ya?ar Arabac? wrote: > And What I want to do is a small economy application. It will work this > way: > > user add a product name, rate how much it like it over 10, and enter its > price. > [repeated as many times as wanted] > > user will enter h(is|er) budget. > > user will use "calcute bundle" to show much of each product s?he should buy > > user will repeat any step as long as s?he likes. My advice is not to mix the backend calculation engine with the frontend user interface in the same code. Keep them separate. So you should write your classes and functions to: * store products and prices * calculate best buys for a budget * etc. And then have a separate function for the user interface, which handles: * input and output to the user * converting the user's text input to numbers, products, etc. * calling the calculation functions * printing the results (The frontend and backend can be in the same file, but they should be separate functions or classes.) At the moment, your code combines calculation with user-interface, which is a poor design: class calculate: @staticmethod def bundle(): print "your best bundle is -->" You have the class responsible for calculating the bundle also responsible for displaying it to the user. It is better to separate those two functions, and have one class for calculating the bundle and returning it (not printing it!) and another function or class responsible for calling the calculate class with the user's input, and displaying the output to the user. This will let you more easily change the user-interface, without needing to change the engine. Want to put your application in a GUI, or on a website? Change the user-interface parts, not the engine. Hope this helps! -- Steven From yasar11732 at gmail.com Tue Mar 15 02:49:01 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Tue, 15 Mar 2011 03:49:01 +0200 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: <4D7E9331.7020202@pearwood.info> Message-ID: As I try to implement things with getattr, I am getting a really strange error. This is my file: #!/usr/bin/env python # -*- encoding:utf-8 -*- class global_variables: "Holds class attributes, so that other classes can share them" products = 0 best_bundle = [] class dispatcher: def GetMethod(self,class_name,method_name): """This method first finds a class if desired classexists. Then, instansites it, and returns a reference to desired method of the instance it created. """ from sys import modules module = modules[self.__module__] if hasattr(module,class_name): print "#debug : hasattr is true" cls = getattr(module,class_name) else: print "#debug : hasattr is false" return None "if we get a valid class, lets instantie it" if cls: a=cls() else: return None return hasattr(a,method_name) and getattr(a,method_name) or None def dispatch_command(self): """Gets command from user, finds appropriate Class/method to run and then runs it. Beware of the fact that, to be able to successfully run the method, method should take exactly two arguments, arg 1: instance of class which method resides (e.g. self) arg 2: list of other needed variables list of other variables can be used to get as many variables as possible """ command = raw_input(">>>") args = command.split(" ") if len(args) < 2: return None method = self.GetMethod(args[0],args[1]) return method and method(args[2:]) or None class calculate(global_variables): def bundle(self,args): print "your best bundle is -->" a = dispatcher() a.dispatch_command() I wanted to see what happens when someone gives an nonexistent function. But when I put a b, it gives me error, when I put c d it doesn't. I don't have either a or c classes, but a somehow causes problems :S This is what I did: yasar at yasar-laptop:~/best_buy> ./main.py >>>a b #debug : hasattr is true Traceback (most recent call last): File "./main.py", line 57, in a.dispatch_command() File "./main.py", line 44, in dispatch_command method = self.GetMethod(args[0],args[1]) File "./main.py", line 25, in GetMethod a=cls() AttributeError: dispatcher instance has no __call__ method yasar at yasar-laptop:~/best_buy> ./main.py >>>c d #debug : hasattr is false From amonroe at columbus.rr.com Tue Mar 15 02:54:36 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 14 Mar 2011 21:54:36 -0400 Subject: [Tutor] Simplistic drive simulation In-Reply-To: References: <471493984816.20110313015151@columbus.rr.com> Message-ID: <181648949924.20110314215436@columbus.rr.com> > "R. Alan Monroe" wrote >> Neither of these seem like they'd scale very well (say, up to the >> resolution of your screen, with one block per pixel). The end goal >> is >> just a basic do-nothing light show that simulates >> fragmentation/defragmentation as eye candy. > For that purpose the basic style you are using will be adequate. > You are only talking about 2-5 million pixels at most on > typical monitors. Usually more like 1.5 million on a laptop. > And you are not too worried about speed, in fact too fast a > display would just be wasted as most chanmges would > never be seen! Here's my first cut. One thing that surprised me is that none of the earlier generation (single and double digit filenames) ever survive to the 80th generation. My expectation was that I would end up with a wider range of generations in the end. Alan -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: defrag004.py URL: From bgailer at gmail.com Tue Mar 15 04:39:37 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Mar 2011 22:39:37 -0500 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: <4D7E9331.7020202@pearwood.info> Message-ID: <4D7EDF79.6060300@gmail.com> On 3/14/2011 8:49 PM, Ya?ar Arabac? wrote: > As I try to implement things with getattr, I am getting a really > strange error. This is my file: Various interspersed comments: > > #!/usr/bin/env python > # -*- encoding:utf-8 -*- > class global_variables: It is customary to start class names with an uppercase letter > "Holds class attributes, so that other classes can share them" > products = 0 > best_bundle = [] > class dispatcher: > def GetMethod(self,class_name,method_name): > It is customary to start method names with a lowercase letter > > """This method first finds a class if desired classexists. > Then, instansites it, and returns a reference to desired > method of > the instance it created. > """ > > from sys import modules It is customary to place import statements close to the top of the program, not in any class or function. > module = modules[self.__module__] > if hasattr(module,class_name): What are the module's attributes? insert print dir(module) to see ALL the attributes. > print "#debug : hasattr is true" > cls = getattr(module,class_name) > else: > print "#debug : hasattr is false" > return None > > "if we get a valid class, lets instantie it" > if cls: > a=cls() > else: > return None > return hasattr(a,method_name) and getattr(a,method_name) or None > > def dispatch_command(self): > """Gets command from user, finds appropriate Class/method to run > and then runs it. Beware of the fact that, to be able to > successfully > run the method, method should take exactly two arguments, > arg 1: instance of class which method resides (e.g. self) > arg 2: list of other needed variables > > list of other variables can be used to get as many variables > as possible > """ > > command = raw_input(">>>") > args = command.split(" ") > if len(args) < 2: > return None > method = self.GetMethod(args[0],args[1]) > return method and method(args[2:]) or None > > class calculate(global_variables): > def bundle(self,args): > print "your best bundle is -->" > > a = dispatcher() > a.dispatch_command() Alternative 1 - put all the user-callable class definitions inside a Container class (or whatever name you want) - then use getattr on the Container class class Container: class Calculate(global_variables): def bundle(self,args): print "your best bundle is -->" Alternative 2 - use the following to create a dictionary of classes in which you look up the desired class by name import sys, inspect thisModule = sys.modules[__name__] classDict = dict((name.lower(), value) for name, value in inspect.getmembers(thisModule, inspect.isclass)) ... cls = classDict[className] Alternative 3 cls = getattr(module,class_name) try: if issubclass(cls, global_variables) a=cls() except TypeError: pass > > I wanted to see what happens when someone gives an nonexistent > function. But when I put a b, it gives me error, when I put c d it > doesn't. I don't have either a or c classes, but a somehow causes > problems :S This is what I did: > > yasar at yasar-laptop:~/best_buy> ./main.py > >>>a b > #debug : hasattr is true > Traceback (most recent call last): > File "./main.py", line 57, in > a.dispatch_command() > File "./main.py", line 44, in dispatch_command > method = self.GetMethod(args[0],args[1]) > File "./main.py", line 25, in GetMethod > a=cls() > AttributeError: dispatcher instance has no __call__ method The error tells you what a is. Isn't it obvious now? Remember to read and understand such messages. > yasar at yasar-laptop:~/best_buy> ./main.py > >>>c d > #debug : hasattr is false > -- Bob Gailer 919-636-4239 Chapel Hill NC From freethinker at pobox.com Tue Mar 15 08:51:43 2011 From: freethinker at pobox.com (Tom Zych) Date: Tue, 15 Mar 2011 03:51:43 -0400 Subject: [Tutor] Static Variable in Functions In-Reply-To: <4D7D89CA.7050505@pearwood.info> References: <4D7D89CA.7050505@pearwood.info> Message-ID: <4D7F1A8F.2000103@pobox.com> Steven D'Aprano wrote: > Most of the common built-in Python objects are immutable: > ... > while a few are mutable: > > lists > dicts > sets Also, bytearrays. -- Tom Zych / freethinker at pobox.com From yasar11732 at gmail.com Tue Mar 15 15:14:42 2011 From: yasar11732 at gmail.com (=?UTF-8?B?WWHFn2FyIEFyYWJhY8Sx?=) Date: Tue, 15 Mar 2011 16:14:42 +0200 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: <4D7EDF79.6060300@gmail.com> References: <4D7E9331.7020202@pearwood.info> <4D7EDF79.6060300@gmail.com> Message-ID: Thanks for excellent explanations. I almost got this working. I just have one more problem, that is: When user enter incorrect number of arguments for a method, I naturally get a type error. I could probably fix that with try and catch, but that is not very explanatory to the user. Is there a way to get expected number of arguments to the method so that I can generate an error report? You can find my codes as attachment. I have split them into two files. In order to run it, you should run cli.py like: python cli.py Thanks in advance, Ya?ar Arabac? 15-03-2011 05:39, bob gailer yazm??: > On 3/14/2011 8:49 PM, Ya?ar Arabac? wrote: >> As I try to implement things with getattr, I am getting a really >> strange error. This is my file: > > Various interspersed comments: >> >> #!/usr/bin/env python >> # -*- encoding:utf-8 -*- >> class global_variables: > > It is customary to start class names with an uppercase letter > >> "Holds class attributes, so that other classes can share them" >> products = 0 >> best_bundle = [] >> class dispatcher: >> def GetMethod(self,class_name,method_name): >> > It is customary to start method names with a lowercase letter >> >> """This method first finds a class if desired classexists. >> Then, instansites it, and returns a reference to desired method of >> the instance it created. >> """ >> >> from sys import modules > > It is customary to place import statements close to the top of the > program, not in any class or function. > >> module = modules[self.__module__] >> if hasattr(module,class_name): > > What are the module's attributes? > insert print dir(module) to see ALL the attributes. > >> print "#debug : hasattr is true" >> cls = getattr(module,class_name) >> else: >> print "#debug : hasattr is false" >> return None >> >> "if we get a valid class, lets instantie it" >> if cls: >> a=cls() >> else: >> return None >> return hasattr(a,method_name) and getattr(a,method_name) or None >> >> def dispatch_command(self): >> """Gets command from user, finds appropriate Class/method to run >> and then runs it. Beware of the fact that, to be able to successfully >> run the method, method should take exactly two arguments, >> arg 1: instance of class which method resides (e.g. self) >> arg 2: list of other needed variables >> >> list of other variables can be used to get as many variables as possible >> """ >> >> command = raw_input(">>>") >> args = command.split(" ") >> if len(args) < 2: >> return None >> method = self.GetMethod(args[0],args[1]) >> return method and method(args[2:]) or None >> >> class calculate(global_variables): >> def bundle(self,args): >> print "your best bundle is -->" >> >> a = dispatcher() >> a.dispatch_command() > > Alternative 1 > - put all the user-callable class definitions inside a Container class > (or whatever name you want) > - then use getattr on the Container class > class Container: > class Calculate(global_variables): > def bundle(self,args): > print "your best bundle is -->" > > Alternative 2 - use the following to create a dictionary of classes in > which you look up the desired class by name > import sys, inspect > thisModule = sys.modules[__name__] > classDict = dict((name.lower(), value) for name, value in > inspect.getmembers(thisModule, inspect.isclass)) > ... > cls = classDict[className] > > Alternative 3 > cls = getattr(module,class_name) > try: > if issubclass(cls, global_variables) > a=cls() > except TypeError: > pass >> >> I wanted to see what happens when someone gives an nonexistent >> function. But when I put a b, it gives me error, when I put c d it >> doesn't. I don't have either a or c classes, but a somehow causes >> problems :S This is what I did: >> >> yasar at yasar-laptop:~/best_buy> ./main.py >> >>>a b >> #debug : hasattr is true >> Traceback (most recent call last): >> File "./main.py", line 57, in >> a.dispatch_command() >> File "./main.py", line 44, in dispatch_command >> method = self.GetMethod(args[0],args[1]) >> File "./main.py", line 25, in GetMethod >> a=cls() >> AttributeError: dispatcher instance has no __call__ method > > The error tells you what a is. Isn't it obvious now? Remember to read > and understand such messages. > >> yasar at yasar-laptop:~/best_buy> ./main.py >> >>>c d >> #debug : hasattr is false >> > > -------------- next part -------------- A non-text attachment was scrubbed... Name: cli.py Type: text/x-python Size: 3335 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: main.py Type: text/x-python Size: 703 bytes Desc: not available URL: From japhy at pearachute.com Tue Mar 15 16:16:53 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Tue, 15 Mar 2011 11:16:53 -0400 Subject: [Tutor] How to use a str object, to find the class in exact name? In-Reply-To: References: <4D7E9331.7020202@pearwood.info> <4D7EDF79.6060300@gmail.com> Message-ID: I hate to jump on this one a little late, but even getattr() is kind of ghetto (though exec/eval is worse ;). For setting up shell scripts or CLIs, the usual route is the optparse module. - Japhy 2011/3/15 Ya?ar Arabac? : > Thanks for excellent explanations. I almost got this working. I just have > one more problem, that is: > > When user enter incorrect number of arguments for a method, I naturally get > a type error. I could probably fix that with try and catch, but that is not > very explanatory to the user. Is there a way to get expected number of > arguments to the method so that I can generate an error report? > > You can find my codes as attachment. I have split them into two files. In > order to run it, you should run cli.py like: > > python cli.py > > Thanks in advance, > > Ya?ar Arabac? > > 15-03-2011 05:39, bob gailer yazm??: >> >> On 3/14/2011 8:49 PM, Ya?ar Arabac? wrote: >>> >>> As I try to implement things with getattr, I am getting a really >>> strange error. This is my file: >> >> Various interspersed comments: >>> >>> #!/usr/bin/env python >>> # -*- encoding:utf-8 -*- >>> class global_variables: >> >> It is customary to start class names with an uppercase letter >> >>> "Holds class attributes, so that other classes can share them" >>> products = 0 >>> best_bundle = [] >>> class dispatcher: >>> def GetMethod(self,class_name,method_name): >>> >> It is customary to start method names with a lowercase letter >>> >>> """This method first finds a class if desired classexists. >>> Then, instansites it, and returns a reference to desired method of >>> the instance it created. >>> """ >>> >>> from sys import modules >> >> It is customary to place import statements close to the top of the >> program, not in any class or function. >> >>> module = modules[self.__module__] >>> if hasattr(module,class_name): >> >> What are the module's attributes? >> insert print dir(module) to see ALL the attributes. >> >>> print "#debug : hasattr is true" >>> cls = getattr(module,class_name) >>> else: >>> print "#debug : hasattr is false" >>> return None >>> >>> "if we get a valid class, lets instantie it" >>> if cls: >>> a=cls() >>> else: >>> return None >>> return hasattr(a,method_name) and getattr(a,method_name) or None >>> >>> def dispatch_command(self): >>> """Gets command from user, finds appropriate Class/method to run >>> and then runs it. Beware of the fact that, to be able to successfully >>> run the method, method should take exactly two arguments, >>> arg 1: instance of class which method resides (e.g. self) >>> arg 2: list of other needed variables >>> >>> list of other variables can be used to get as many variables as possible >>> """ >>> >>> command = raw_input(">>>") >>> args = command.split(" ") >>> if len(args) < 2: >>> return None >>> method = self.GetMethod(args[0],args[1]) >>> return method and method(args[2:]) or None >>> >>> class calculate(global_variables): >>> def bundle(self,args): >>> print "your best bundle is -->" >>> >>> a = dispatcher() >>> a.dispatch_command() >> >> Alternative 1 >> - put all the user-callable class definitions inside a Container class >> (or whatever name you want) >> - then use getattr on the Container class >> class Container: >> class Calculate(global_variables): >> def bundle(self,args): >> print "your best bundle is -->" >> >> Alternative 2 - use the following to create a dictionary of classes in >> which you look up the desired class by name >> import sys, inspect >> thisModule = sys.modules[__name__] >> classDict = dict((name.lower(), value) for name, value in >> inspect.getmembers(thisModule, inspect.isclass)) >> ... >> cls = classDict[className] >> >> Alternative 3 >> cls = getattr(module,class_name) >> try: >> if issubclass(cls, global_variables) >> a=cls() >> except TypeError: >> pass >>> >>> I wanted to see what happens when someone gives an nonexistent >>> function. But when I put a b, it gives me error, when I put c d it >>> doesn't. I don't have either a or c classes, but a somehow causes >>> problems :S This is what I did: >>> >>> yasar at yasar-laptop:~/best_buy> ./main.py >>> >>>a b >>> #debug : hasattr is true >>> Traceback (most recent call last): >>> File "./main.py", line 57, in >>> a.dispatch_command() >>> File "./main.py", line 44, in dispatch_command >>> method = self.GetMethod(args[0],args[1]) >>> File "./main.py", line 25, in GetMethod >>> a=cls() >>> AttributeError: dispatcher instance has no __call__ method >> >> The error tells you what a is. Isn't it obvious now? Remember to read >> and understand such messages. >> >>> yasar at yasar-laptop:~/best_buy> ./main.py >>> >>>c d >>> #debug : hasattr is false >>> >> >> > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From carlarjenkins at yahoo.com Wed Mar 16 01:00:51 2011 From: carlarjenkins at yahoo.com (Carla Jenkins) Date: Tue, 15 Mar 2011 17:00:51 -0700 (PDT) Subject: [Tutor] Processing Financial Calculations using Python Message-ID: <914467.65806.qm@web31503.mail.mud.yahoo.com> Are there specific Python commands to process present value, future value and net present value?? Thanks. ? Sincerely, Carla Jenkins -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Mar 16 01:54:21 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 15 Mar 2011 19:54:21 -0500 Subject: [Tutor] Processing Financial Calculations using Python In-Reply-To: <914467.65806.qm@web31503.mail.mud.yahoo.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> Message-ID: On Tue, Mar 15, 2011 at 7:00 PM, Carla Jenkins wrote: > Are there specific Python commands to process present value, future value > and net present value? Thanks. > http://tinyurl.com/4j5exao http://tinyurl.com/67x2to8 HTH, Wayne > > Sincerely, > Carla Jenkins > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Mar 16 02:00:44 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 15 Mar 2011 17:00:44 -0800 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <914467.65806.qm@web31503.mail.mud.yahoo.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> Message-ID: <20110316010044.GB1827@johnsons-web.com> What is the difference between using hasattr(object, name) and name in dir(object) ? TIA -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From waynejwerner at gmail.com Wed Mar 16 02:24:27 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 15 Mar 2011 20:24:27 -0500 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <20110316010044.GB1827@johnsons-web.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> <20110316010044.GB1827@johnsons-web.com> Message-ID: On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson wrote: > What is the difference between using > hasattr(object, name) > and > name in dir(object) > hasattr is basically try: object.name return True except AttributeError: return False while "name in dir(object)" is (AFAIK) more like: for attr in dir(object): if name == attr: return True return False However, rare is the occasion that you should use either of these. If you're doing something like: if hasattr(myobj, 'something'): myobj.something() else: print "blah blah blah" then what you really should be doing is: try: myobj.something() except AttributeError: print "blah blah blah" because 1) you avoid the overhead of an extra(?) try-except block, 2) in Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You shouldn't inspect an object to find out what it can do, you should just try it and then handle failures appropriately (at least that's what I've been told). YMMV, objects in mirror are closer than they appear, etc. etc. HTH, Wayne > ? > TIA > -- > Tim > tim at johnsons-web dot com or akwebsoft dot com > http://www.akwebsoft.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryan at quantodesign.com Wed Mar 16 02:26:16 2011 From: ryan at quantodesign.com (Ryan McAdam) Date: Tue, 15 Mar 2011 18:26:16 -0700 Subject: [Tutor] first steps Message-ID: I'm a newbie running my very first module . . . Specs: Mac OSX 10.6.6 Python 3.2 IDLE v 3.2 Tk v 8.5 I saved this module to my desktop > # File: chaos.py > # A simple program illustrating chaotic behavior. > > def main(): > print("This program illustrates a chaotic function") > x = eval(input("Enter a number between 0 and 1: ")) > for i in range(10): > x = 3.9 * x * (1 - x) > print(x) > > main() When I open and run this module in IDLE's shell the application hangs. This can sometimes be 'fixed' by going to Run > Check Module and then running the module. But I have a feeling I'm doing something wrong. Is there a better way to import the file into IDLE so I can run it without crashing the app? Also, when it works correctly, IDLE won't run the program again via the >>> chaos.main() statement. I get this: > Traceback (most recent call last): > File "", line 1, in > chaos.main() > NameError: name 'chaos' is not defined Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Mar 16 02:54:37 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 15 Mar 2011 17:54:37 -0800 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: References: <914467.65806.qm@web31503.mail.mud.yahoo.com> <20110316010044.GB1827@johnsons-web.com> Message-ID: <20110316015437.GF1827@johnsons-web.com> * Wayne Werner [110315 17:29]: > On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson wrote: > > > What is the difference between using > > hasattr(object, name) > > and > > name in dir(object) > > > > hasattr is basically > > try: > object.name > return True > except AttributeError: > return False > > while "name in dir(object)" is (AFAIK) more like: > > for attr in dir(object): > if name == attr: return True > return False Wayne, that is interesting to read. I'm glad I read it. > However, rare is the occasion that you should use either of these. If you're > doing something like: > > if hasattr(myobj, 'something'): > myobj.something() > else: > print "blah blah blah" > > then what you really should be doing is: > > try: > myobj.something() > except AttributeError: > print "blah blah blah" > because 1) you avoid the overhead of an extra(?) try-except block, 2) in > Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You > shouldn't inspect an object to find out what it can do, you should just try > it and then handle failures appropriately (at least that's what I've been > told). > > HTH, Yes it helps, including the distinction between the two try/except blocks. On another note, I made an error in the original posting. I did a 'reply' rather than a direct 'send' thus this thread is under the topic heading of a different thread. I will repost with your reply. thanks. -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From tim at johnsons-web.com Wed Mar 16 03:02:14 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Tue, 15 Mar 2011 18:02:14 -0800 Subject: [Tutor] atr in dir Vs. hasattr Message-ID: <20110316020214.GA3421@johnsons-web.com> This following post was originally posted to the wrong thread. I am reposting (hopefully correctly) with the first and very succint response. I thing the answer is a revealation to be noted: ########################################################## On Tue, Mar 15, 2011 at 8:00 PM, Tim Johnson wrote: What is the difference between using hasattr(object, name) and name in dir(object) ########################################################## Wayne Werner Replied: ########################################################## hasattr is basically try: object.name return True except AttributeError: return False while "name in dir(object)" is (AFAIK) more like: for attr in dir(object): if name == attr: return True return False However, rare is the occasion that you should use either of these. If you're doing something like: if hasattr(myobj, 'something'): myobj.something() else: print "blah blah blah" then what you really should be doing is: try: myobj.something() except AttributeError: print "blah blah blah" because 1) you avoid the overhead of an extra(?) try-except block, 2) in Python it's EAFP - Easier to Ask Forgivness than Permission, 3) You shouldn't inspect an object to find out what it can do, you should just try it and then handle failures appropriately (at least that's what I've been told). YMMV, objects in mirror are closer than they appear, etc. etc. HTH, Wayne -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From drbedsole at gmail.com Wed Mar 16 03:09:42 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Tue, 15 Mar 2011 22:09:42 -0400 Subject: [Tutor] first steps Message-ID: Hi Ryan, Also, when it works correctly, IDLE won't run the program again via the >>> chaos.main() statement. I get this: Traceback (most recent call last): File "", line 1, in chaos.main() NameError: name 'chaos' is not defined I think IDLE is looking for a file name to run. If your file name is chaos.py, use that. From drbedsole at gmail.com Wed Mar 16 03:35:04 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Tue, 15 Mar 2011 22:35:04 -0400 Subject: [Tutor] first steps Message-ID: Ryan, Did you enter it like this at the prompt: >>> chaos.main() statement If so, that's a problem. Your function was called: "main()", so if you type chaos.main(), Python doesn't know what you're talking about. From drbedsole at gmail.com Wed Mar 16 06:22:32 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Wed, 16 Mar 2011 01:22:32 -0400 Subject: [Tutor] Boolean question Message-ID: Hi folks, I'm working on Boolean Operators right now, and I'm getting it for the most part. But, could someone make sure I'm understanding this one expression correctly? not (False and True) Python evaluates it as "True" Is it because: 1)You evaluate what's in the parentheses first. A thing can not be false and true at the same time, so the answer is false. 2)However, the "not" outside the parentheses flips the meaning of what is inside the parentheses, so false becomes "True." ? From jacktradespublic at gmail.com Wed Mar 16 06:55:19 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Wed, 16 Mar 2011 00:55:19 -0500 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: On Wed, Mar 16, 2011 at 12:22 AM, Donald Bedsole wrote: > > not (False and True) > > Python evaluates it as "True" > > Is it because: > 1)You evaluate what's in the parentheses first. A thing can not be > false and true at the same time, so the answer is false. > Yes, the expression in the parenthesis is evaluated first. However it's not just one thing being evaluated. 'and' evaluates one argument at a time and returns immediately if the argument is False. In this case there are 2 distinct 'things'. False and True. False, obviously, evaluates to False, which causes 'and' to stop and return False. This reduces the expression to... not False > 2)However, the "not" outside the parentheses flips the meaning of what > is inside the parentheses, so false becomes "True." ? > Correct, the expression "not False" evaluates to True. -- Jack Trades Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Wed Mar 16 07:24:49 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Wed, 16 Mar 2011 02:24:49 -0400 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: Hi Jack, On Wed, Mar 16, 2011 at 1:50 AM, Jack Trades wrote: > On Wed, Mar 16, 2011 at 12:22 AM, Donald Bedsole > wrote: > >> not (False and True) >> >> Python evaluates it as "True" > > >> >> 1)You evaluate what's in the parentheses first. ?A thing can not be >> false and true at the same time, so the answer is false. > > Yes, the expression in the parenthesis is evaluated first.? However it's not > just one thing being evaluated. > > 'and' evaluates one argument at a time and returns immediately if the > argument is False. > > In this case there are 2 distinct 'things'.? False and True.? False, > obviously, evaluates to False, which causes 'and' to stop and return False. > This reduces the expression to... > > not False > >> >> 2)However, the "not" outside the parentheses flips the meaning of what >> is inside the parentheses, so false becomes "True." ? > > Correct, the expression "not False" evaluates to True. Ok, so, as another example: not(True and False) is "True" because: the first argument "True" is true, and the second argument "False" when returned is negated by "not" becomes "not False" which evaluates to True? Thanks for the help! Btw, you're blog looks interesting; I'm going to have to check it our more closely later. From jacktradespublic at gmail.com Wed Mar 16 07:30:38 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Wed, 16 Mar 2011 01:30:38 -0500 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: On Wed, Mar 16, 2011 at 1:24 AM, Donald Bedsole wrote: > > Ok, so, as another example: > > not(True and False) is "True" > > because: the first argument "True" is true, and the second argument > "False" when returned is negated by "not" becomes "not False" which > evaluates to True? > > Correct. When Python sees (True and False) it first evaluates True, which is obviously True. Because the first argument was not False, it continues on and evaluates False. At this point Python stops evaluating anything else (for example if you had (True and False and True)) and returns False, which is then negated by 'not'. -- Jack Trades Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 16 09:28:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2011 08:28:37 -0000 Subject: [Tutor] first steps References: Message-ID: "Ryan McAdam" wrote > I saved this module to my desktop You probably need to create a Folder for your Python code or you will soon have a very busy desktop! :-) > # File: chaos.py > # A simple program illustrating chaotic behavior. > > def main(): > print("This program illustrates a chaotic function") > x = eval(input("Enter a number between 0 and 1: ")) > for i in range(10): > x = 3.9 * x * (1 - x) > print(x) > > main() Don;t use eval() here it is bad practice since it opens a security hole in your program and its best to get into good security habits from the start. Instead use the explicit type that you want the data to be, in your case a floating point number(float() ) x = float(input("Enter a number between 0 and 1: ")) > When I open and run this module in IDLE's shell Thats your mistake. Don't open files in the shell use the File->Open menu to create a new IDLE window that doesn't have the >>> prompt. Then when you run the file the output will appear in the IDLE shell window. > going to Run > Check Module and then running the module. You shouldn't need to Check Module first (unless IDLE on Mac works differently to IDLE on Windows, which it shouldn't...) > Also, when it works correctly, IDLE won't run the program > again via the >>> chaos.main() statement. I get this: > chaos.main() > NameError: name 'chaos' is not defined This tells you that Python does not recognise chaos. If you do want to run from the >>> prompt (eg to test chaos) then you will need to import chaos first >>> import chaos >>> chaos.main() HTH and welcome to the tutor list. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Mar 16 09:40:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2011 08:40:00 -0000 Subject: [Tutor] Boolean question References: Message-ID: "Donald Bedsole" wrote > most part. But, could someone make sure I'm understanding this one > expression correctly? > > not (False and True) > > Python evaluates it as "True" > > Is it because: > 1)You evaluate what's in the parentheses first. A thing can not be > false and true at the same time, so the answer is false. > 2)However, the "not" outside the parentheses flips the meaning of > what > is inside the parentheses, so false becomes "True." ? Absolutely correct. Well done. Boolean algebra can be a weird thing to get your head around the first time you come across it :-) Here are some of the standard rules: True and thing = thing False and thing = False True or thing = True False or thing = thing And perhaps most bizarre of all: not(X or Y) = not X and not Y not(X and Y) = not X or not Y HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lagrapidis at yahoo.com Wed Mar 16 11:14:14 2011 From: lagrapidis at yahoo.com (Lukas Agrapidis) Date: Wed, 16 Mar 2011 03:14:14 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <825418.74147.qm@web36101.mail.mud.yahoo.com> http://witboy.110mb.com/index187.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Mar 16 14:12:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Mar 2011 00:12:18 +1100 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <20110316010044.GB1827@johnsons-web.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> <20110316010044.GB1827@johnsons-web.com> Message-ID: <4D80B732.3030705@pearwood.info> Tim Johnson wrote: > What is the difference between using > hasattr(object, name) > and > name in dir(object) > ? Did you read the Fine Manual? http://docs.python.org/library/functions.html#dir "The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information: ... Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases." And here's an example: >>> class C(object): ... pass ... >>> hasattr(C, '__eq__') True >>> '__eq__' in dir(C) False -- Steven From bhavanasisarath at gmail.com Wed Mar 16 14:15:14 2011 From: bhavanasisarath at gmail.com (bhavanasi sarath) Date: Wed, 16 Mar 2011 18:45:14 +0530 Subject: [Tutor] how to compress a folder in python Message-ID: i want to learn how to compress a folder which is having some text files....but compress that from another directory.. -- $$$ Bhavanasi $$$ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Mar 16 14:19:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Mar 2011 00:19:34 +1100 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: References: <914467.65806.qm@web31503.mail.mud.yahoo.com> <20110316010044.GB1827@johnsons-web.com> Message-ID: <4D80B8E6.1030609@pearwood.info> Wayne Werner wrote: > However, rare is the occasion that you should use either of these. If you're > doing something like: > > if hasattr(myobj, 'something'): > myobj.something() > else: > print "blah blah blah" > > then what you really should be doing is: > > try: > myobj.something() > except AttributeError: > print "blah blah blah" > > because 1) you avoid the overhead of an extra(?) try-except block, But there is no extra try-except block, because you've just explained that hasattr itself contains a try-except block. The only difference is whether it is explicit in your own code, or implicit inside hasattr. More likely though, hasattr (like its cousins getattr and setattr) will be used when the attribute name isn't known until runtime, rather than for fixed strings: name = get_some_name_from_somewhere(arg) if hasattr(myobj, name): result = getattr(myobj, name) else: do_something_else() Of course, you could do this instead: try: result = getattr(myobj, name) except AttributeError: do_something_else() or even this: result = getattr(myobj, name, default_value) -- Steven From freethinker at pobox.com Wed Mar 16 14:30:59 2011 From: freethinker at pobox.com (Tom Zych) Date: Wed, 16 Mar 2011 09:30:59 -0400 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <4D80B732.3030705@pearwood.info> References: <914467.65806.qm@web31503.mail.mud.yahoo.com><20110316010044.GB1827@johnsons-web.com> <4D80B732.3030705@pearwood.info> Message-ID: <1300282259.11329.1430412069@webmail.messagingengine.com> On Thu, 17 Mar 2011 00:12 +1100, "Steven D'Aprano" wrote: > And here's an example: > > >>> class C(object): > ... pass > ... > >>> hasattr(C, '__eq__') > True > >>> '__eq__' in dir(C) > False OTOH, I got True in 3.1.1. As the docs say, detailed behavior may change across releases. I suppose there must be some reliable way to get a list of *all* an object's attributes, but I don't see it. -- Tom Zych / freethinker at pobox.com From steve at pearwood.info Wed Mar 16 14:40:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Mar 2011 00:40:35 +1100 Subject: [Tutor] how to compress a folder in python In-Reply-To: References: Message-ID: <4D80BDD3.5010806@pearwood.info> bhavanasi sarath wrote: > i want to learn how to compress a folder which is having some text > files....but compress that from another directory.. http://docs.python.org/library/archiving.html Let us know if this doesn't help. -- Steven From kb1pkl at aim.com Wed Mar 16 14:38:49 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 16 Mar 2011 09:38:49 -0400 Subject: [Tutor] how to compress a folder in python In-Reply-To: References: Message-ID: <4D80BD69.1030802@aim.com> On 03/16/2011 09:15 AM, bhavanasi sarath wrote: > i want to learn how to compress a folder which is having some text > files....but compress that from another directory.. > http://docs.python.org/library/zipfile.html (Sorry for the HTML email, getting things set up on new workstation) From steve at pearwood.info Wed Mar 16 14:49:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Mar 2011 00:49:36 +1100 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <1300282259.11329.1430412069@webmail.messagingengine.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com><20110316010044.GB1827@johnsons-web.com> <4D80B732.3030705@pearwood.info> <1300282259.11329.1430412069@webmail.messagingengine.com> Message-ID: <4D80BFF0.4080405@pearwood.info> Tom Zych wrote: > I suppose there must be some reliable way to get a list of *all* an > object's attributes, but I don't see it. Nope, there isn't, because Python allows classes to define arbitrary attributes at runtime. >>> import random >>> class Funny: ... def __getattr__(self, name): ... if name == 'weird' and random.random() < 0.5: ... return "Yes, that's very strange." ... else: ... raise AttributeError ... >>> f = Funny() >>> f.weird Traceback (most recent call last): File "", line 1, in File "", line 6, in __getattr__ AttributeError >>> f.weird "Yes, that's very strange." Then add in __getattribute__, inheritance from superclasses, metaclasses, custom dictionary types for __dict__ (Python 3 only), and descriptors, and, well, there really isn't a guaranteed list of attributes. -- Steven From eire1130 at gmail.com Wed Mar 16 15:26:41 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 16 Mar 2011 10:26:41 -0400 Subject: [Tutor] Processing Financial Calculations using Python In-Reply-To: <914467.65806.qm@web31503.mail.mud.yahoo.com> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> Message-ID: For all of these, I wrote my own class with methods to create the correct output. there is not built in python functionality that I know, although there may be a package. For IRR, the method expects a list and at least one negative value. I believe the way I did NPV was a dictionary, where the key was the discount rate and the value was a list of cash flows. For NPV specifically, I wrote this as a C module, but I need to rewrite this because I didn't know much about C at the time. It works and all, but I feel it could be more efficient. For my purposes, NPV and IRR calculations are fairly slow using native Python and you will may want to consider writing some of this in C as a python extension if you can. My view is if you aren't doing a large number of calculations, just use excel. If you are, speed becomes an issue. On Tue, Mar 15, 2011 at 8:00 PM, Carla Jenkins wrote: > Are there specific Python commands to process present value, future value > and net present value? Thanks. > > Sincerely, > Carla Jenkins > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Mar 16 16:42:38 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 16 Mar 2011 07:42:38 -0800 Subject: [Tutor] atr in dir Vs. hasattr In-Reply-To: <4D80B732.3030705@pearwood.info> References: <914467.65806.qm@web31503.mail.mud.yahoo.com> <20110316010044.GB1827@johnsons-web.com> <4D80B732.3030705@pearwood.info> Message-ID: <20110316154238.GB3421@johnsons-web.com> * Steven D'Aprano [110316 05:26]: > Tim Johnson wrote: > > What is the difference between using > > hasattr(object, name) > > and > > name in dir(object) > > ? > > Did you read the Fine Manual? No but I will :) > http://docs.python.org/library/functions.html#dir > > "The default dir() mechanism behaves differently with different > types of objects, as it attempts to produce the most relevant, > rather than complete, information: ... > Note: Because dir() is supplied primarily as a convenience for use > at an interactive prompt, it tries to supply an interesting set of > names more than it tries to supply a rigorously or consistently > defined set of names, and its detailed behavior may change across > releases." help(dir) speaks similarly > > And here's an example: > > >>> class C(object): > ... pass > ... > >>> hasattr(C, '__eq__') > True > >>> '__eq__' in dir(C) > False I like Wayne's approach a lot. thanks -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com From susana.delgado_s at utzmg.edu.mx Wed Mar 16 18:12:13 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 16 Mar 2011 11:12:13 -0600 Subject: [Tutor] CSV to Excel In-Reply-To: <4D7A8FD8.8010503@timgolden.me.uk> References: <4D7A8FD8.8010503@timgolden.me.uk> Message-ID: Thank you for your help! Once I read your comments I tried both corrections in my code, but none of them we're sucessful. Tim's idea kept the quotes at the moment I open the csv in Excel, quotues appeared at the beggining and the end of the row for Excel. Joel's idea wrote just tha variable name 'filepath' and ''filename'. The corrections I made were: import os, csv, time, socket from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk( "C:\\" ): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(".shp")) ofile = open('csv1.csv', "wb") writer = csv.writer(open('csv2.csv', "wb")) ruta = 'Ruta' archivo = 'archivo' prj = '.prj' campos = [ruta,archivo,prj] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) n = os.path.splitext(filepath) p = n[0]+'.prj' filepath = ''+filepath+'' filename = ''+filename+'' if os.path.exists(p): prj_text = open(p, 'r').read() prjtext = ''+prj_text+'' aRow= [ filepath, filename, 1, ] writer.writerow(aRow) else: no_prj = 'Sin prj, no se puede determinar la proyeccion' aRow1= [ filepath, filename,0] writer.writerow(aRow1) print "El archivo esta listo" 2011/3/11 Tim Golden > On 11/03/2011 8:59 PM, Susana Iraiis Delgado Rodriguez wrote: > >> Hello list!! >> >> I'm trying to write a CSV file to work it with Excel. My python script is >> working, the issue is: when I import the file from excel the data comes >> with >> quotes at the beginnig and ending of the row. I don't want to have these >> quotes. What is wrong with my code? >> > > Essentially, the work is being done twice. > The .writerow method expects a list which it will > convert into a quoted, comma-separated string. You're > giving it a list whose one element is a quoted, comma-separated > string. > > Just pass it a list instead: > > writer.writerow (['Ruta', 'Archivo', '.prj']) > ... > writer.writerow ([filepath, filename, 1]) > > (BTW, my naive knowledge of Spanish suggests that you're confusing > the two identical-sounding English words: "root" -> "raiz" and > "route" -> "ruta"). > > TJG > -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Wed Mar 16 18:21:34 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Wed, 16 Mar 2011 19:21:34 +0200 Subject: [Tutor] Check my dummy application Message-ID: hi, While I was trying to learn python by doing it. I created a really primitive app, called best buy. You can find it here: http://ug.bcc.bilkent.edu.tr/~y_arabaci/best_buy.tar.gz Here is what this code suppossed to do: *You add products with its name, price and rating: Note : Rating defines liking ratio. For example, rating 2, means you like that product two times then product with rating 1. If difference of your liking of two items are not that big, you can put numbers like 7,8 indicating a minor difference in liking. *You add budget *Program will (try) to calculate best bundle of products you can get. Like this; a:5 b:7 c:4 --> You should buy 5 piece of a, 7 piece of b, 4 piece of c And that's all, there is also functions to remove product and list product. How to use After downloading the program (which is only 2.6 KB!), extract it to somewhere. Run cli.py. You will see a command prompt. First add at least two products like this: add product car 5 7 This will add product, named car, with price 5 and rating 7 Then add another one in the same way. After that, you can enter your budget like this: add budget 100 This will add your budget. Then you can calculate what to buy with: calculate bundle You can keep adding, removing products, or change your budget as many times as you like. Other command you can use: quit --> quits help --> gives possible commands remove product [insert name of a product here] -> removes product list products --> gives a list of products. list budget --> shows your current budget Known bugs: Because products assumed to be un-divideable, flooring optimum number to integer causes unspent budget. Will fix this later. What I want to hear from you: Since purpose of this is code to learn python. I want to hear from you * Better practices: How can I write this code in a better way. * Comments on comments : How do you think I used my comments. How can I better comment. * Object orientation: What do you think of my object orientation, can I make it in a better way? * Style: What do you think of my coding style, as in spaces, line breaks, upper-lower cases etc. And any additional comment is also welcome. Best Regards, Ya?ar Arabac? From fomcl at yahoo.com Wed Mar 16 21:24:16 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 16 Mar 2011 13:24:16 -0700 (PDT) Subject: [Tutor] ctypes and spssio.dll Message-ID: <208557.19435.qm@web110715.mail.gq1.yahoo.com> Hi, I'm still working on a program that uses a .dll to read SPSS system files. It's getting somewhere already, but I'm still struggling with one thing. When using the C function spssGetVarNames I'm having trouble translating C arrays to Python lists. I want to translate an array that holds the variable names into a Python list. Same thing for variable types. The documentation of the SPSSIO dll says the following: spssGetVarNames int spssGetVarNames (int handle, int *numVars, char ***varNames, int **varTypes) Parameter - Description handle - Handle to the data file numVars - Pointer to number of variables varNames - Pointer to array of pointers to variable varTypes - Pointer to array of variable types In the code below, which can also be found on http://pastebin.com/d7d0hpyV, the equivalent Python function is called getVarNamesAndTypes(). This is the output I typically get: retcode: 0 Varnames: ['\x80\xde\x10\x01P\xd8\x10\x01\xf0\xd0\x10\x01', None, None, None, None, None, None, None, None, None] varTypes: [17885264, 0, 0, 0, 0, 0, 0, 0, 0, 0] The first item of each list is clearly wrong, but what does it mean? If varType > 0 it is supposed to be a string var of that length. And of course the varNames are mostly 'None'. Probably, something is wrong with the way the C arrays are initialized, or with the two list comprehensions, but I can't find the solution. varNames = [varNamesPtr[0][i] for i in range(numVars)] does not seem to work. For those who are interested, the complete program can be found on http://pastebin.com/ff1b1Y9a (note that it's still work in progress) Any hints? Thanks very much in advance! import os, ctypes, datetime # dll and py file should be in the same dir! def loadSavFile(fn): os.environ["PATH"] += ";" + os.path.abspath(os.curdir) ctypes.cdll.LoadLibrary("spssio32.dll") spssio = ctypes.windll.spssio32 libc = ctypes.cdll.msvcrt if os.path.exists(fn): fh = libc._fdopen(fn, "rb") fhPtr = ctypes.pointer(ctypes.c_int(fh)) retcode = spssio.spssOpenRead(ctypes.c_char_p(fn), fhPtr) return retcode, spssio, fh else: raise Exception, "File '%s' does not exist!" % fn def getVarNamesAndTypes(fh, spssio): numVarsPtr = ctypes.pointer(ctypes.c_int()) spssio.spssGetNumberofVariables(fh, numVarsPtr) numVars = numVarsPtr[0] varNamesArray = (ctypes.c_char_p * numVars)() varNamesPtr = ctypes.pointer(varNamesArray) varTypesArray = (ctypes.c_int * numVars)() varTypesPtr = ctypes.pointer(varTypesArray) retcode = spssio.spssGetVarNames(fh, numVarsPtr, varNamesPtr, varTypesPtr) varNames = [varNamesPtr[0][i] for i in range(numVars)] # -- WRONG!! varTypes = [varTypesPtr[0][i] for i in range(numVars)] return retcode, varNames, varTypes savFileName = r"C:\Program Files\SPSS\Employee data.sav" retcode, spssio, fh = loadSavFile(savFileName) retcode, varNames, varTypes = getVarNamesAndTypes(fh, spssio) print "retcode:", retcode print "Varnames:", varNames Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Wed Mar 16 22:26:41 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Wed, 16 Mar 2011 17:26:41 -0400 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: Hi Allen, > Boolean algebra can be a weird thing to get your head around > the first time you come across it :-) Yes, :-) > Here are some of the standard rules: > > True and thing = thing > False and thing = False > True or thing = True > False or thing = thing > Thanks for your response and for the rules, but for some reason I'm not understanding. In the above quote, what is meant by "thing"? Thank you. From bgailer at gmail.com Wed Mar 16 22:53:57 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 16 Mar 2011 16:53:57 -0500 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: <4D813175.8020201@gmail.com> On 3/16/2011 4:26 PM, Donald Bedsole wrote: > Hi Allen, > >> Boolean algebra can be a weird thing to get your head around >> the first time you come across it :-) > Yes, :-) > >> Here are some of the standard rules: >> >> True and thing = thing >> False and thing = False >> True or thing = True >> False or thing = thing >> > Thanks for your response and for the rules, but for some reason I'm > not understanding. In the above quote, what is meant by "thing"? Thing in this context means 'anything". could be a string, number, list, any Python object. True and 1 = 1 True and 'a'= 'a' etc. -- Bob Gailer 919-636-4239 Chapel Hill NC From drbedsole at gmail.com Wed Mar 16 22:55:28 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Wed, 16 Mar 2011 17:55:28 -0400 Subject: [Tutor] Boolean question In-Reply-To: <4D813175.8020201@gmail.com> References: <4D813175.8020201@gmail.com> Message-ID: On Wed, Mar 16, 2011 at 5:53 PM, bob gailer wrote: > > Thing in this context means 'anything". could be a string, number, list, any > Python object. > Ok, thanks Bob. From drbedsole at gmail.com Wed Mar 16 22:49:05 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Wed, 16 Mar 2011 17:49:05 -0400 Subject: [Tutor] Boolean question In-Reply-To: References: Message-ID: Hi Jack, On Wed, Mar 16, 2011 at 1:55 AM, Jack Trades wrote: 'and' evaluates one argument at a time and returns immediately if the argument is False. > And "or" works in the inverse manner? It "evaluates one argument at a time and returns immediately if the argument is [True]." ? For example, >>> not (True or False) >>> False The first argument was "True", so "True" was returned and negated by the "not" with a final result of "False" for the expression. Is this correct? From alan.gauld at btinternet.com Wed Mar 16 23:37:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2011 22:37:13 -0000 Subject: [Tutor] Boolean question References: Message-ID: "Donald Bedsole" wrote > The first argument was "True", so "True" was returned and negated by > the "not" with a final result of "False" for the expression. > > Is this correct? Yes. Its called Short Circuit Evaluation. You will find an explanation on the Functional Programming topic of my tutor HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Mar 16 23:41:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Mar 2011 22:41:02 -0000 Subject: [Tutor] Boolean question References: Message-ID: "Donald Bedsole" wrote >> False or thing = thing >> > Thanks for your response and for the rules, but for some reason I'm > not understanding. In the above quote, what is meant by "thing"? Any Boolean value, and in Python that means pretty much anything at all because Python has a set of rules over how it converts values to booleans. More or less it is that: None, empty strings, lists etc , zero, are all False, anything else is True You can check by explicitly converting: spam = "foo" # or any other value print bool(spam) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From spiderbabymass at gmail.com Thu Mar 17 01:32:29 2011 From: spiderbabymass at gmail.com (Shane O'Connor) Date: Wed, 16 Mar 2011 17:32:29 -0700 Subject: [Tutor] Efficiency of while versus (x)range Message-ID: Hi, First-time poster here. I've a question about loop efficiency - I was wondering whether this code: i = 0 while i < 1000: do something i+=1 is more efficient than: for i in range(1000): do something or: for i in xrange(1000): do something In my mind, the while loop should not allocate as much memory as range or have the overhead of the iterator of xrange (although aesthetically, I prefer the x/range style). Is this the case or does the compiler do something clever here? In particular, I'm using Python 2.4.3 on a web server which needs to run as fast as possible using as little memory as possible (no surprises there!). I'm aware that there are more significant optimizations than the above and I will profile the code rather than prematurely optimize loops at the sake of readability/errors but I'm still curious about the answer. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Mar 17 02:23:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Mar 2011 20:23:50 -0500 Subject: [Tutor] Efficiency of while versus (x)range In-Reply-To: References: Message-ID: On Wed, Mar 16, 2011 at 7:32 PM, Shane O'Connor wrote: > Hi, > > First-time poster here. I've a question about loop efficiency - I was > wondering whether this code: > > i = 0 > while i < 1000: > do something > i+=1 > > is more efficient than: > > for i in range(1000): > do something > > or: > > for i in xrange(1000): > do something > > In my mind, the while loop should not allocate as much memory as range or > have the overhead of the iterator of xrange (although aesthetically, I > prefer the x/range style). Is this the case or does the compiler do > something clever here? > > In particular, I'm using Python 2.4.3 on a web server which needs to run as > fast as possible using as little memory as possible (no surprises there!). > I'm aware that there are more significant optimizations than the above and I > will profile the code rather than prematurely optimize loops at the sake of > readability/errors but I'm still curious about the answer. > Well, I'm not sure about the xrange v while loop, but I'm 100% certain that range is the least efficient of all - because you both create the iterator *and* a list to iterate over it. My guess is that xrange v while is fairly similar, I do know that the for loop raises/catches a StopIteration under the hood, so there may be some performance issues - I don't think you'll get a big gain unless you're running the loop thousands+ times, but I could be wrong. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Mar 17 02:33:03 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 16 Mar 2011 21:33:03 -0400 Subject: [Tutor] Efficiency of while versus (x)range In-Reply-To: References: Message-ID: <4D8164CF.4090701@aim.com> On 03/16/2011 08:32 PM, Shane O'Connor wrote: > Hi, > > First-time poster here. I've a question about loop efficiency - I was > wondering whether this code: > > i = 0 > while i < 1000: > do something > i+=1 > > is more efficient than: > > for i in range(1000): > do something > > or: > > for i in xrange(1000): > do something > > In my mind, the while loop should not allocate as much memory as range or > have the overhead of the iterator of xrange (although aesthetically, I > prefer the x/range style). Is this the case or does the compiler do > something clever here? > Only way to know is to check! http://docs.python.org/library/timeit.html -- Corey Richardson From alan.gauld at btinternet.com Thu Mar 17 02:42:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Mar 2011 01:42:42 -0000 Subject: [Tutor] Efficiency of while versus (x)range References: Message-ID: "Shane O'Connor" wrote > First-time poster here. I've a question about loop efficiency - I > was > wondering whether this code: > > i = 0 > while i < 1000: > do something > i+=1 > > is more efficient than: > > for i in range(1000): > do something It is impossible to tell and 99% of the time irrelevant since the body of the loop will be far more significant than the loop itself. In the case of Python its impossible to tell without profiling and looking at the generated byte code. With true copmiled languages it is even harder because an optimising compiler will take account of the body of the loop and concert between while and for type structures as appropriate. So for some cases the for will be faster and for others the while will be. I can honestly say I have never, in around 30 years of programming, converted a 'while' to a 'for' or vice versa as a performance improvement, the difference is so tiny as to be irrelevant. If that will make a difference you are using the wrong language and you should probably rewrite the function in C or assembler. > In my mind, the while loop should not allocate as much memory as > range or > have the overhead of the iterator of xrange But on the other hand it has to do the counter indexing and incrementing using pure python rather than in C. When in doubt profile it. > Is this the case or does the compiler do something clever here? Who knows and different Python implementations might do it differently. And different versions of Python might give different results. There is no way to tell in any general sense. > In particular, I'm using Python 2.4.3 on a web server > which needs to run as fast as possible using as little > memory as possible (no surprises there!). As a general rule you could say that about any program. But in practice web apps are far more performance constrained by the amount of HTML and other stuff they have to output plus the time spent accessing databases and then waiting for the network to respond. Very few web apps run anywhere near 100% execution efficiency, they will usually be I/O bound. Moving things into or out of the database or into or out of JavaScript (for client side execution) will likely be far more significant improvements than worrying about the difference between a 'for' or 'while' loop. > I'm aware that there are more significant optimizations > than the above Yes, orders of magnitude more significant. As I say if you really are running so close that changing the loop type makes a difference then you really need a different programming language (or just buy a bigger box!) > will profile the code rather than prematurely optimize > loops at the sake of readability/errors Optimising loops is very important when tuning code, but that usually means addressing the algorithm and logic inside the loop and ensuring there are no wasted/duplicated operations, not worrying about whether it's a while or for construct. Those are primarily readability, reliability and maintenance issues, not performance ones. > but I'm still curious about the answer. Curiosity is fine, so profile it. But do it twice. Once with a dummy loop body (not an empty one but one with a very simple operation that can be duplicated for both types) Then do it again with a realistic loop body, something containg an if/else branch plus several operations. Then consider how much difference the loop type really makes. (prime numbers or fibbonacci series type problems are fine) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Thu Mar 17 03:40:54 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 17 Mar 2011 02:40:54 +0000 Subject: [Tutor] time taken to execute certain task Message-ID: hi, i would like to know the time taken to execute a certain task in python. i used time.time and time.clock and i see the time taken is different? what is the right method to use? import time def testtime(num): start=time.time() #print start for n in range(num): #print n print time.time()-start testtime(101) start = time.clock() for x in range(101): y = x # do something end = time.clock() print "Time clock elapsed = ", end - start, "seconds" thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Mar 17 05:02:56 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 16 Mar 2011 23:02:56 -0500 Subject: [Tutor] Linux library for getch() and kbhit()? Message-ID: I have found that for the Windows build of Python the msvcrt library provides getch() and kbhit() functions. Is there a library available for the Linux Python build that provides the same or similar functions? I have found lots of recipes out there to do these, but have not yet found a canned library. Being able to do a non-blocking character get or simply check for a keyboard hit is so useful, so many times, that I wonder about there not being something like the msvcrt library for Linux. I am hoping there is and I have just missed it somewhere. --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacktradespublic at gmail.com Thu Mar 17 05:50:09 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Wed, 16 Mar 2011 23:50:09 -0500 Subject: [Tutor] time taken to execute certain task In-Reply-To: References: Message-ID: On Wed, Mar 16, 2011 at 9:40 PM, tee chwee liong wrote: > hi, > > i would like to know the time taken to execute a certain task in python. i > used time.time and time.clock and i see the time taken is different? what is > the right method to use? > > import time > def testtime(num): > start=time.time() > #print start > for n in range(num): > #print n > print time.time()-start > > testtime(101) > > start = time.clock() > for x in range(101): > y = x # do something > end = time.clock() > print "Time clock elapsed = ", end - start, "seconds" > > thanks > tcl > > First you have to start by testing things that are similar. I've rewritten your tests to look exactly the same except for the time.time() or time.clock(). In your first example, you are calculating an end time for each iteration of the for loop. In your second example you are only calculating the end time once, after the for loop has finished. Here's how I would compare them... (I hope the indentation doesn't get hosed. If it does I can repost.) import time def testtime(num): start = time.time() for n in range(num): 1 + 1 # do something print time.time() - start testtime(101) #===> 3.50475311279e-05 def testclock(num): start = time.clock() for n in range(num): 1 + 1 # do something print time.clock() - start testclock(101) #===> 0.0 Now that each test is exactly the same, you are in a better position to judge the differences. And there are some obvious differences! Why? To determine that you need to find out just what each function is supposed to return. The help() function will show you what each function (time or clock) is supposed to return. It looks like this... help(time.time) time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. help(time.clock) clock(...) clock() -> floating point number Return the CPU time or real time since the start of the process or since the first call to clock(). This has as much precision as the system records. As you can see, time.time() returns the current time in seconds from the Epoch, while time.clock() returns the time since the program started, or the time since the first call to time.clock(). The "epoch" is an arbitrary point in the past (don't rely on it always being the same). So both time.time() and time.clock() return the number of seconds, but each of them starts at a different time. As to which one's best? I don't know. I know there are some profiling tools that will give you a better idea about the performance of a function, but I rarely use them so I'll let someone else give you advice on this. For a quick-n-dirty test, either will work just fine. I usually use time.time(), but I only really ever do this "just for kicks". -- Jack Trades Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Thu Mar 17 07:15:35 2011 From: modulok at gmail.com (Modulok) Date: Thu, 17 Mar 2011 00:15:35 -0600 Subject: [Tutor] time taken to execute certain task In-Reply-To: References: Message-ID: On 3/16/11, tee chwee liong wrote: > > hi, > > i would like to know the time taken to execute a certain task in python. i > used time.time and time.clock and i see the time taken is different? what is > the right method to use? > > import time > def testtime(num): > start=time.time() > #print start > for n in range(num): > #print n > print time.time()-start > > testtime(101) > > start = time.clock() > for x in range(101): > y = x # do something > end = time.clock() > print "Time clock elapsed = ", end - start, "seconds" > > thanks > tcl > Also look into the builtin module 'timeit' if you're trying to benchmark things. -Modulok- From stefan_ml at behnel.de Thu Mar 17 08:45:43 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 17 Mar 2011 08:45:43 +0100 Subject: [Tutor] Efficiency of while versus (x)range In-Reply-To: References: Message-ID: Shane O'Connor, 17.03.2011 01:32: > In particular, I'm using Python 2.4.3 on a web server which needs to run as > fast as possible using as little memory as possible (no surprises there!). Note that a web application involves many things outside of your own code that seriously impact the performance and/or resource requirements. Database access can be slow, excessively dynamic page generation and template engines can become a bottleneck, badly configured caching can eat your RAM and slow down your response times. It seems very unlikely to me that the performance of loop iteration will make a substantial difference for you. > I'm aware that there are more significant optimizations than the above and I > will profile the code rather than prematurely optimize loops at the sake of > readability/errors but I'm still curious about the answer. You shouldn't be. Optimising at that level is clearly the wrong place to start with. That touches on a really nice feature of Python. It's a language that allows you to focus strongly on your desired functionality instead of thinking about questionable micro optimisations all over the place. Optimisation is something that you should start to apply when your test suite is large enough to catch the bugs you introduce by doing it. Stefan From andreengels at gmail.com Thu Mar 17 09:18:25 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 17 Mar 2011 09:18:25 +0100 Subject: [Tutor] Efficiency of while versus (x)range In-Reply-To: References: Message-ID: On Thu, Mar 17, 2011 at 8:45 AM, Stefan Behnel wrote: > Note that a web application involves many things outside of your own code > that seriously impact the performance and/or resource requirements. Database > access can be slow, excessively dynamic page generation and template engines > can become a bottleneck, badly configured caching can eat your RAM and slow > down your response times. Yes, that has been my experience too back when I did web applications in Python. I had several cases where the page took too long to load; in all but one cases the issue was resolved by getting a database access out of a loop, thus changing many database accesses into one. The remaining case was also resolved in the area of database access, this time by checking whether a particular database result was one that we needed in the database request instead of afterward in Python. > You shouldn't be. Optimising at that level is clearly the wrong place to > start with. The three rules of optimisation in Python: 1. Only optimise if your system is actually too slow 2. Only optimise the thing that is actually causing the slowness 3. If you are of the opinion that should break one of these rules, you are using the wrong language. > Optimisation is > something that you should start to apply when your test suite is large > enough to catch the bugs you introduce by doing it. That's a quote to remember :-) -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Thu Mar 17 09:57:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Mar 2011 08:57:11 -0000 Subject: [Tutor] time taken to execute certain task References: Message-ID: "tee chwee liong" wrote > i would like to know the time taken to execute a > certain task in python. i used time.time and time.clock > and i see the time taken is different? > what is the right method to use? Neither of those, either use timeit() or the Python profiler. They are both specifically provided for timing things in your code. Search the documentation for help with both. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Mar 17 10:01:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Mar 2011 09:01:31 -0000 Subject: [Tutor] Linux library for getch() and kbhit()? References: Message-ID: "Bill Allen" wrote >I have found that for the Windows build of Python the msvcrt library > provides getch() and kbhit() functions. Is there a library > available for > the Linux Python build that provides the same or similar functions? curses. Take a look at the event handling topic in my tutor for examples comparing msvcrt and curses. I'm not sure if curses provides a kbhit() equivalent but you can usually simulate the effect by using a combination of getch() and ungetch() - not pretty but it works. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Thu Mar 17 10:06:56 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 17 Mar 2011 09:06:56 +0000 Subject: [Tutor] time taken to execute certain task In-Reply-To: References: , Message-ID: hi, i used profiler. but it gives 0 sec? is this expected? tq >>> profile.run('import math') 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 :1() 1 0.000 0.000 0.000 0.000 profile:0(import math) 0 0.000 0.000 profile:0(profiler) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Mar 17 10:27:25 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Mar 2011 09:27:25 +0000 Subject: [Tutor] CSV to Excel In-Reply-To: References: <4D7A8FD8.8010503@timgolden.me.uk> Message-ID: <4D81D3FD.6030208@timgolden.me.uk> On 16/03/2011 17:12, Susana Iraiis Delgado Rodriguez wrote: > > Thank you for your help! > Once I read your comments I tried both corrections in my code, but none > of them we're sucessful. Ok, Susana, your problem (here) is the use of the csv module so can I suggest we back away from your wider program and try to help you understand the way in which that works. Here's a really simple example of how to use the module: import os import csv # # Open a file which will automatically close once # we're finished # with open ("temp.csv", "wb") as f: writer = csv.writer (f) # # Write to the csv file with explicit (if meaningless) strings # writer.writerow (['A', 'B', 'C']) list_of_stuff = ["Name", 2, 3] # # Write something which is already a list (like your filenames) # writer.writerow (list_of_stuff) # # Now look at the contents of the file produced # print open ("temp.csv").read () Can you run that and make sure that it produces the .csv format which you'd expect. The output should look something like this: A,B,C Name,2,3 Notice that I'm letting the csv module work out where it needs to put quote marks and where not (which is a lot of the reason for its existence). I just pass it a list of strings, numbers, or whatever and let it turn into a line. I hope that this example helps you to understand the way you would normally use the csv module. Feel free to come back to ask more questions or to see how introduce it into your wider codebase. TJG From alan.gauld at btinternet.com Thu Mar 17 10:41:54 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 17 Mar 2011 09:41:54 +0000 (GMT) Subject: [Tutor] time taken to execute certain task In-Reply-To: References: , Message-ID: <97504.94703.qm@web86703.mail.ird.yahoo.com> Profiling is really intended to profile a complex set of operations not a single statement, for that timeit() would be a better choice. However in this case, it may be that the time is so low it simply doesn't register. Have you already imported math for example? In which case you are effectively profiling a single if statement... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: tee chwee liong To: alan.gauld at btinternet.com; tutor at python.org Sent: Thursday, 17 March, 2011 9:06:56 Subject: RE: [Tutor] time taken to execute certain task hi, i used profiler. but it gives 0 sec? is this expected? tq >>> profile.run('import math') 3 function calls in 0.000 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.000 0.000 0.000 0.000 :1() 1 0.000 0.000 0.000 0.000 profile:0(import math) 0 0.000 0.000 profile:0(profiler) -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Mar 17 12:56:43 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 17 Mar 2011 12:56:43 +0100 Subject: [Tutor] CSV Ouptut concern... Message-ID: i wrote a code for extracting information from a csv file into another csv file. it worked well but i have an immediate challenge i can't seem to fix. the new file that is created has an row and then an empty row and then a row all through the file. how can i make the empty rows not be part of the file. here is the code: import csv reader = csv.reader(open('stateparty.csv')) counter = 1 fh = open('stateparty2.csv','w') writer = csv.writer(fh) for row in reader: if counter == 1: parties_row = row elif counter > 2: for index, column in enumerate(row[1:-1]): if column == "1": writer.writerow([row[0],parties_row[index+1]]) counter += 1 fh.close() and the output has something like this: Benue,ACN Benue,ANPP Benue,APGA Benue,CPC Benue,PDP Kogi,ACN Kogi,ADC Kogi,ANPP Kogi,APGA Kogi,CDC Kogi,CPC Kogi,DPP i am not expecting the spaces in between each line, kindly help with the challenge... thanks. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Mar 17 13:00:00 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 17 Mar 2011 12:00:00 +0000 Subject: [Tutor] CSV Ouptut concern... In-Reply-To: References: Message-ID: <4D81F7C0.1070604@timgolden.me.uk> On 17/03/2011 11:56, Dipo Elegbede wrote: > i wrote a code for extracting information from a csv file into another > csv file. > it worked well but i have an immediate challenge i can't seem to fix. > the new file that is created has an row and then an empty row and then a > row all through the file. how can i make the empty rows not be part of > the file. Open the file in binary mode: fh = open('stateparty2.csv','wb') TJG From delegbede at dudupay.com Thu Mar 17 13:53:39 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 17 Mar 2011 13:53:39 +0100 Subject: [Tutor] CSV Ouptut concern... In-Reply-To: <4D81F7C0.1070604@timgolden.me.uk> References: <4D81F7C0.1070604@timgolden.me.uk> Message-ID: Thanks Tim, that worked like magic. I now have another challenge on the same file, in this case, i am trying to extract just a column as PARTY, I successfully wrote the header but instead of having each element in a single excel block like this: A ACD ACN ACPN AD ADC ALP ANPP APGA APS ARP BNPP CAP CDC CPC CPN CPP DFPF DPP It is spelt out on different block like this: PARTY A A C D A C N A C P N A D A D C A L P A N P P A P G A A P S A R P B N P P C A P C D C C P C C P N C P P D F P F D P P what could be wrong with this code: import csv reader = csv.reader(open('stateparty.csv')) counter = 1 header = ["PARTY"] fh = open('stateparty3.csv','wb') writer = csv.writer(fh) writer.writerow(header) for row in reader: if counter == 1: parties = row[1:-1] for party in parties: writer.writerow([party]) counter += 1 fh.close() Thanks for your responses as anticipated. On Thu, Mar 17, 2011 at 1:00 PM, Tim Golden wrote: > On 17/03/2011 11:56, Dipo Elegbede wrote: > >> i wrote a code for extracting information from a csv file into another >> csv file. >> it worked well but i have an immediate challenge i can't seem to fix. >> the new file that is created has an row and then an empty row and then a >> row all through the file. how can i make the empty rows not be part of >> the file. >> > > Open the file in binary mode: > > fh = open('stateparty2.csv','wb') > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 17 14:04:54 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 17 Mar 2011 09:04:54 -0400 Subject: [Tutor] CSV Ouptut concern... In-Reply-To: References: <4D81F7C0.1070604@timgolden.me.uk> Message-ID: On Thu, Mar 17, 2011 at 8:53 AM, Dipo Elegbede wrote: > > Thanks Tim, that worked like magic. > > I now have another challenge on the same file, in this case, i am trying to > extract just a column as PARTY, I successfully wrote the header but instead > of having each element in a single excel block like this: > > A > ACD > ACN > ACPN > AD > ADC > ALP > ANPP > APGA > APS > ARP > BNPP > CAP > CDC > CPC > CPN > CPP > DFPF > DPP > > It is spelt out on different block like this: > > PARTY A A C D A C N A C P N A D A D C A L P A N P P A P > G A A P S A R P B N P P C A P C D C C P C C P N C P P D F > P F D P P > > > > > what could be wrong with this code: > > import csv > > reader = csv.reader(open('stateparty.csv')) > counter = 1 > header = ["PARTY"] > fh = open('stateparty3.csv','wb') > writer = csv.writer(fh) > writer.writerow(header) > > for row in reader: > if counter == 1: > parties = row[1:-1] > for party in parties: > writer.writerow([party]) > counter += 1 > fh.close() > > Thanks for your responses as anticipated. > > > > > > > > > > > On Thu, Mar 17, 2011 at 1:00 PM, Tim Golden wrote: > >> On 17/03/2011 11:56, Dipo Elegbede wrote: >> >>> i wrote a code for extracting information from a csv file into another >>> csv file. >>> it worked well but i have an immediate challenge i can't seem to fix. >>> the new file that is created has an row and then an empty row and then a >>> row all through the file. how can i make the empty rows not be part of >>> the file. >>> >> >> Open the file in binary mode: >> >> fh = open('stateparty2.csv','wb') >> >> TJG >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Elegbede Muhammed Oladipupo > OCA > +2348077682428 > +2347042171716 > www.dudupay.com > Mobile Banking Solutions | Transaction Processing | Enterprise Application > Development > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You want row[1] from each iteration of row. So instead of this: for row in reader: if counter == 1: parties = row[1:-1] for party in parties: writer.writerow([party]) counter += 1 fh.close() Do this: for row in reader: if counter == 1: party = row[1:2] write.writerow(party) counter += 1 What is the counter for? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Mar 17 14:18:48 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 17 Mar 2011 14:18:48 +0100 Subject: [Tutor] CSV Ouptut concern... In-Reply-To: References: <4D81F7C0.1070604@timgolden.me.uk> Message-ID: The counter is there so that it limits the iteration to only the first rows, i actually left it there because i used it earlier to print out specific rows. On Thu, Mar 17, 2011 at 2:04 PM, Joel Goldstick wrote: > > > On Thu, Mar 17, 2011 at 8:53 AM, Dipo Elegbede wrote: > >> >> Thanks Tim, that worked like magic. >> >> I now have another challenge on the same file, in this case, i am trying >> to extract just a column as PARTY, I successfully wrote the header but >> instead of having each element in a single excel block like this: >> >> A >> ACD >> ACN >> ACPN >> AD >> ADC >> ALP >> ANPP >> APGA >> APS >> ARP >> BNPP >> CAP >> CDC >> CPC >> CPN >> CPP >> DFPF >> DPP >> >> It is spelt out on different block like this: >> >> PARTY A A C D A C N A C P N A D A D C A L P A N P P A >> P G A A P S A R P B N P P C A P C D C C P C C P N C P P D >> F P F D P P >> >> >> >> >> what could be wrong with this code: >> >> import csv >> >> reader = csv.reader(open('stateparty.csv')) >> counter = 1 >> header = ["PARTY"] >> fh = open('stateparty3.csv','wb') >> writer = csv.writer(fh) >> writer.writerow(header) >> >> for row in reader: >> if counter == 1: >> parties = row[1:-1] >> for party in parties: >> writer.writerow([party]) >> counter += 1 >> fh.close() >> >> Thanks for your responses as anticipated. >> >> >> >> >> >> >> >> >> >> On Thu, Mar 17, 2011 at 1:00 PM, Tim Golden wrote: >> >>> On 17/03/2011 11:56, Dipo Elegbede wrote: >>> >>>> i wrote a code for extracting information from a csv file into another >>>> csv file. >>>> it worked well but i have an immediate challenge i can't seem to fix. >>>> the new file that is created has an row and then an empty row and then a >>>> row all through the file. how can i make the empty rows not be part of >>>> the file. >>>> >>> >>> Open the file in binary mode: >>> >>> fh = open('stateparty2.csv','wb') >>> >>> TJG >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> -- >> Elegbede Muhammed Oladipupo >> OCA >> +2348077682428 >> +2347042171716 >> www.dudupay.com >> Mobile Banking Solutions | Transaction Processing | Enterprise Application >> Development >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > You want row[1] from each iteration of row. So instead of this: > > > for row in reader: > if counter == 1: > parties = row[1:-1] > for party in parties: > writer.writerow([party]) > counter += 1 > fh.close() > > > Do this: > > > for row in reader: > if counter == 1: > party = row[1:2] > write.writerow(party) > counter += 1 > > > What is the counter for? > > > > -- > Joel Goldstick > > -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Mar 17 16:46:31 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 17 Mar 2011 10:46:31 -0500 Subject: [Tutor] Linux library for getch() and kbhit()? In-Reply-To: References: Message-ID: Alan, Ah ha, ungetch(), that is what I was needing. I had be trying to simulate kbhit() with getch() and keep being left with unhandled data in the buffer. I had resorted to a trash=raw_input() to clear it. Many thanks, Bill On Thu, Mar 17, 2011 at 04:01, Alan Gauld wrote: > > "Bill Allen" wrote > > > I have found that for the Windows build of Python the msvcrt library >> provides getch() and kbhit() functions. Is there a library available for >> the Linux Python build that provides the same or similar functions? >> > > curses. > > Take a look at the event handling topic in my tutor for examples > comparing msvcrt and curses. > > I'm not sure if curses provides a kbhit() equivalent but you can > usually simulate the effect by using a combination of getch() > and ungetch() - not pretty but it works. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffbgoodwin at gmail.com Thu Mar 17 19:19:17 2011 From: jeffbgoodwin at gmail.com (Jeff Goodwin) Date: Thu, 17 Mar 2011 14:19:17 -0400 Subject: [Tutor] Print/Loop Question Message-ID: I'm trying to run the below program and get it to print out feedback as the loop goes. However, if you enter a number too high or too low, it skips the print statement under the if and elif clauses and asks the user to "Guess a number between 1-100" again. Any suggestions on how to get it to print the "too high" and "too low" responses?? Once the number is entered correctly it prints "Just Right" and exits correctly. number = 44 while guess != number : guess = int(raw_input("Guess a number between 1 - 100: ")) *if* guess > number : *print* ("Too high") *elif* guess < number : *print* ("Too low") *else*: *print* ("Just right" ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Thu Mar 17 20:02:13 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Thu, 17 Mar 2011 12:02:13 -0700 (PDT) Subject: [Tutor] Print/Loop Question In-Reply-To: References: Message-ID: <108998.13376.qm@web130206.mail.mud.yahoo.com> Hi Jeff how are you today? Well about your question... I copy and pasted your code and it worked fine for me. Well except for in the code bit you posted you forgot to give a guess a value before it was referred to. So under number = 44 I just wrote guess = 0 and it worked fine. But perhaps I'm misunderstanding your question, because I did not get any of the errors you mentioned. Here is what I got jigenbakuda at jigenbakuda-HP-G50-Notebook-PC:~$ python 6.py Guess a number between 1 - 100: 45 Too high Guess a number between 1 - 100: 43 Too low Guess a number between 1 - 100: 44 Just right jigenbakuda at jigenbakuda-HP-G50-Notebook-PC:~$ with this code number = 44 guess = 0 while guess != number : guess = int(raw_input("Guess a number between 1 - 100: ")) if guess > number : print ("Too high") elif guess < number : print ("Too low") else: print ("Just right" ) If I'm misunderstanding your problem, I'm sorry. ---- What is it about you... that intrigues me so? ________________________________ From: Jeff Goodwin To: tutor at python.org Sent: Thu, March 17, 2011 2:19:17 PM Subject: [Tutor] Print/Loop Question I'm trying to run the below program and get it to print out feedback as the loop goes. However, if you enter a number too high or too low, it skips the print statement under the if and elif clauses and asks the user to "Guess a number between 1-100" again. Any suggestions on how to get it to print the "too high" and "too low" responses?? Once the number is entered correctly it prints "Just Right" and exits correctly. number = 44 while guess != number : guess = int(raw_input("Guess a number between 1 - 100: ")) if guess > number : print ("Too high") elif guess < number : print ("Too low") else: print ("Just right" ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jacktradespublic at gmail.com Thu Mar 17 20:10:18 2011 From: jacktradespublic at gmail.com (Jack Trades) Date: Thu, 17 Mar 2011 14:10:18 -0500 Subject: [Tutor] Print/Loop Question In-Reply-To: References: Message-ID: On Thu, Mar 17, 2011 at 1:19 PM, Jeff Goodwin wrote: > I'm trying to run the below program and get it to print out feedback as the > loop goes. However, if you enter a number too high or too low, it skips the > print statement under the if and elif clauses and asks the user to "Guess a > number between 1-100" again. Any suggestions on how to get it to print the > "too high" and "too low" responses?? Once the number is entered correctly it > prints "Just Right" and exits correctly. > > number = 44 > > while guess != number : > guess = int(raw_input("Guess a number between 1 - 100: ")) > *if* guess > number : > *print* ("Too high") > > *elif* guess < number : > *print* ("Too low") > *else*: > *print* ("Just right" ) > Your solution is correct, except for one thing. When you start the while loop 'guess' is not yet defined. That's why it gives you an error. You need to define 'guess' before you start your while loop, like so... number = 44 guess = 0 while guess != number : guess = int(raw_input("Guess a number between 1 - 100: ")) if guess > number : print ("Too high") elif guess < number : print ("Too low") else: print ("Just right" ) After that change it worked for me. Did you get this error when you tried your code? Traceback (most recent call last): File "", line 1, in NameError: name 'guess' is not defined >From your question it sounds like I might be missing something though. If that didn't help, please provide more details. -- Jack Trades Pointless Programming Blog -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Mar 17 20:13:58 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 17 Mar 2011 14:13:58 -0500 Subject: [Tutor] Print/Loop Question In-Reply-To: References: Message-ID: <4D825D76.7040401@gmail.com> On 3/17/2011 1:19 PM, Jeff Goodwin wrote: > I'm trying to run the below program and get it to print out feedback > as the loop goes. However, if you enter a number too high or too low, > it skips the print statement under the if and elif clauses and asks > the user to "Guess a number between 1-100" again. Any suggestions on > how to get it to print the "too high" and "too low" responses?? Once > the number is entered correctly it prints "Just Right" and exits > correctly. > number = 44 > while guess != number : > guess = int(raw_input("Guess a number between 1 - 100: ")) > *if* guess > number : > *print* ("Too high") > > *elif* guess < number : > *print* ("Too low") > *else*: > *print* ("Just right" ) That program is not the one you ran! Something is missing! Please also inform us: Python Version Operating System How you run the program. Be sure to Reply-All so a copy goes to the list. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at justuber.com Thu Mar 17 22:47:42 2011 From: lists at justuber.com (lists) Date: Thu, 17 Mar 2011 21:47:42 +0000 Subject: [Tutor] Waiting until a thread ends Message-ID: Hi tutors! I'm not a hard-core programmer but have used Python in systems administration (it makes sense to me to use a scripting language which supports both Windows and Unix). The code below is an excerpt from a module I have written to collect information about hosts on my network and populate a database with this data. I have a couple of thousand PCs to check, so decided to try and use Python's inbuilt threading module to allow me to scan multiple hosts concurrently. I've tried to design this function so that it won't end until all of the threads it spawns have completed. I want it to work like this so I can be sure that each step of the script has completed before moving onto the next step.. I find that if the thread I'm calling uses subprocess.popen (for instance, a function using the windows ping command to collect information), that requests for ping are sent, and are results are returned before the script prints 'FINISH'. When I'm spawning a thread that connects to a PC using WMI however, the output I get is more like this: CONNECTING TO PC1 USING WMI CONNECTING TO PC2 USING WMI CONNECTING TO PC3 USING WMI CONNECTING TO PC4 USING WMI CONNECTING TO PC5 USING WMI PC1 = SERVICE PACK3 FINISH PC2 = SERVICE PACK3 PC3 = SERVICE PACK3 PC4 = SERVICE PACK3 PC5 = SERVICE PACK3 I'm somewhat perplexed by this, because as I understood it: if t.isAlive(): t.join() checks to see if any threads are still running, and if they are, it will wait until the threads have terminated. I'm guessing that I'm missing something here and I wondered if anyone has the time to point out the error of my ways? Thanks :-) def wmiem(): DATABASELOC = shared.DATABASELOC MAXTHREADS = shared.MAXTHREADS hoststate = [] #list of running threads try: conn = sqlite3.connect(DATABASELOC) c = conn.cursor() except: raw_input("Couldn't connect to the database. Press 'Enter' to exit") exit() currenttime = time.time() anhourago = currenttime - 3600 #work out the time an hour ago by subtracting 3600 secs off unixtime tup = (anhourago,) c.execute(""" SELECT DISTINCT hostname FROM ping WHERE pingtime > ? AND pingresult = 1; """, tup) for computer in c.fetchall(): for value in computer: while threading.activeCount() > MAXTHREADS: time.sleep(0.5) print 'wmi started on ' + value t = threading.Thread(target=pingandwmi.whatsmyservicepack, args=(value,)) hoststate.append(t) print threading.activeCount() t.start() if t.isAlive(): t.join() # wait till threads have finished. print 'FINISHED' -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at justuber.com Fri Mar 18 00:12:06 2011 From: lists at justuber.com (lists) Date: Thu, 17 Mar 2011 23:12:06 +0000 Subject: [Tutor] Waiting until a thread ends In-Reply-To: References: Message-ID: > > Only really glanced at this, but you seem to be checking only the last > thread *after* the loop? Surely you should be storing all the threads in a > list (or someplace) as you create them, and then check them all for liveness > and if so join them each in turn, to ensure you only print 'FINISHED' once > you've checked and confirmed that all the threads created have in fact > finished. > > Walter > > That makes absolute sense. Doh on my part! Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at justuber.com Fri Mar 18 01:00:44 2011 From: lists at justuber.com (lists) Date: Fri, 18 Mar 2011 00:00:44 +0000 Subject: [Tutor] Waiting until a thread ends In-Reply-To: References: Message-ID: > Only really glanced at this, but you seem to be checking only the last >> thread *after* the loop? Surely you should be storing all the threads in a >> list (or someplace) as you create them, and then check them all for liveness >> and if so join them each in turn, to ensure you only print 'FINISHED' once >> you've checked and confirmed that all the threads created have in fact >> finished. >> >> Walter >> >> > That makes absolute sense. Doh on my part! > > Thanks! > > Just done a little more reading and came across this in an O'Reilly article here http://www.oreillynet.com/onlamp/blog/2008/01/pymotw_threading.html Seems like an elegant way to accomplish a wait until all running threads have finished. Using enumerate() to wait for all running threads: It is not necessary to retain an explicit handle to all of the daemon threads you start in order to ensure they have completed before exiting the main process. threading.enumerate()returns a list of active Thread instances. The list includes the current thread, and since joining the current thread is not allowed (it introduces a deadlock situation), we must check before joining. import randomimport threadingimport time def worker(): """thread worker function""" t = threading.currentThread() pause = random.randint(1,5) print 'Starting:', t.getName(), 'sleeping', pause time.sleep(pause) print 'Ending :', t.getName() return for i in range(3): t = threading.Thread(target=worker) t.setDaemon(True) t.start() main_thread = threading.currentThread()for t in threading.enumerate(): if t is main_thread: continue print 'Joining :', t.getName() t.join() -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Mar 18 06:43:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Mar 2011 16:43:57 +1100 Subject: [Tutor] Efficiency of while versus (x)range In-Reply-To: References: Message-ID: <4D82F11D.2090603@pearwood.info> Shane O'Connor wrote: > Hi, > > First-time poster here. I've a question about loop efficiency - I was > wondering whether this code: > > i = 0 > while i < 1000: > do something > i+=1 > > is more efficient than: > > for i in range(1000): > do something > > or: > > for i in xrange(1000): > do something You can test this with the timeit module. xrange is about 50% faster than range for a million items, due to the overhead of building the full list: [steve at sylar ~]$ python -m timeit "for n in range(1000000): pass" 10 loops, best of 3: 156 msec per loop [steve at sylar ~]$ python -m timeit "for n in xrange(1000000): pass" 10 loops, best of 3: 106 msec per loop (The "10 loops" part means that timeit repeats the entire code snippet ten times, in order to minimize the effect of other processes and background tasks.) However, if you move building the list into setup code, which doesn't get timed, you will see that there's hardly any difference in time for iterating over a list and an xrange object: [steve at sylar ~]$ python -m timeit -s "items = range(1000000)" "for n in items: pass" 10 loops, best of 3: 96.1 msec per loop [steve at sylar ~]$ python -m timeit -s "items = xrange(1000000)" "for n in items: pass" 10 loops, best of 3: 99.3 msec per loop As for the while loop, it doesn't even come close! [steve at sylar ~]$ python -m timeit "n = 0 > while n < 1000000: n += 1" 10 loops, best of 3: 282 msec per loop The problem is that in a while loop, the looping itself is handled in slow Python code, while in the for loop, it's handled by fast C code (or whatever language the Python virtual machine is written in). We can see this by disassembling the code into virtual machine instructions: [steve at sylar ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> from dis import dis >>> dis(compile("for x in xrange(1000000): pass", "", "exec")) 1 0 SETUP_LOOP 20 (to 23) 3 LOAD_NAME 0 (xrange) 6 LOAD_CONST 0 (1000000) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 6 (to 22) 16 STORE_NAME 1 (x) 19 JUMP_ABSOLUTE 13 >> 22 POP_BLOCK >> 23 LOAD_CONST 1 (None) 26 RETURN_VALUE The for-loop is three virtual instructions: FOR_ITER, STORE_NAME and JUMP_ABSOLUTE. Compare that to the while loop: >>> dis(compile("n = 0\nwhile n < 1000000: n += 1", "", "exec")) 1 0 LOAD_CONST 0 (0) 3 STORE_NAME 0 (n) 2 6 SETUP_LOOP 28 (to 37) >> 9 LOAD_NAME 0 (n) 12 LOAD_CONST 1 (1000000) 15 COMPARE_OP 0 (<) 18 JUMP_IF_FALSE 14 (to 35) 21 POP_TOP 22 LOAD_NAME 0 (n) 25 LOAD_CONST 2 (1) 28 INPLACE_ADD 29 STORE_NAME 0 (n) 32 JUMP_ABSOLUTE 9 >> 35 POP_TOP 36 POP_BLOCK >> 37 LOAD_CONST 3 (None) 40 RETURN_VALUE So the for loop pushes more of the actual effort into the underlying engine, which is faster. Of course, in real-life code, most of this is just theoretical. I see from your comment below that you understand this, but for the benefit of others reading, most of the time, the overhead of the loop body will be much bigger than the loop itself. Who cares whether a loop takes 30 seconds + 100 milliseconds, or 30 seconds + 150 milliseconds? You aren't going to notice the difference. The general advice is best summed up with a quote from the famous computer scientist Donald Knuth: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified." http://en.wikipedia.org/wiki/Program_optimization Other quotes of note: "More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity." - W.A. Wulf "The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet." - Michael A. Jackson > In my mind, the while loop should not allocate as much memory as range or > have the overhead of the iterator of xrange (although aesthetically, I > prefer the x/range style). Is this the case or does the compiler do > something clever here? As a general rule, Python's compiler rarely does anything clever. "Clever" optimizations are remarkable for the number of difficult to notice and even more difficult to fix bugs they introduce. Nevertheless, the PyPy project is experimenting with optimizing just-in-time compilers, and so far are already running about twice as fast as the standard CPython compiler. Similarly, the experimental WPython compiler also does a lot more optimizations than CPython. If you're interested in optimization, PyPy is good to look at: for a handful of carefully selected examples, Python code in PyPy is faster than optimized C code! http://morepypy.blogspot.com/2011/02/pypy-faster-than-c-on-carefully-crafted.html > In particular, I'm using Python 2.4.3 on a web server which needs to run as > fast as possible using as little memory as possible (no surprises there!). > I'm aware that there are more significant optimizations than the above and I > will profile the code rather than prematurely optimize loops at the sake of > readability/errors but I'm still curious about the answer. -- Steven From steve at pearwood.info Fri Mar 18 07:16:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Mar 2011 17:16:25 +1100 Subject: [Tutor] time taken to execute certain task In-Reply-To: References: Message-ID: <4D82F8B9.8060601@pearwood.info> tee chwee liong wrote: > hi, > > i would like to know the time taken to execute a certain task in python. i used time.time and time.clock and i see the time taken is different? what is the right method to use? Neither, or either. For timing small code snippets, the right tool is the timeit module, rather than trying to re-invent the wheel. For large, time consuming functions, the difference between the two is irrelevant. time.time() and time.clock() have different behaviour and different performance characteristics. They are platform dependent -- they are different from each other, and different depending on your operating system. On Windows: time.clock() measures wall clock time and is accurate to better than one microsecond; time.time() is only accurate to 1/60th of a second. On POSIX systems such as Unix, Linux, Apple Macintosh: time.clock() measures CPU time, but is only accurate to 1/100th of a second; time.time() is much more accurate but measures wall clock time. The timeit module automatically chooses the best timer for your operating system, although you can choose another if you prefer. -- Steven From jakesunplugged at gmail.com Fri Mar 18 08:33:48 2011 From: jakesunplugged at gmail.com (jaco erasmus) Date: Fri, 18 Mar 2011 16:33:48 +0900 Subject: [Tutor] binary, ascii, steganography Message-ID: Hi there, list The other day I got bored at work and decided to give this programming thing a try, since Rick Romero said it's becoming all the rage these days. Eventually, I want to end up writing a steganography program, but for now I am still an idiot playing around with text files, substituting letters in a text file with letters from my secret message. Not really all that impressive, but you've got to start somewhere, right? Here's where I become a tech idiot: Eventually, I want to hide messages in photos by changing the value of pixels in the photos, and then compare the two to each other. The I suppose I'll take the resulting 1's and 0's and, somehow, change them into binary or something so that I can eventually magically make them letters. How do I do that? Baby steps, first, though. For the moment, I just want to compare 2 text files, have similar letters give me 0 and different letters give me 1. I want to take those and turn them into letters. How would I do that? Thanks in advance. Jakes -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Mar 18 10:54:27 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Mar 2011 05:54:27 -0400 Subject: [Tutor] binary, ascii, steganography In-Reply-To: References: Message-ID: <4D832BD3.1080907@ieee.org> On 01/-10/-28163 02:59 PM, jaco erasmus wrote: > Hi there, list > The other day I got bored at work and decided to give this programming thing > a try, since Rick Romero said it's becoming all the rage these days. > Eventually, I want to end up writing a steganography program, but for now I > am still an idiot playing around with text files, substituting letters in a > text file with letters from my secret message. Not really all that > impressive, but you've got to start somewhere, right? > Here's where I become a tech idiot: > Eventually, I want to hide messages in photos by changing the value of > pixels in the photos, and then compare the two to each other. The I suppose > I'll take the resulting 1's and 0's and, somehow, change them into binary or > something so that I can eventually magically make them letters. How do I do > that? > Baby steps, first, though. For the moment, I just want to compare 2 text > files, have similar letters give me 0 and different letters give me 1. I > want to take those and turn them into letters. How would I do that? > Thanks in advance. > Jakes > Welcome to the tutor group. You've come to the right place for beginner questions. But people naturally expect you to show you've put some effort into the problem, rather than just asking for an answer. The main key to writing a successful program is decomposing the task into pieces you can solve. If you can do that reliably, you can solve a problem that otherwise appears much too complex for your abilities. So, if you want to compare two text files, the first question is how to get their contents, probably as text objects. Probably you want to use open() and readline() functions, and compose some form of loop. So, start by writing a program that reads and prints a single text file. Next, see how you would open and read a second text file without losing the first. Next, you need to decide just how different these text files are going to be. If you have one text file with the Gettysburg Address, and the other one saying "Hello World", do you want to reject the data, or what? From your wording, I'd guess you're assuming the text files are nearly the same, with the same number of lines, in the same order, and with just a few characters different in each line. DaveA From hugo.yoshi at gmail.com Fri Mar 18 10:55:35 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 18 Mar 2011 10:55:35 +0100 Subject: [Tutor] binary, ascii, steganography In-Reply-To: References: Message-ID: On Fri, Mar 18, 2011 at 8:33 AM, jaco erasmus wrote: > Hi there, list > The other day I got bored at work and decided to give this programming thing > a try, since Rick Romero said it's becoming all the rage these days. > Eventually, I want to end up writing a steganography program, but for now I > am still an idiot playing around with text files, substituting letters in a > text file with letters from my secret message. ?Not really all that > impressive, but you've got to start somewhere, right? > Here's where I become a tech idiot: > Eventually, I want to hide messages in photos by changing the value of > pixels in the photos, and then compare the two to each other. ?The I suppose > I'll take the resulting 1's and 0's and, somehow, change them into binary or > something so that I can eventually magically make them letters. ?How do I do > that? > Baby steps, first, though. ?For the moment, I just want to compare 2 text > files, have similar letters give me 0 and different letters give me 1. ?I > want to take those and turn them into letters. ?How would I do that? > Thanks in advance. > Jakes If you had some code to show us, anything at all, we'd be able to help you much more effectively. What have you tried? From steve at pearwood.info Fri Mar 18 12:16:39 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Mar 2011 22:16:39 +1100 Subject: [Tutor] binary, ascii, steganography In-Reply-To: References: Message-ID: <4D833F17.9030208@pearwood.info> jaco erasmus wrote: > Baby steps, first, though. For the moment, I just want to compare 2 text > files, have similar letters give me 0 and different letters give me 1. I > want to take those and turn them into letters. How would I do that? The basic algorithm is: 1 Read one file into text1 2 Read second file into text2 3 Iterate over both together, taking one character from each 4 If first character == second character then bit = 0 else bit = 1 5 Collect 8 bits and put them together to a number between 0 and 255 6 Convert that number to a character In Python, here's an outline: text1 = open('file1').read() text2 = open('file2').read() characters = [] bits = [] for c1, c2 in zip(text1, text2): if c1 == c2: bits.append(1) else: bits.append(0) if len(bits) == 8: characters.append(bits_to_character(bits)) bits = [] print ''.join(characters) The tricky bit is the function bits_to_character(), which should take a list of eight numbers 0 or 1, and return a character. Try writing that, and email back if you have trouble. -- Steven From coolankur2006 at gmail.com Fri Mar 18 14:56:23 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Fri, 18 Mar 2011 19:26:23 +0530 Subject: [Tutor] books Recommendation Message-ID: Any good ebooks or printed books to get started with the Django framework and web based python?? Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Mar 18 15:10:26 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 18 Mar 2011 10:10:26 -0400 Subject: [Tutor] books Recommendation In-Reply-To: References: Message-ID: On Fri, Mar 18, 2011 at 9:56 AM, ANKUR AGGARWAL wrote: > Any good ebooks or printed books to get started with the Django framework > and web based python?? > Ankur Aggarwal > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Start with the Djangoproject.com tutorials. They also have a list of other resources on that site. I like the Apress books, and a book called Python Web Develpment with Django from Addison Wesley publishing And of course this list! -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From linsihong2003 at yahoo.com Fri Mar 18 17:46:47 2011 From: linsihong2003 at yahoo.com (sihong lin) Date: Fri, 18 Mar 2011 09:46:47 -0700 (PDT) Subject: [Tutor] python.py with no console Message-ID: <991675.82040.qm@web36403.mail.mud.yahoo.com> hi, Those days the idle couldn't open in windows 7. Today I found the type of file python.py(c:\Python27\lib\idlelib) is "no console". what is it means? that is why the idle couldn't open, right? thanks Sharon? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 18 20:16:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Mar 2011 19:16:16 -0000 Subject: [Tutor] python.py with no console References: <991675.82040.qm@web36403.mail.mud.yahoo.com> Message-ID: "sihong lin" wrote > Those days the idle couldn't open in windows 7. > Today I found the type of file python.py(c:\Python27\lib\idlelib) is > "no console". what is it means? that is why the idle couldn't > open, right? No, that just means you don't get a black DOS window in the background. But since I don't have Win 7 I can't comment on the reason you have an IDLE problem, but I believe it should work OK in Windows 7. Can anyone else confirm? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From drbedsole at gmail.com Fri Mar 18 20:21:19 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 18 Mar 2011 15:21:19 -0400 Subject: [Tutor] python.py with no console In-Reply-To: References: <991675.82040.qm@web36403.mail.mud.yahoo.com> Message-ID: Hi folks, On Fri, Mar 18, 2011 at 3:16 PM, Alan Gauld wrote: > > "sihong lin" wrote >> >> Those days the idle couldn't open in windows 7. >> Today I found the type of file python.py(c:\Python27\lib\idlelib) is >> "no console". what is it means? that is why the idle couldn't >> open, right? > > No, that just means you don't get a black DOS window in the > background. But since I don't have Win 7 I can't comment on > the reason you have an IDLE problem, but I believe it should > work OK in Windows 7. > > Can anyone else confirm? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ IDLE opens ok for me on Windows 7. From drbedsole at gmail.com Fri Mar 18 20:26:54 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 18 Mar 2011 15:26:54 -0400 Subject: [Tutor] python.py with no console In-Reply-To: <991675.82040.qm@web36403.mail.mud.yahoo.com> References: <991675.82040.qm@web36403.mail.mud.yahoo.com> Message-ID: Hello, On Fri, Mar 18, 2011 at 12:46 PM, sihong lin wrote: > hi, > > Those days the idle couldn't open in windows 7. Today I found the type of > file python.py(c:\Python27\lib\idlelib) is "no console". what is it means? > that is why the idle couldn't open, right? > > thanks > > Sharon > Can you start Python from a command prompt? -------------- next part -------------- An HTML attachment was scrubbed... URL: From openerpmail at gmail.com Sat Mar 19 00:48:58 2011 From: openerpmail at gmail.com (Savyn - OpenERP Mail) Date: Fri, 18 Mar 2011 23:48:58 +0000 Subject: [Tutor] New to programming Message-ID: Dear Everyone I am new to programming (a passion mainly). I have no background in programming. The python.org beginner tutorial seems hard after a few chapters or not sure how to merge requirement with the tutorials. Where and how should I start programming with python for complete beginner? Many thanks Sav From drbedsole at gmail.com Sat Mar 19 00:58:07 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 18 Mar 2011 19:58:07 -0400 Subject: [Tutor] New to programming In-Reply-To: References: Message-ID: Hi, Welcome to the list: On Fri, Mar 18, 2011 at 7:48 PM, Savyn - OpenERP Mail wrote: > Dear Everyone > > I am new to programming (a passion mainly). I have no background in programming. ?The python.org beginner tutorial seems hard after a few chapters or not sure how to merge requirement with the tutorials. > > Where and how should I start programming with python for complete beginner? > > Many thanks > Sav Here's the tutorial I'm doing now. It's for complete programming beginners: http://learnpythonthehardway.org/index Allen Gault (a member of this list) also has a tutorial for beginners at his site: http://www.alan-g.me.uk/ Don From beachkidken at gmail.com Sat Mar 19 01:23:42 2011 From: beachkidken at gmail.com (Ken G.) Date: Fri, 18 Mar 2011 20:23:42 -0400 Subject: [Tutor] New to programming In-Reply-To: References: Message-ID: <4D83F78E.6010604@gmail.com> You may want to check out a short article entitled "Instant Hacking" by Magnus Lie Hetland. It is an introduction to programming using Python as an example. In the first paragraph thereby mentioned, there is a link to another easy article titled "Instant Python" written by the same author. He had already has written three Python books. Ken On 03/18/2011 07:48 PM, Savyn - OpenERP Mail wrote: > Dear Everyone > > I am new to programming (a passion mainly). I have no background in programming. The python.org beginner tutorial seems hard after a few chapters or not sure how to merge requirement with the tutorials. > > Where and how should I start programming with python for complete beginner? > > Many thanks > Sav > From alan.gauld at btinternet.com Sat Mar 19 02:58:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Mar 2011 01:58:42 -0000 Subject: [Tutor] New to programming References: Message-ID: "Savyn - OpenERP Mail" wrote > I am new to programming (a passion mainly). > I have no background in programming. Check out the Non Programmers section of the Python web site it has several tutorials designed for complete beginners. The official tutorioal is really for those who can already program. http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Try a few of the tutorials lisdted till you find one that gels with your way of thinking then stick with it. Post questions here. Always include full error messages plus which Python version and OS you are using. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jakesunplugged at gmail.com Sat Mar 19 07:13:20 2011 From: jakesunplugged at gmail.com (jaco erasmus) Date: Sat, 19 Mar 2011 15:13:20 +0900 Subject: [Tutor] binary, ascii, steganography Message-ID: Thank you for the help, everyone. Like I said, I got the basics for my text file comparison, but my problem is with how to get binary to text, so your suggestions are greatly appreciated. I'll get to it! (00000001 = a, 00000010 = b, ...) Cheers, and thanks again. Jakes -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Mar 19 07:32:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Mar 2011 17:32:35 +1100 Subject: [Tutor] binary, ascii, steganography In-Reply-To: References: Message-ID: <4D844E03.1070302@pearwood.info> jaco erasmus wrote: > Thank you for the help, everyone. > Like I said, I got the basics for my text file comparison, but my problem is > with how to get binary to text, so your suggestions are greatly appreciated. > I'll get to it! (00000001 = a, 00000010 = b, ...) >>> int('01101110', 2) 110 >>> chr(110) 'n' Is that enough of a hint? :) -- Steven From alan.gauld at btinternet.com Sat Mar 19 10:58:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Mar 2011 09:58:57 -0000 Subject: [Tutor] binary, ascii, steganography References: <4D844E03.1070302@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> with how to get binary to text, so your suggestions are greatly >> appreciated. >> I'll get to it! (00000001 = a, 00000010 = b, ...) > > >>> int('01101110', 2) > 110 > >>> chr(110) > 'n' And if you really want to use non standard character values you could look at the string maketrans() function and string.translate() method... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lists at justuber.com Sat Mar 19 11:38:32 2011 From: lists at justuber.com (lists) Date: Sat, 19 Mar 2011 10:38:32 +0000 Subject: [Tutor] Waiting until a thread ends In-Reply-To: References: Message-ID: > > >> Only really glanced at this, but you seem to be checking only the last >>> thread *after* the loop? Surely you should be storing all the threads in a >>> list (or someplace) as you create them, and then check them all for liveness >>> and if so join them each in turn, to ensure you only print 'FINISHED' once >>> you've checked and confirmed that all the threads created have in fact >>> finished. >>> >>> Walter >>> >>> >> That makes absolute sense. Doh on my part! >> >> Thanks! >> >> > Just done a little more reading and came across this in an O'Reilly article > here http://www.oreillynet.com/onlamp/blog/2008/01/pymotw_threading.html > > Seems like an elegant way to accomplish a wait until all running threads > have finished. > > Using enumerate() to wait for all running threads: > > It is not necessary to retain an explicit handle to all of the daemon > threads you start in order to ensure they have completed before exiting the > main process. threading.enumerate()returns a list of active Thread instances. > The list includes the current thread, and since joining the current thread > is not allowed (it introduces a deadlock situation), we must check before > joining. > > In my continuing quest the find the best way of doing this I came across the following method: for thread in threading.enumerate(): if thread is not threading.currentThread(): thread.join() print 'FINISHED' In my newbie understanding, you can't join() the current thread, because it's the main thread (the one from which the others are called), join()ing it would lock the program up (it would never complete). The above only join()s a thread if it isn't the current thread, thus (hopefully) getting around this. Swapping my earlier stupid code for this seems to work as expected in my tests. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajitsd at gmail.com Sat Mar 19 15:44:34 2011 From: ajitsd at gmail.com (Ajit Deshpande) Date: Sat, 19 Mar 2011 07:44:34 -0700 Subject: [Tutor] lambda Message-ID: I am trying to figure out where lambda functions can be useful. Has anyone used them in real world? >From my reading so far, I hear people claim that lambda can be a useful replacement for small functions. Most examples didn't make much sense to me. Why would anyone use a one liner anonymous function, if you never plan to use it elsewhere? You would then be implementing the logic directly in the line, isn't it?. Functions are useful if they plan to get called multiple times within your code. For example: add_one = lambda x: x + 1 In real world, why would I use a lambda for this. I would simply do: add_one = x + 1 Can you provide some useful use cases for lambda functions? ~ Ajit Deshpande -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Sat Mar 19 15:50:30 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sat, 19 Mar 2011 16:50:30 +0200 Subject: [Tutor] Need some clarification on this Message-ID: >>>a=5 >>>b=5 >>>a == b True >>>a is b True My question is, why "a is b" is true. What I expected it to be is that, a and b are different things with same value. From joel.goldstick at gmail.com Sat Mar 19 15:54:49 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 19 Mar 2011 10:54:49 -0400 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: 2011/3/19 Ya?ar Arabac? > >>>a=5 > >>>b=5 > >>>a == b > True > >>>a is b > True > > My question is, why "a is b" is true. What I expected it to be is that, a > and b are different things with same value. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > True means not zero, not "". Any numeric value but 0 is true. so you have True and True. I think what you are thinking of would be a == b. Since a does not equal b, the result is False -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Mar 19 16:01:17 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 19 Mar 2011 11:01:17 -0400 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: 2011/3/19 Ya?ar Arabac? > >>>a=5 > >>>b=5 > >>>a == b > True > >>>a is b > True > > My question is, why "a is b" is true. What I expected it to be is that, a > and b are different things with same value. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Oops. I misread your post. I (why I don't know) thought I saw a = 5, b = 4. a and b are names. Python has an integer of 5 from a = 5, so it just refers to that same object with b. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Sat Mar 19 16:06:27 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sat, 19 Mar 2011 15:06:27 +0000 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: <4D84C673.6060000@gmail.com> On 19/03/11 14:44, Ajit Deshpande wrote: > I am trying to figure out where lambda functions can be useful. Has > anyone used them in real world? > > From my reading so far, I hear people claim that lambda can be a > useful replacement for small functions. Most examples didn't make > much sense to me. Why would anyone use a one liner anonymous function, > if you never plan to use it elsewhere? You would then be implementing > the logic directly in the line, isn't it?. Functions are useful if > they plan to get called multiple times within your code. > > For example: > > add_one = lambda x: x + 1 > > In real world, why would I use a lambda for this. I would simply do: > > add_one = x + 1 > > Can you provide some useful use cases for lambda functions? > > ~ Ajit Deshpande Here's one from the python docs, reduce takes a function so technically the programmer only uses it once but the program calls it many times. Map is another that works similarly. Have a look into functional programming as that's the branch of computer science those two functions and lambdas tend to come from I believe. http://docs.python.org/library/functions.html?highlight=lambda#reduce HTH, Adam. From bgailer at gmail.com Sat Mar 19 16:08:39 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Mar 2011 10:08:39 -0500 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: <4D84C6F7.8080107@gmail.com> On 3/19/2011 9:44 AM, Ajit Deshpande wrote: > I am trying to figure out where lambda functions can be useful. Has > anyone used them in real world? > > From my reading so far, I hear people claim that lambda can be a > useful replacement for small functions. Most examples didn't make > much sense to me. Why would anyone use a one liner anonymous function, > if you never plan to use it elsewhere? You would then be implementing > the logic directly in the line, isn't it?. Functions are useful if > they plan to get called multiple times within your code. > > For example: > > add_one = lambda x: x + 1 > > In real world, why would I use a lambda for this. I would simply do: > > add_one = x + 1 > > Can you provide some useful use cases for lambda functions? One is the list sort method. someList.sort([cmp[, key[, reverse]]]) /"cmp/ specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower())." -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Mar 19 16:17:15 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Mar 2011 10:17:15 -0500 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: <4D84C8FB.7050405@gmail.com> In my Python Pipelines program I have the following opts = { 'characters' : (lambda rec, tot: tot + len(rec), 0), 'words' : (lambda rec, tot: tot + len(rec.split()), 0), 'lines' : (lambda rec, tot: tot + 1, 0), 'minline' : (lambda rec, tot: min(len(rec), tot), 999999999), 'maxline' : (lambda rec, tot: max(len(rec), tot), 0) } The user specifies option(s) (the dictionary keys). Thje program then creates a class instance for each option, passing the corresponding function as a class initialization parameter: for option in options: func, initTotal = Count.opts.get(option , 0) if func: ctr = Count.CounterClass(func, spec, initTotal) it made lots of sense to me to code these as lambdas. The alternatve would have been 4 defs: (4 more lines of code and more indirection in code reading). def char(rec, tot): return tot + len(rec) etc -- Bob Gailer 919-636-4239 Chapel Hill NC From emmanuel.ruellan at laposte.net Sat Mar 19 16:35:16 2011 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Sat, 19 Mar 2011 16:35:16 +0100 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: 2011/3/19 Ya?ar Arabac? > > > >>>a=5 > >>>b=5 > >>>a == b > True > >>>a is b > True > > My question is, why "a is b" is true. What I expected it to be is that, a > and b are different things with same value. > Even stranger: >>> a = 10**10 >>> b = 10**10 >>> a == b True >>> a is b False >>> a = 5 >>> b = 5 >>> a == b True >>> a is b True In the general case, you're right: a and b point to two different objects, but there is also some kind of optimisation for small numbers, and as a result when a = 5 and b = 5, both point the same '5' object. Emmanuel Ruellan -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at gmail.com Sat Mar 19 16:47:48 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sat, 19 Mar 2011 08:47:48 -0700 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: <201103190847.48440.thudfoo@gmail.com> On Saturday 2011 March 19 08:35, Emmanuel Ruellan wrote: > 2011/3/19 Ya?ar Arabac? > > > >>>a=5 > > >>>b=5 > > >>>a == b > > > > True > > > > >>>a is b > > > > True > > > > My question is, why "a is b" is true. What I expected it to be is that, a > > and b are different things with same value. > > Even stranger: > >>> a = 10**10 > >>> b = 10**10 > >>> a == b > > True > > >>> a is b > > False > > >>> a = 5 > >>> b = 5 > >>> a == b > > True > > >>> a is b > > True > > In the general case, you're right: a and b point to two different objects, > but there is also some kind of optimisation for small numbers, and as a > result when a = 5 and b = 5, both point the same '5' object. > > Emmanuel Ruellan From http://docs.python.org/c-api/int.html The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. -- I have seen the future and I am not in it. From hugo.yoshi at gmail.com Sat Mar 19 16:50:16 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 19 Mar 2011 16:50:16 +0100 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: 2011/3/19 Ya?ar Arabac? : >>>>a=5 >>>>b=5 >>>>a == b > True >>>>a is b > True > > My question is, why "a is b" is true. What I expected it to be is that, a > and b are different things with same value. > It's an optimization thing. When you type "a=5," the python interpreter is obligated to give you an integer object with the value 5. However, it doesn't need to be a *new* object. If an interpreter happens to have an object like that lying around already, it is perfectly allowed to give you that one. This doesn't mess things up for anyone, because integers are immutable. You can't change them, so it's safe to give the same object to different people. Interpreters can make the same optimization for strings, if they like. It makes it more efficient (since they don't have to allocate a new object) without changing the semantics of the language. From ajitsd at gmail.com Sat Mar 19 18:18:38 2011 From: ajitsd at gmail.com (Ajit Deshpande) Date: Sat, 19 Mar 2011 10:18:38 -0700 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: This is a special feature called interning in python. As of Python 2.6, values of -5 to 105 are never cleared from memory for performance reasons. This is applicable to integers only. "==" is a value comparator, whereas "is" is a reference compartor. Check this interesting extension to your code: >>> a=5.0 >>> b=5.0 >>> a==b True >>> a is b False Because I used "5.0" instead of "5", the "is" operator is giving a different result ("False") ~ Ajit Deshpande 2011/3/19 Ya?ar Arabac? > >>>a=5 > >>>b=5 > >>>a == b > True > >>>a is b > True > > My question is, why "a is b" is true. What I expected it to be is that, a > and b are different things with same value. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Mar 19 19:17:48 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Mar 2011 14:17:48 -0400 Subject: [Tutor] Need some clarification on this In-Reply-To: References: Message-ID: <4D84F34C.50300@ieee.org> On 01/-10/-28163 02:59 PM, Joel Goldstick wrote: > 2011/3/19 Ya?ar Arabac? > >>>>> a=5 >>>>> b=5 >>>>> a == b >> True >>>>> a is b >> True >> >> My question is, why "a is b" is true. What I expected it to be is that, a >> and b are different things with same value. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Oops. I misread your post. I (why I don't know) thought I saw a = 5, b = > 4. > > a and b are names. Python has an integer of 5 from a = 5, so it just refers > to that same object with b. > > > Sometimes a particular implementation of Python will reuse the same object, if it's immutable. So certain strings and certain integers may be reused, presumably to save some space. But you cannot count on it. If you tried the same thing with a value of 741, you'd probably get a different answer. It's not time-efficient for Python to go hunting through all the existing objects to find a match, so this optimization is done pretty narrowly. You seldom want to use 'is' on an integer or a string anyway. Use == unless it really matters, which is usually either a custom object, or a singleton like True. DaveA From davea at ieee.org Sat Mar 19 19:20:20 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Mar 2011 14:20:20 -0400 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: <4D84F3E4.2010106@ieee.org> On 01/-10/-28163 02:59 PM, Ajit Deshpande wrote: > I am trying to figure out where lambda functions can be useful. Has anyone > used them in real world? > >> From my reading so far, I hear people claim that lambda can be a useful > replacement for small functions. Most examples didn't make much sense to > me. Why would anyone use a one liner anonymous function, if you never plan > to use it elsewhere? You would then be implementing the logic directly in > the line, isn't it?. Functions are useful if they plan to get called > multiple times within your code. > > For example: > > add_one = lambda x: x + 1 > > In real world, why would I use a lambda for this. I would simply do: > > add_one = x + 1 > > Can you provide some useful use cases for lambda functions? > > ~ Ajit Deshpande > The other comments are useful. Lambdas are usually used for callback functions. But I wanted to point out that your two add_one objects are not at all equivalent. The first one is a function, which can be called at a later time. The second one is probably an integer, depending of course on the type of x. To get the equivalent of the lambda function above, you'd use def add_one(x): return x+1 DaveA From lists at justuber.com Sun Mar 20 00:36:54 2011 From: lists at justuber.com (lists) Date: Sat, 19 Mar 2011 23:36:54 +0000 Subject: [Tutor] Waiting until a thread ends In-Reply-To: References: Message-ID: > > > >> In my continuing quest the find the best way of doing this I came across >> the following method: >> >> for thread in threading.enumerate(): >> if thread is not threading.currentThread(): >> thread.join() >> print 'FINISHED' >> >> In my newbie understanding, you can't join() the current thread, because >> it's the main thread (the one from which the others are called), join()ing >> it would lock the program up (it would never complete). >> >> The above only join()s a thread if it isn't the current thread, thus >> (hopefully) getting around this. Swapping my earlier stupid code for this >> seems to work as expected in my tests. >> > > Thanks for the postbacks, it's been useful/interesting for me. > > Best, > > Walter > I'm really pleased that it was of some help to somebody else too. Kind Regards, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 20 01:57:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Mar 2011 00:57:21 -0000 Subject: [Tutor] lambda References: Message-ID: "Ajit Deshpande" wrote >I am trying to figure out where lambda functions can be useful. Has >anyone > used them in real world? Yers lots of people, all over the place. They are very useful things. > Why would anyone use a one liner anonymous function, To pass as an argument to another function. GUI widgets for example frequently take a function as an argument so that when they are clicked they call the function. If the function is only doing something trivial a lambda is better than writing a small function just to pass to the GUI widget. Similarly functions like sort() often take functions as arguments so that you can customise the sort algorithm. Often these are just one liners defining how a comparison should work. lambda comes from the matth/computer science term lambda calculus and lambdas are at the very core of theoretical computing. Functional programming is a style closely aligned to computer science theory and as such makes much use of lambdas (Lisp does this too). You can read more on the use of Lambdas and functional programming in the Functional Programming topic of my tutorial. You can see lambdas in use in the GUI topic of my tutor. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Mar 20 02:07:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Mar 2011 12:07:12 +1100 Subject: [Tutor] lambda In-Reply-To: References: Message-ID: <4D855340.2020202@pearwood.info> Ajit Deshpande wrote: > I am trying to figure out where lambda functions can be useful. Has anyone > used them in real world? Of course. lambdas are especially useful for callback functions, which are especially common when doing GUI programming. > From my reading so far, I hear people claim that lambda can be a useful > replacement for small functions. Most examples didn't make much sense to > me. Why would anyone use a one liner anonymous function, if you never plan > to use it elsewhere? That's precisely the point -- why would you define a non-anonymous function that you only use once? def spam(x): return x + something register_handler(spam) # Provide a callback to some part of your app # never use spam again is better written as: register_handler(lambda x: x+something) > You would then be implementing the logic directly in > the line, isn't it?. Functions are useful if they plan to get called > multiple times within your code. That's often the case, but not necessarily. > For example: > > add_one = lambda x: x + 1 This defines a function "add_one". This is equivalent to writing: def add_one(x): return x+1 > In real world, why would I use a lambda for this. I would simply do: > > add_one = x + 1 This takes the current value of x, adds one to it, and assigns it to the very badly named variable "add_one". > Can you provide some useful use cases for lambda functions? Sorting with comparison or key functions. min or max with a key function. Callbacks. map reduce Solving numerical equations. There are probably others, but they're the obvious ones. Here's an example you can try: text = """Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.""" words = text.lower().split() sorted(words) # sort in alphabetical order Now suppose you want to sort by the number of vowels. Here's how you can do it with an anonymous key function: sorted(words, key=lambda word: sum(word.count(c) for c in 'aeiou')) -- Steven From ajitsd at gmail.com Sun Mar 20 17:01:26 2011 From: ajitsd at gmail.com (Ajit Deshpande) Date: Sun, 20 Mar 2011 09:01:26 -0700 Subject: [Tutor] lambda In-Reply-To: <4D855340.2020202@pearwood.info> References: <4D855340.2020202@pearwood.info> Message-ID: Fantastic explanation everyone. Thanks a lot. Looking forward to using lambda going forward. ~ Ajit Deshpande On Sat, Mar 19, 2011 at 6:07 PM, Steven D'Aprano wrote: > Ajit Deshpande wrote: > >> I am trying to figure out where lambda functions can be useful. Has anyone >> used them in real world? >> > > Of course. lambdas are especially useful for callback functions, which are > especially common when doing GUI programming. > > > > From my reading so far, I hear people claim that lambda can be a useful >> replacement for small functions. Most examples didn't make much sense to >> me. Why would anyone use a one liner anonymous function, if you never plan >> to use it elsewhere? >> > > That's precisely the point -- why would you define a non-anonymous function > that you only use once? > > def spam(x): > return x + something > > register_handler(spam) # Provide a callback to some part of your app > # never use spam again > > > is better written as: > > register_handler(lambda x: x+something) > > > > You would then be implementing the logic directly in >> the line, isn't it?. Functions are useful if they plan to get called >> multiple times within your code. >> > > That's often the case, but not necessarily. > > > > > For example: >> >> add_one = lambda x: x + 1 >> > > This defines a function "add_one". This is equivalent to writing: > > def add_one(x): > return x+1 > > > In real world, why would I use a lambda for this. I would simply do: >> >> add_one = x + 1 >> > > This takes the current value of x, adds one to it, and assigns it to the > very badly named variable "add_one". > > > > Can you provide some useful use cases for lambda functions? >> > > Sorting with comparison or key functions. > min or max with a key function. > Callbacks. > map > reduce > Solving numerical equations. > > There are probably others, but they're the obvious ones. > > Here's an example you can try: > > text = """Li Europan lingues es membres del sam familie. Lor separat > existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li > sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation > e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua > franca: On refusa continuar payar custosi traductores.""" > words = text.lower().split() > sorted(words) # sort in alphabetical order > > > Now suppose you want to sort by the number of vowels. Here's how you can do > it with an anonymous key function: > > sorted(words, key=lambda word: sum(word.count(c) for c in 'aeiou')) > > > -- > Steven > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolankur2006 at gmail.com Sun Mar 20 18:46:34 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Sun, 20 Mar 2011 23:16:34 +0530 Subject: [Tutor] Difference Message-ID: Hey want to know whats the difference between the pygame.display.update() and pygame.display.flip() An explanation with the example would be grea. Thanks In Advance Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sun Mar 20 18:55:53 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 20 Mar 2011 13:55:53 -0400 (EDT) Subject: [Tutor] Difference In-Reply-To: References: Message-ID: <8CDB53F2F7DF966-158C-16483@webmail-d030.sysops.aol.com> -----Original Message----- From: ANKUR AGGARWAL To: tutor Sent: Sun, Mar 20, 2011 1:49 pm Subject: [Tutor] Difference Hey want to know whats the difference between the pygame.display.update() and pygame.display.flip() An explanation with the example would be grea. Thanks In Advance Ankur Aggarwal ------------------------------------------------------------------ http://www.pygame.org/docs/ref/display.html#pygame.display.flip Read that and the section below. In the future, pygame questions will be better off answered by their mailing list or similar communication structure. (Forgive for the poor formatting etc, on the road using a web client) From linsihong2003 at yahoo.com Mon Mar 21 01:58:58 2011 From: linsihong2003 at yahoo.com (sihong lin) Date: Sun, 20 Mar 2011 17:58:58 -0700 (PDT) Subject: [Tutor] what is it mean--- File "", line 1 Message-ID: <267151.8176.qm@web36405.mail.mud.yahoo.com> Hi, ?I just write a simplest file test.py with only one line--print "hello", when I run it in command line: >>> python test.py the follow message comes out: File "" , line 1 ?python test SyntaxError: invalid syntax but, the file can run in shell, also in the command line, I put >>> print "hello" output is fine, "Hello" thanks Sharon -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Mon Mar 21 02:14:23 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 20 Mar 2011 21:14:23 -0400 (EDT) Subject: [Tutor] what is it mean--- File "", line 1 In-Reply-To: <267151.8176.qm@web36405.mail.mud.yahoo.com> References: <267151.8176.qm@web36405.mail.mud.yahoo.com> Message-ID: <8CDB57C725791BB-BB0-16EC9@webmail-d099.sysops.aol.com> Hi, ?I just write a simplest file test.py with only one line--print "hello", when I run it in command line: >>> python test.py the follow message comes out: File "" , line 1 ?python test SyntaxError: invalid syntax but, the file can run in shell, also in the command line, I put >>> print "hello" output is fine, "Hello" thanks Sharon ------------------------------------------------------------------------- --------------------------- You're trying to run the file from the Python interpreter. It does work in the shell, because that's what the shell does! So, exit out of the Python interpreter before trying to run that command (>>>exit, or Ctrl-D). -- Corey Richardson (Forgive the horrible formatting and HTML, on the road using a web client) From andreengels at gmail.com Mon Mar 21 06:27:42 2011 From: andreengels at gmail.com (Andre Engels) Date: Mon, 21 Mar 2011 06:27:42 +0100 Subject: [Tutor] what is it mean--- File "", line 1 In-Reply-To: <267151.8176.qm@web36405.mail.mud.yahoo.com> References: <267151.8176.qm@web36405.mail.mud.yahoo.com> Message-ID: On Mon, Mar 21, 2011 at 1:58 AM, sihong lin wrote: > Hi, > > I just write a simplest file test.py with only one line--print "hello", > when I run it in command line: > >>> python test.py > > the follow message comes out: > > File "" , line 1 > python test > > SyntaxError: invalid syntax > > but, the file can run in shell, also in the command line, I put > > >>> print "hello" > > output is fine, "Hello" > In the shell you can run shell commands, in the Python command line you can run Python code. "python test.py" is a shell command, not Python code, so you can run it in the shell, but not on the Python command line. "print "hello"" is Python code, so you can run it on the Python command line, but not in the shell. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Mon Mar 21 16:11:49 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 21 Mar 2011 08:11:49 -0700 (PDT) Subject: [Tutor] Saving information for my program Message-ID: <725735.80410.qm@web130223.mail.mud.yahoo.com> I apologize now but I'm going to be spamming the tutor list as I have just decided to create an extremely ambitious project for someone of my level. Anyhow, I will start with my first question. How do I save user created information in python? In my progam I will have users input various "attributes" of people they like (age, height, movies they have been in, songs they sung in, favorite part of them, important links dealing with them, etc), and I'd like to know how to save these things so that even after you stop running the program they are saved and when you start the program again, these variables are loaded. This part of my program will be sort of like an offline-wiki-gui-thingie. I was planning on using classes for each person so that I could store their attributes that way . jessica = Profile() jessica.name = "jessica ngorn" jessica.age = 25 jessica.favorite_song = "chinpo no uta" I was thinking I have 2 options, which is save the information to a text file a write / read it in every session, but I have no idea how to do this with class attributes. I know how to do it for like a paragraph of text, but I have no idea how to do it with classes and their attributes. The other option I was thinking about was using the pickle module. I have never used it, but I read the documentation, and I'm not exactly sure how to use it... it says it only saves the class "name", but not the body (same for functions), but how would that help me? Well if you can contribute to helping me please do. Linking me to stuff to read is great, explaining it here is great, writing short example code is great too, anything helps. ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Mar 21 16:18:28 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 21 Mar 2011 11:18:28 -0400 Subject: [Tutor] Saving information for my program In-Reply-To: <725735.80410.qm@web130223.mail.mud.yahoo.com> References: <725735.80410.qm@web130223.mail.mud.yahoo.com> Message-ID: On Mon, Mar 21, 2011 at 11:11 AM, michael scott wrote: > I apologize now but I'm going to be spamming the tutor list as I have just > decided to create an extremely ambitious project for someone of my level. > Anyhow, I will start with my first question. > > How do I save user created information in python? > > In my progam I will have users input various "attributes" of people they > like (age, height, movies they have been in, songs they sung in, favorite > part of them, important links dealing with them, etc), and I'd like to know > how to save these things so that even after you stop running the program > they are saved and when you start the program again, these variables are > loaded. This part of my program will be sort of like an > offline-wiki-gui-thingie. > > I was planning on using classes for each person so that I could store their > attributes that way . > jessica = Profile() > jessica.name = "jessica ngorn" > jessica.age = 25 > jessica.favorite_song = "chinpo no uta" > > I was thinking I have 2 options, which is save the information to a text > file a write / read it in every session, but I have no idea how to do this > with class attributes. I know how to do it for like a paragraph of text, but > I have no idea how to do it with classes and their attributes. > > The other option I was thinking about was using the pickle module. I have > never used it, but I read the documentation, and I'm not exactly sure how to > use it... it says it only saves the class "name", but not the body (same for > functions), but how would that help me? > > Well if you can contribute to helping me please do. Linking me to stuff to > read is great, explaining it here is great, writing short example code is > great too, anything helps. > ---- > What is it about you... that intrigues me so? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You need to read about forms and models. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon Mar 21 16:30:49 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 21 Mar 2011 11:30:49 -0400 Subject: [Tutor] Saving information for my program In-Reply-To: <725735.80410.qm@web130223.mail.mud.yahoo.com> References: <725735.80410.qm@web130223.mail.mud.yahoo.com> Message-ID: On Mon, Mar 21, 2011 at 11:11 AM, michael scott wrote: > I apologize now but I'm going to be spamming the tutor list as I have just > decided to create an extremely ambitious project for someone of my level. > Anyhow, I will start with my first question. > > How do I save user created information in python? > > In my progam I will have users input various "attributes" of people they > like (age, height, movies they have been in, songs they sung in, favorite > part of them, important links dealing with them, etc), and I'd like to know > how to save these things so that even after you stop running the program > they are saved and when you start the program again, these variables are > loaded. This part of my program will be sort of like an > offline-wiki-gui-thingie. > > I was planning on using classes for each person so that I could store their > attributes that way . > jessica = Profile() > jessica.name = "jessica ngorn" > jessica.age = 25 > jessica.favorite_song = "chinpo no uta" > > I was thinking I have 2 options, which is save the information to a text > file a write / read it in every session, but I have no idea how to do this > with class attributes. I know how to do it for like a paragraph of text, but > I have no idea how to do it with classes and their attributes. > > The other option I was thinking about was using the pickle module. I have > never used it, but I read the documentation, and I'm not exactly sure how to > use it... it says it only saves the class "name", but not the body (same for > functions), but how would that help me? > > Well if you can contribute to helping me please do. Linking me to stuff to > read is great, explaining it here is great, writing short example code is > great too, anything helps. > ---- > What is it about you... that intrigues me so? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > This would probably be a good opportunity for you to learn about SQL and specifically SQlite3, which comes with current versions of Python. For what you are describing, you could probably have a single table in a database handle all of this. For it to populate immediately, have your program call in its __init__ whatever program you have to extract all the data from the database, then create all of your Profile objects. I think if you just read up on SQlite3 and what it can do, or SQL more generally, you will have an Aha! moment on your own. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Mar 21 19:59:49 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 Mar 2011 13:59:49 -0500 Subject: [Tutor] Saving information for my program In-Reply-To: <725735.80410.qm@web130223.mail.mud.yahoo.com> References: <725735.80410.qm@web130223.mail.mud.yahoo.com> Message-ID: <4D87A025.20305@gmail.com> On 3/21/2011 10:11 AM, michael scott wrote: > I apologize now but I'm going to be spamming the tutor list as I have > just decided to create an extremely ambitious project for someone of > my level. Anyhow, I will start with my first question. Please no more apologies. Just post your questions. > > How do I save user created information in python? I don't know about Joel Goldstick's advice. Seems a bit advanced or specialized. I suggest you either pickle and store the pickled objects in a (as James suggested) Sqlite database. Or use the shelve module which pickles and saves under a key akin to a dictionary. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Mar 21 20:06:46 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 21 Mar 2011 12:06:46 -0700 Subject: [Tutor] Saving information for my program In-Reply-To: <725735.80410.qm@web130223.mail.mud.yahoo.com> References: <725735.80410.qm@web130223.mail.mud.yahoo.com> Message-ID: On Mon, Mar 21, 2011 at 8:11 AM, michael scott wrote: > How do I save user created information in python? > As others have mentioned, SQL support is bundled with Python. If your collection of people and their attributes is expected to grow much, that would definitely be how I'd go. However, there's another time-tested option: the config or INI file. Even if you store your data in an SQL database, you might want to keep the connection parameters (how your program talks to that database) in a human-readable format... I also like to keep user preferences (size/location of main window, favorite printer, whatever) in an INI file (I know this isn't universal, but it's how I like to do it - I dabbled in XML config files, but the signal/noise ratio is way too low.) Python comes with the ConfigParser module: http://docs.python.org/library/configparser.html and Michael Foord has an excellent upgrade called ConfigObj: http://www.voidspace.org.uk/python/modules.shtml#configobj -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Mar 21 20:54:22 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 21 Mar 2011 19:54:22 +0000 Subject: [Tutor] Saving information for my program In-Reply-To: <725735.80410.qm@web130223.mail.mud.yahoo.com> References: <725735.80410.qm@web130223.mail.mud.yahoo.com> Message-ID: On 21 March 2011 15:11, michael scott wrote: > I was thinking I have 2 options, which is save the information to a text > file a write / read it in every session, but I have no idea how to do this > with class attributes. I know how to do it for like a paragraph of text, but > I have no idea how to do it with classes and their attributes. > If you know how to save text, then you should be able to write your own code to store ("persist") your objects, shouldn't you? Trying to do so might be a good learning excercise... ;) Anyway, I agree with Bob Gailer's advice, and I'd suggest you play around with several options, learning as you go. If you design your code appropriately, you can even start now with e.g. a persistence layer that uses Pickle (or your own home-brewn save/load code that uses ini file or text file or whatever), and later move to an SQLite store or even another relational database engine. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Mon Mar 21 21:12:18 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Mon, 21 Mar 2011 16:12:18 -0400 Subject: [Tutor] help with user input Message-ID: I'm going through a tutorial called "Learn Python the Hard Way" by Zed Shaw. At the end of his lessons he has "Extra Credit" sessions, and I'm stuck on one. I'm on lesson 35, here is a link to it: http://blamcast.net/python/ex35.html The lesson involves creating a very simple text based game. One of the functions accepts user input: def gold_room(): print "This room is full of gold. How much do you take?" next = raw_input("> ") if "0" in next or "1" in next: how_much = int(next) else: dead("Man, learn to type a number.") if how_much < 50: print "Nice, you're not greedy, you win!" exit(0) else: dead("You greedy bastard!") The instruction from the Extra Credit section reads: The gold_room has a weird way of getting you to type a number. What are all the bugs in this way of doing it? Can you make it better than just checking if "1" or "0" are in the number? Look at how int() works for clues. I have read the documentation for int() and done some googling, but no lights have come on. :-) Here is what I have so far: def gold_room(): print "This room is full of gold. How much do you take?" next = raw_input("> ") if next <= "50": how_much = int(next) else: dead("You were too greedy.") if how_much < 50: print "Nice, you're not greedy, you win!" exit(0) else: dead("Man, learn to type a number!") This works fine as long as the user enters a number. However, if they enter anything else, they just get the first :else statement, "You were too greedy." My googling found solutions using an exception, but that hasn't been introduced yet in the tutorial. How would you solve this without using an exception? Thanks for any help, Don From marc.tompkins at gmail.com Mon Mar 21 21:47:09 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 21 Mar 2011 13:47:09 -0700 Subject: [Tutor] help with user input In-Reply-To: References: Message-ID: On Mon, Mar 21, 2011 at 1:12 PM, Donald Bedsole wrote: > > This works fine as long as the user enters a number. However, if they > enter anything else, they just get the first :else statement, "You > were too greedy." > > I think that's because you're trying to do a string comparison, rather than a numeric comparison. (if next <= "50":) You need to convert 'next' to an int FIRST, then compare to 50, not "50". > My googling found solutions using an exception, but that hasn't been > introduced yet in the tutorial. How would you solve this without > using an exception? > > If you don't want to use an exception, check the entered value first (note: I haven't checked my code, so caveat lector) - next = raw_input(">") > if next.isdigit(): > if int(next) < 50: > print "Nice, you're not greedy, you win!" > else: > dead("You were too greedy.") > else: > dead("Man, learn to type a number!") > isdigit() returns True if every character is a digit; False otherwise. http://docs.python.org/library/stdtypes.html Using an exception: next = raw_input(">") > try: > if int(next) < 50: > print "Nice, you're not greedy, you win!" > else: > dead("You were too greedy.") > except ValueError: > dead("Man, learn to type a number!") > Note that I specified ValueError - you want to make your exception handling as specific as possible, so that if really unforeseen things go wrong, your program doesn't blindly treat them as normal. In other words, if any exception other than ValueError were to pop up here, you would want the program to terminate and show you a traceback so you could fix it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Mon Mar 21 22:58:42 2011 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 22 Mar 2011 10:58:42 +1300 Subject: [Tutor] getting the last file in a folder (reliably) Message-ID: Hi I have some code which works nine times out of ten. Maybe some could help me make this a little more robust. I have a bunch of files in a folder with a strict versioning based naming convention, where I want to open the highest version number of a nuke script (not necessarily the one with the newest modification date). So in the example folder contents listed below I want to open "233_bb0072_comp_comp2k_v05.nk" (fourth from the bottom). Every once in a while my python script ends up opening 233_bb0072_comp_comp2k_v04.nk (the next to last correct one). The script I am using is shown below. Can anyone explain why it doesn't always work? 233_bb0072_comp_comp2k_v01.nk 233_bb0072_comp_comp2k_v01.nk~ 233_bb0072_comp_comp2k_v02.nk 233_bb0072_comp_comp2k_v03.nk 233_bb0072_comp_comp2k_v03.nk~ 233_bb0072_comp_comp2k_v04.nk 233_bb0072_comp_comp2k_v04.nk~ 233_bb0072_comp_comp2k_v05.nk 233_bb0072_comp_comp2k_v05.autosave 233_bb0072_comp_comp2k_v05.nk~ 233_bb0072_comp_comp2k_v06.nk ####################################### import os def openNewestCompCommandLine(): theDirectory = "/path/to/my/comps/" theFilesInTheFolder = os.listdir(theDirectory) for aFile in theFilesInTheFolder: if "~" not in aFile: if "autosave" not in aFile: theNukeFileName = aFile theFullPath = theDirectory + theNukeFileName os.system("nuke " + theFullPath) if __name__ == '__main__': openNewestCompCommandLine() for aFile in theFilesInTheFolder: print aFile ################################################ Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Mon Mar 21 23:02:30 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Mon, 21 Mar 2011 18:02:30 -0400 Subject: [Tutor] help with user input In-Reply-To: References: Message-ID: Thank you, Marc On Mon, Mar 21, 2011 at 4:47 PM, Marc Tompkins wrote: > On Mon, Mar 21, 2011 at 1:12 PM, Donald Bedsole wrote: >> >> This works fine as long as the user enters a number. ?However, if they >> enter anything else, they just get the first :else statement, "You >> were too greedy." >> > I think that's because you're trying to do a string comparison, rather than > a numeric comparison. (if next <= "50":)? You need to convert 'next' to an > int FIRST, then compare to 50, not "50". > >> >> My googling found solutions using an exception, but that hasn't been >> introduced yet in the tutorial. ?How would you solve this without >> using an exception? >> > > If you don't want to use an exception, check the entered value first (note: > I haven't checked my code, so caveat lector) - > >> next = raw_input(">") >> if next.isdigit(): >> ? ? if int(next) < 50: >> ??????? print "Nice, you're not greedy, you win!" >> ??? else: >> ??????? dead("You were too greedy.") >> else: >> ??? dead("Man, learn to type a number!") > > isdigit() returns True if every character is a digit; False otherwise. > http://docs.python.org/library/stdtypes.html > > > Using an exception: > >> next = raw_input(">") >> try: >> ? ? if int(next) < 50: >> ??????? print "Nice, you're not greedy, you win!" >> ??? else: >> ??????? dead("You were too greedy.") >> except ValueError: >> ??? dead("Man, learn to type a number!") > > Note that I specified ValueError - you want to make your exception handling > as specific as possible, so that if really unforeseen things go wrong, your > program doesn't blindly treat them as normal.? In other words, if any > exception other than ValueError were to pop up here, you would want the > program to terminate and show you a traceback so you could fix it. > > > It'll take me awhile to digest this. Thanks for your time and your help. From rafadurancastaneda at gmail.com Mon Mar 21 23:20:29 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Mon, 21 Mar 2011 23:20:29 +0100 Subject: [Tutor] getting the last file in a folder (reliably) In-Reply-To: References: Message-ID: You are taking the last file from os.listdir that hasn't neither ~ nor aoutosave, but os.listdir doesn't return a sorted list, so that file is random. You must order or compare in the for loop. 2011/3/21 Pete O'Connell > Hi I have some code which works nine times out of ten. Maybe some could > help me make this a little more robust. I have a bunch of files in a folder > with a strict versioning based naming convention, where I want to open the > highest version number of a nuke script (not necessarily the one with the > newest modification date). So in the example folder contents listed below I > want to open "233_bb0072_comp_comp2k_v05.nk" (fourth from the bottom). Every > once in a while my python script ends up opening > 233_bb0072_comp_comp2k_v04.nk (the next to last correct one). The script I > am using is shown below. Can anyone explain why it doesn't always work? > > > 233_bb0072_comp_comp2k_v01.nk > 233_bb0072_comp_comp2k_v01.nk~ > 233_bb0072_comp_comp2k_v02.nk > 233_bb0072_comp_comp2k_v03.nk > 233_bb0072_comp_comp2k_v03.nk~ > 233_bb0072_comp_comp2k_v04.nk > 233_bb0072_comp_comp2k_v04.nk~ > 233_bb0072_comp_comp2k_v05.nk > 233_bb0072_comp_comp2k_v05.autosave > 233_bb0072_comp_comp2k_v05.nk~ > 233_bb0072_comp_comp2k_v06.nk > > ####################################### > import os > def openNewestCompCommandLine(): > > theDirectory = "/path/to/my/comps/" > theFilesInTheFolder = os.listdir(theDirectory) > for aFile in theFilesInTheFolder: > if "~" not in aFile: > if "autosave" not in aFile: > theNukeFileName = aFile > > theFullPath = theDirectory + theNukeFileName > os.system("nuke " + theFullPath) > if __name__ == '__main__': > openNewestCompCommandLine() > > for aFile in theFilesInTheFolder: > print aFile > ################################################ > Pete > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 21 23:44:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Mar 2011 09:44:59 +1100 Subject: [Tutor] getting the last file in a folder (reliably) In-Reply-To: References: Message-ID: <4D87D4EB.9060204@pearwood.info> Pete O'Connell wrote: > Hi I have some code which works nine times out of ten. Today. Next week it might work zero times out of ten. Your result is a pure accident of the order that the files are created. When you call os.listdir(), you don't get the files in any specific order. The order you receive is the order that they happen to be stored by the file system, which is essentially arbitrary. So you take this arbitrary list, walk through it in order skipping some files, and when you hit the last file, you go on to the next step. But there's no guarantee which that last file will be. A better way is to take the file names from os.listdir, remove the ones you don't care about, and then sort the remaining ones, then take the last one: files = os.listdir('.') # filter out backups and autosave files files = [f for f in files if not (f.endswith('~') or f.endswith('.autosave')] files.sort() the_file_name = files[-1] should work, although you might need a bit more work on the sorting. One last comment: > def openNewestCompCommandLine(): Your function is called *open* newest command line. How do you open a command line? Seems like a misleading name to me. But then, instead of opening the file, you "nuke" it instead: > os.system("nuke " + theFullPath) Oh my, I can see this being *very* entertaining in the future... -- Steven From ldl08 at gmx.net Tue Mar 22 02:06:21 2011 From: ldl08 at gmx.net (David) Date: Tue, 22 Mar 2011 02:06:21 +0100 Subject: [Tutor] a function I fail to understand Message-ID: <4D87F60D.80101@gmx.net> Hello list, I am having trouble understanding the following function. What trips me up is the "letter = letter.lower()" line. As I understand, the function takes a letter and assigns True to a letter if it is upper case. But then he goes to letter = letter.lower() and all letters are converted back to lower again!?? The point is that, to my understanding, the logic follows from the first block to letter = letter.lower(). Isn't that true? Thanks for helping me out, David def rotate13_letter(letter): """ Return the 13-char rotation of a letter. """ do_upper = False if letter.isupper(): do_upper = True letter = letter.lower() if letter not in CHAR_MAP: return letter else: letter = CHAR_MAP[letter] if do_upper: letter = letter.upper() return letter From mehgcap at gmail.com Tue Mar 22 02:38:15 2011 From: mehgcap at gmail.com (Alex Hall) Date: Mon, 21 Mar 2011 21:38:15 -0400 Subject: [Tutor] a function I fail to understand In-Reply-To: <4D87F60D.80101@gmx.net> References: <4D87F60D.80101@gmx.net> Message-ID: On 3/21/11, David wrote: > Hello list, > > I am having trouble understanding the following function. What trips me > up is the "letter = letter.lower()" line. > > As I understand, the function takes a letter and assigns True to a > letter if it is upper case. No, the function takes a letter and returns that letter in its uppercase form. lr="a" lr.upper() #lr now = A lr.lower() #lr now equals a I should actually say that it takes a string and uppercases any letters in it. It just happens that you are dealing with one letter here. > > But then he goes to > > letter = letter.lower() > > and all letters are converted back to lower again!?? The point is that, > to my understanding, the logic follows from the first block to > letter = letter.lower(). Isn't that true? > > Thanks for helping me out, > > David > > > def rotate13_letter(letter): > """ > Return the 13-char rotation of a letter. > """ > do_upper = False > if letter.isupper(): > do_upper = True > > letter = letter.lower() > if letter not in CHAR_MAP: > return letter > > else: > letter = CHAR_MAP[letter] > if do_upper: > letter = letter.upper() > > return letter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From marc.tompkins at gmail.com Tue Mar 22 04:24:41 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 21 Mar 2011 20:24:41 -0700 Subject: [Tutor] a function I fail to understand In-Reply-To: <4D87F60D.80101@gmx.net> References: <4D87F60D.80101@gmx.net> Message-ID: On Mon, Mar 21, 2011 at 6:06 PM, David wrote: > Hello list, > > I am having trouble understanding the following function. What trips me > up is the "letter = letter.lower()" line. > > As I understand, the function takes a letter and assigns True to a > letter if it is upper case. > > But then he goes to > > letter = letter.lower() > > and all letters are converted back to lower again!?? The point is that, > to my understanding, the logic follows from the first block to > letter = letter.lower(). Isn't that true? > > Thanks for helping me out, > > David > > > def rotate13_letter(letter): > """ > Return the 13-char rotation of a letter. > """ > do_upper = False > if letter.isupper(): > do_upper = True > > letter = letter.lower() > if letter not in CHAR_MAP: > return letter > > else: > letter = CHAR_MAP[letter] > if do_upper: > letter = letter.upper() > > return letter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The person who wrote this only wanted to write one conversion routine, so what he's doing is: - check to see if the letter is uppercase, and if it is, set a flag (do_upper) for later - force the letter to lowercase regardless of its previous status - do the conversion - if the do_upper flag is set, convert back to uppercase - return the letter It may look a little funny, but it beats writing logic to deal with each upper- and lower-case letter. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Mar 22 06:45:07 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Mar 2011 01:45:07 -0400 Subject: [Tutor] a function I fail to understand In-Reply-To: References: <4D87F60D.80101@gmx.net> Message-ID: <4D883763.6010701@ieee.org> On 01/-10/-28163 02:59 PM, Alex Hall wrote: > On 3/21/11, David wrote: >> Hello list, >> >> I am having trouble understanding the following function. What trips me >> up is the "letter = letter.lower()" line. >> >> As I understand, the function takes a letter and assigns True to a >> letter if it is upper case. > No, the function takes a letter and returns that letter in its uppercase form. > lr="a" > lr.upper() #lr now = A > lr.lower() #lr now equals a > I should actually say that it takes a string and uppercases any > letters in it. It just happens that you are dealing with one letter > here. Not even close. The CHAR_MAP is apparently a map from char to char, where both are presumably lower-case ones. My suspicion is the map looks like: CHAR_MAP = { "a":"n", "b", "o", ... "z":"m"} The code simply returns its input if it's not represented in the map. But if the letter is lowercase, it's just looked up in the map, and the result is returned. if the letter is uppercase, it's changed to lowercase, looked up, then changed back to uppercase. The code could have been trivial if the map had simply had both lower and uppercase entries in it to begin with. The table would be twice the size, but the code would then have been trivial. Of course, the maketrans function could have simplified it even more. Or you could just use the rot_13 encoder: >>> import codecs >>> f = codecs.getencoder("rot_13") >>> f("Abcde") ('Nopqr', 5) DaveA >> >> But then he goes to >> >> letter = letter.lower() >> >> and all letters are converted back to lower again!?? The point is that, >> to my understanding, the logic follows from the first block to >> letter = letter.lower(). Isn't that true? >> >> Thanks for helping me out, >> >> David >> >> >> def rotate13_letter(letter): >> """ >> Return the 13-char rotation of a letter. >> """ >> do_upper = False >> if letter.isupper(): >> do_upper = True >> >> letter = letter.lower() >> if letter not in CHAR_MAP: >> return letter >> >> else: >> letter = CHAR_MAP[letter] >> if do_upper: >> letter = letter.upper() >> >> return letter >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > From ldl08 at gmx.net Tue Mar 22 17:28:14 2011 From: ldl08 at gmx.net (David) Date: Tue, 22 Mar 2011 17:28:14 +0100 Subject: [Tutor] a function I fail to understand In-Reply-To: <4D883763.6010701@ieee.org> References: <4D87F60D.80101@gmx.net> <4D883763.6010701@ieee.org> Message-ID: <4D88CE1E.3070100@gmx.net> Hey guys, thanks for all this help, I now got a clearer picture. Given the confusion as to the CHAR_MAP I am attaching the entire file. It comes, btw, out of Jeff McNeil's "Python 2.6 Text Processing" book (Packt), p. 11. Happy hacking, David On 03/22/2011 06:45 AM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Alex Hall wrote: >> On 3/21/11, David wrote: >>> Hello list, >>> >>> I am having trouble understanding the following function. What trips me >>> up is the "letter = letter.lower()" line. >>> >>> As I understand, the function takes a letter and assigns True to a >>> letter if it is upper case. >> No, the function takes a letter and returns that letter in its >> uppercase form. >> lr="a" >> lr.upper() #lr now = A >> lr.lower() #lr now equals a >> I should actually say that it takes a string and uppercases any >> letters in it. It just happens that you are dealing with one letter >> here. > > Not even close. The CHAR_MAP is apparently a map from char to char, > where both are presumably lower-case ones. My suspicion is the map > looks like: > > CHAR_MAP = { "a":"n", "b", "o", ... "z":"m"} > > The code simply returns its input if it's not represented in the map. > But if the letter is lowercase, it's just looked up in the map, and the > result is returned. if the letter is uppercase, it's changed to > lowercase, looked up, then changed back to uppercase. > > The code could have been trivial if the map had simply had both lower > and uppercase entries in it to begin with. The table would be twice the > size, but the code would then have been trivial. > > Of course, the maketrans function could have simplified it even more. Or > you could just use the rot_13 encoder: > >>>> import codecs >>>> f = codecs.getencoder("rot_13") >>>> f("Abcde") > ('Nopqr', 5) > > > > DaveA > >>> >>> But then he goes to >>> >>> letter = letter.lower() >>> >>> and all letters are converted back to lower again!?? The point is that, >>> to my understanding, the logic follows from the first block to >>> letter = letter.lower(). Isn't that true? >>> >>> Thanks for helping me out, >>> >>> David >>> >>> >>> def rotate13_letter(letter): >>> """ >>> Return the 13-char rotation of a letter. >>> """ >>> do_upper = False >>> if letter.isupper(): >>> do_upper = True >>> >>> letter = letter.lower() >>> if letter not in CHAR_MAP: >>> return letter >>> >>> else: >>> letter = CHAR_MAP[letter] >>> if do_upper: >>> letter = letter.upper() >>> >>> return letter >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> > > -------------- next part -------------- A non-text attachment was scrubbed... Name: rot13.py Type: text/x-python Size: 690 bytes Desc: not available URL: From __peter__ at web.de Wed Mar 23 07:48:35 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Mar 2011 07:48:35 +0100 Subject: [Tutor] getting the last file in a folder (reliably) References: <4D87D4EB.9060204@pearwood.info> Message-ID: Steven D'Aprano wrote: > files.sort() > the_file_name = files[-1] You don't need to sort if you want only one file: the_file_name = max(files) From steve at pearwood.info Wed Mar 23 12:49:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Mar 2011 22:49:02 +1100 Subject: [Tutor] getting the last file in a folder (reliably) In-Reply-To: References: <4D87D4EB.9060204@pearwood.info> Message-ID: <4D89DE2E.1070902@pearwood.info> Peter Otten wrote: > Steven D'Aprano wrote: > >> files.sort() >> the_file_name = files[-1] > > You don't need to sort if you want only one file: > > the_file_name = max(files) Nice catch! -- Steven From lezlie.kline at gmail.com Wed Mar 23 14:09:53 2011 From: lezlie.kline at gmail.com (Lezlie Kline) Date: Wed, 23 Mar 2011 09:09:53 -0400 Subject: [Tutor] Checksum program Message-ID: Hi, I'm trying to work out the bugs in a program for calculating the checksum (modulo 256) of an input string. I'm testing it with my full name and I'm a beginner with Python. Here's what I have so far. def main(): print"This program creates a checksum for a message." name=raw_input("Please enter the message to encode: ") message=name output=name for i in range(len(message)): print"The value of message[i] is ", message[i] output=output+name+ord(message[i]) print"The value of the message is ", output checksum=(output)%256 print"The checksum is ", checksum main() I know I'm offbase somewhere, but I'm not understanding some parts of the accumulator part of the program. I need it to work with the message[i] intact. In other words, I need the pseudo code to go something like this: print message get input find length using length in range function accumulate ASCII numbers calculate checksum print checksum I'd appreciate any help offered as I'm "pulling out my hair." -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Wed Mar 23 14:30:01 2011 From: taserian at gmail.com (taserian) Date: Wed, 23 Mar 2011 09:30:01 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: On Wed, Mar 23, 2011 at 9:09 AM, Lezlie Kline wrote: > Hi, > > I'm trying to work out the bugs in a program for calculating the checksum > (modulo 256) of an input string. I'm testing it with my full name and I'm a > beginner with Python. Here's what I have so far. > > def main(): > print"This program creates a checksum for a message." > name=raw_input("Please enter the message to encode: ") > message=name > output=name > for i in range(len(message)): > print"The value of message[i] is ", message[i] > output=output+name+ord(message[i]) > print"The value of the message is ", output > checksum=(output)%256 > print"The checksum is ", checksum > > main() > I'd like to give you some pointers so you can solve it yourself: What's the checksum for a completely empty message (i.e., no characters at all)? Where are you storing the (ASCII) values of each letter? Has it been initialized properly? > I know I'm offbase somewhere, but I'm not understanding some parts of the > accumulator part of the program. I need it to work with the message[i] > intact. In other words, I need the pseudo code to go something like this: > > print message > get input > find length > using length in range function accumulate ASCII numbers > calculate checksum > print checksum > > I'd appreciate any help offered as I'm "pulling out my hair." message[i] will provide you the character at position i. What are you doing with it? Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: From freethinker at pobox.com Wed Mar 23 15:19:14 2011 From: freethinker at pobox.com (Tom Zych) Date: Wed, 23 Mar 2011 10:19:14 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: <4D8A0162.9050307@pobox.com> Lezlie Kline wrote: > I'm trying to work out the bugs in a program for calculating the checksum > (modulo 256) of an input string. I'm testing it with my full name and I'm a > beginner with Python. Here's what I have so far. > > def main(): > print"This program creates a checksum for a message." > name=raw_input("Please enter the message to encode: ") > message=name > output=name > for i in range(len(message)): > print"The value of message[i] is ", message[i] > output=output+name+ord(message[i]) > print"The value of the message is ", output > checksum=(output)%256 > print"The checksum is ", checksum > > main() You're not too far off. Take a good look at everything you do with `output`. In particular, note what type of object it is. Your loop will work but it's not Pythonic - you can iterate over a sequence directly: for i in message: # i = a character (string of length 1) from message print "Processing", i -- Tom Zych / freethinker at pobox.com "Because if they didn't vote for a lizard," said Ford, "the wrong lizard might get in." -- DNA From taserian at gmail.com Wed Mar 23 15:28:25 2011 From: taserian at gmail.com (taserian) Date: Wed, 23 Mar 2011 10:28:25 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: On Wed, Mar 23, 2011 at 9:55 AM, Lezlie Kline wrote: > Tony, > > For your question "What's the checksum for a completely empty message > (i.e., no characters at all)?" Do you mean the value or how do I write it? > I would think the value would be 0. > Correct. Now think of that as your starting point; any message containing characters is going to start at 0 plus the sum of the ASCII values of each of its characters. Where would you store the initial value of an empty message? > My understanding of where I'm storing the ASCII values for each letter is > ord(message[i]) > ord isn't a variable, it's a function. It's calculating the ASCII value of the i-th character of "message". > I don't think it's been initialized properly, but that's where I don't > understand about the accumulator for strings. I originally thought this for > the accumulator: > > output="" > for i in range(len(message[i])" > > print"The value of message[i] is ", message[i] > output=output+" " + ord(message[i]) > > print"The value of the message is ", output > > but strings and integers don't concatentate AND my ord(value) isn't > accumulating AND I thing my output is getting overwritten. > You don't want to mix apples and oranges. Your variable "message" contains a full name in the test case, "John X. Doe", for example, so it's made up of characters. What should the accumulator contain, if you're going to be adding numbers? > Here's part of the problem. The person "teaching" me Python provides some > information and then jumps to the programs so I'm struggling in the fuzzy > dark. I was given the range "for i in range(len(message[i]):print"The value > of message[i] is ", message[i]" and I understand that it obtains the length > of my message, but I don't really understand the [i] part other than [i] > represents integer and the "i" in for i is the iteration of the loop so when > you ask the question "message[i] will provide you the character at position > i. What are you doing with it?" I'm not sure what you're asking? > > I'm sorry to be so dense. Believe it or not I've been working on this > program for a week.... > > L. Is this homework? Tony R. > On Wed, Mar 23, 2011 at 9:30 AM, taserian wrote: > >> On Wed, Mar 23, 2011 at 9:09 AM, Lezlie Kline wrote: >> >>> Hi, >>> >>> I'm trying to work out the bugs in a program for calculating the checksum >>> (modulo 256) of an input string. I'm testing it with my full name and I'm a >>> beginner with Python. Here's what I have so far. >>> >>> def main(): >>> print"This program creates a checksum for a message." >>> name=raw_input("Please enter the message to encode: ") >>> message=name >>> output=name >>> for i in range(len(message)): >>> print"The value of message[i] is ", message[i] >>> output=output+name+ord(message[i]) >>> print"The value of the message is ", output >>> checksum=(output)%256 >>> print"The checksum is ", checksum >>> >>> main() >>> >> I'd like to give you some pointers so you can solve it yourself: >> >> What's the checksum for a completely empty message (i.e., no characters at >> all)? >> Where are you storing the (ASCII) values of each letter? Has it been >> initialized properly? >> >> >>> I know I'm offbase somewhere, but I'm not understanding some parts of the >>> accumulator part of the program. I need it to work with the message[i] >>> intact. In other words, I need the pseudo code to go something like this: >>> >>> print message >>> get input >>> find length >>> using length in range function accumulate ASCII numbers >>> calculate checksum >>> print checksum >>> >>> I'd appreciate any help offered as I'm "pulling out my hair." >> >> >> message[i] will provide you the character at position i. What are you >> doing with it? >> >> Tony R. >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Wed Mar 23 15:29:03 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 23 Mar 2011 07:29:03 -0700 (PDT) Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: <666073.89561.qm@web130222.mail.mud.yahoo.com> Hi Lezlie, Well first off, let me admit I have no idea what checksums are (I be a noobz) and I can not help you with that part of your program at all, but there are lots of people here who can. But since you are new to python, let me comment on some of the general things I noticed in your code. When I ran your code with the word being hello I got the error. "TypeError: cannot concatenate 'str' and 'int' objects" it occured at line 8 of your code "output=output+name+ord(message[i])". Now in this line you are adding 2 strings together (output and name) with 1 int (ord(message[i])). In python you can not add these types together. Hence the error. But if it did add them together (using hello as an example) you would get output = hellohello104, is this what you want? Since message = hello and output = hello and ord("h") = 104. Also keep in mind that for every iteration of the for loop, output actually changes (meaning that output lost its last value, to make room for the new one, and it only has 1 value in it), so if python actually did what you asked it to your output would look like this. The value of message[i] is h The value of the message is hellohello104 The value of message[i] is e The value of the message is hellohello101 The value of message[i] is l The value of the message is hellohello108 The value of message[i] is l The value of the message is hellohello108 The value of message[i] is o The value of the message is hellohello111 The checksum is , 111 (according to "checksum=(output)%256" supposing the hellohello was not added and just 111 was evaluated, if you had put in "256%(output)" the answer would have been 54 instead of 111) Note that because it changed in every iteration the last letter (o) is the final value of output, instead of the values being appended to the variable output Is this what you wanted to happen? If its not, try to think of ways to slighty change your code to give you closer results to what you want. If this is what you want, there are cheats to actually make it output this without errors... I hope this helps (^_^) ---- What is it about you... that intrigues me so? ________________________________ From: Lezlie Kline To: tutor at python.org Sent: Wed, March 23, 2011 9:09:53 AM Subject: [Tutor] Checksum program Hi, I'm trying to work out the bugs in a program for calculating the checksum (modulo 256) of an input string. I'm testing it with my full name and I'm a beginner with Python. Here's what I have so far. def main(): print"This program creates a checksum for a message." name=raw_input("Please enter the message to encode: ") message=name output=name for i in range(len(message)): print"The value of message[i] is ", message[i] output=output+name+ord(message[i]) print"The value of the message is ", output checksum=(output)%256 print"The checksum is ", checksum main() I know I'm offbase somewhere, but I'm not understanding some parts of the accumulator part of the program. I need it to work with the message[i] intact. In other words, I need the pseudo code to go something like this: print message get input find length using length in range function accumulate ASCII numbers calculate checksum print checksum I'd appreciate any help offered as I'm "pulling out my hair." -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Wed Mar 23 15:54:53 2011 From: taserian at gmail.com (taserian) Date: Wed, 23 Mar 2011 10:54:53 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: When replying to the Python Tutor list, please use "Reply All" instead of just "Reply". I meant to put this in my previous message, but it remained in "meant to" phase and never got implemented properly. 8-) I don't think it's been initialized properly, but that's where I don't understand about the accumulator for strings. I originally thought this for the accumulator: output="" for i in range(len(message[i])" >>> print"The value of message[i] is ", message[i] >>> output=output+" " + ord(message[i]) >>> >>> print"The value of the message is ", output >>> >>> but strings and integers don't concatentate AND my ord(value) isn't >>> accumulating AND I thing my output is getting overwritten. >>> >> You don't want to mix apples and oranges. Your variable "message" >> contains a full name in the test case, "John X. Doe", for example, so it's >> made up of characters. What should the accumulator contain, if you're going >> to be adding numbers? Numbers >> > Then your code above should look something like this: output= 0 for i in message: print"Character i in message: ", message[i] output=output + ord(message[i]) print "The value of the message is ", output In pseudocode: Start with the value for an empty message in the variable "output". For every character in "message": Print the character Add the ASCII value of the character to the accumulator "output". After all of the characters have been processed, show the final value of "output" > >> Is this homework? Not anymore I'm past that and I live in NC and I've >> been desperately looking for a tutor but I'm having difficulty finding >> anyone who does Python programming. They don't teach it at NC State or UNC >> or Wake Tech. If you don't want to help. I understand. This was my last >> resort. >> > >> > Not at all. It's just that we have a rule about not doing anyone's homework on the list. It robs them of the learning experience, and can provide a grade which hasn't been earned properly. Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lezlie.kline at gmail.com Wed Mar 23 16:11:04 2011 From: lezlie.kline at gmail.com (Lezlie Kline) Date: Wed, 23 Mar 2011 11:11:04 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: I have a question for the list about the homework rule and the tutoring list. If you have a question and you're not asking for your homework or past homework to be done for you but you just have questions to be explained isn't that what tutoring and learning is all about. For example, on my question here. I have a problem that is not homework for a grade and I don't understand it. I can't find a tutor. I'm frustrated and you guys can provide help for my understanding which you were doing. Not by giving me an answer, but by asking me questions and helping me to understand. Isn't that what tutoring and open forum is all about. Unfortunately, I still don't quite have it I feel like I got left hanging on the edge of almost... I called the Dean of Graduate students at NC State to try to find someone to tutor me and the response was helpful but Python isn't taught at NC State. UNC - the same. Wake Technical - the same. I've looked on Craig's list and Googled with no luck I'm taking an intro to computer science class online through Utica for Cybersecurity and I would just like some help understanding. I'm not one to easily give up!! Anyway, I understand having rules and why, but I also think that when those rules don't make sense under the situation exceptions should be made. Just saying... L. On Wed, Mar 23, 2011 at 10:54 AM, taserian wrote: > When replying to the Python Tutor list, please use "Reply All" instead of > just "Reply". I meant to put this in my previous message, but it remained in > "meant to" phase and never got implemented properly. 8-) > > > I don't think it's been initialized properly, but that's where I don't > understand about the accumulator for strings. I originally thought this for > the accumulator: > > output="" > for i in range(len(message[i])" > > >>>> print"The value of message[i] is ", message[i] >>>> output=output+" " + ord(message[i]) >>>> >>>> print"The value of the message is ", output >>>> >>>> but strings and integers don't concatentate AND my ord(value) isn't >>>> accumulating AND I thing my output is getting overwritten. >>>> >>> You don't want to mix apples and oranges. Your variable "message" >>> contains a full name in the test case, "John X. Doe", for example, so it's >>> made up of characters. What should the accumulator contain, if you're going >>> to be adding numbers? Numbers >>> >> > Then your code above should look something like this: > > output= 0 > for i in message: > print"Character i in message: ", message[i] > > output=output + ord(message[i]) > print "The value of the message is ", output > > > In pseudocode: > Start with the value for an empty message in the variable "output". > For every character in "message": > Print the character > Add the ASCII value of the character to the accumulator "output". > After all of the characters have been processed, show the final value of > "output" > > >> >>> Is this homework? Not anymore I'm past that and I live in NC and I've >>> been desperately looking for a tutor but I'm having difficulty finding >>> anyone who does Python programming. They don't teach it at NC State or UNC >>> or Wake Tech. If you don't want to help. I understand. This was my last >>> resort. >>> >> >>> >> > Not at all. It's just that we have a rule about not doing anyone's homework > on the list. It robs them of the learning experience, and can provide a > grade which hasn't been earned properly. > > Tony R. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Wed Mar 23 17:26:01 2011 From: taserian at gmail.com (taserian) Date: Wed, 23 Mar 2011 12:26:01 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: On Wed, Mar 23, 2011 at 11:11 AM, Lezlie Kline wrote: > I have a question for the list about the homework rule and the tutoring > list. If you have a question and you're not asking for your homework or > past homework to be done for you but you just have questions to be explained > isn't that what tutoring and learning is all about. For example, on my > question here. I have a problem that is not homework for a grade and I > don't understand it. I can't find a tutor. I'm frustrated and you guys can > provide help for my understanding which you were doing. Not by giving me an > answer, but by asking me questions and helping me to understand. Isn't that > what tutoring and open forum is all about. Unfortunately, I still don't > quite have it I feel like I got left hanging on the edge of almost... > I tend to err on the side of caution and try not to give away too much, just so that the student achieves more by themselves than by giving them the answer outright. What's the quandary on that "edge of almost"? > I called the Dean of Graduate students at NC State to try to find someone > to tutor me and the response was helpful but Python isn't taught at NC > State. UNC - the same. Wake Technical - the same. I've looked on Craig's > list and Googled with no luck I'm taking an intro to computer science class > online through Utica for Cybersecurity and I would just like some help > understanding. I'm not one to easily give up!! > > Anyway, I understand having rules and why, but I also think that when those > rules don't make sense under the situation exceptions should be made. Just > saying... > > L. Have you tried any of the online Python tutorials? http://docs.python.org/tutorial/ http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf http://www.freenetpages.co.uk/hp/alan.gauld/ Even though Python has been around long enough, it isn't taught formally in as many institutions as we'd like. I'd venture to guess that most of the Python experts on this list are self-taught rather than having taken a formal course. The above links would be great for you if you're up for learning on your own. One thing I've found: http://trizpug.org/ , which seems to be a Python group that meets monthly in the Durham area (not sure how close that is to you). You might want to subscribe to their mailing list and see if there's anyone willing to tutor you, if that's more your style; it looks like they have a meeting tomorrow 3/24/11. I'd contact them and see how welcome they are to newcomers. Hoping this helps, Tony R. > On Wed, Mar 23, 2011 at 10:54 AM, taserian wrote: > >> When replying to the Python Tutor list, please use "Reply All" instead of >> just "Reply". I meant to put this in my previous message, but it remained in >> "meant to" phase and never got implemented properly. 8-) >> >> >> I don't think it's been initialized properly, but that's where I don't >> understand about the accumulator for strings. I originally thought this for >> the accumulator: >> >> output="" >> for i in range(len(message[i])" >> >> >>>>> print"The value of message[i] is ", message[i] >>>>> output=output+" " + ord(message[i]) >>>>> >>>>> print"The value of the message is ", output >>>>> >>>>> but strings and integers don't concatentate AND my ord(value) isn't >>>>> accumulating AND I thing my output is getting overwritten. >>>>> >>>> You don't want to mix apples and oranges. Your variable "message" >>>> contains a full name in the test case, "John X. Doe", for example, so it's >>>> made up of characters. What should the accumulator contain, if you're going >>>> to be adding numbers? Numbers >>>> >>> >> Then your code above should look something like this: >> >> output= 0 >> for i in message: >> print"Character i in message: ", message[i] >> >> output=output + ord(message[i]) >> print "The value of the message is ", output >> >> >> In pseudocode: >> Start with the value for an empty message in the variable "output". >> For every character in "message": >> Print the character >> Add the ASCII value of the character to the accumulator "output". >> After all of the characters have been processed, show the final value of >> "output" >> >> >>> >>>> Is this homework? Not anymore I'm past that and I live in NC and I've >>>> been desperately looking for a tutor but I'm having difficulty finding >>>> anyone who does Python programming. They don't teach it at NC State or UNC >>>> or Wake Tech. If you don't want to help. I understand. This was my last >>>> resort. >>>> >>> >>>> >>> >> Not at all. It's just that we have a rule about not doing >> anyone's homework on the list. It robs them of the learning experience, and >> can provide a grade which hasn't been earned properly. >> >> Tony R. >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lezlie.kline at gmail.com Wed Mar 23 17:29:29 2011 From: lezlie.kline at gmail.com (Lezlie Kline) Date: Wed, 23 Mar 2011 12:29:29 -0400 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: Thanks for the links. Yes, I've worked with the tutorials. My work doesn't flow exactly along those lines, but they do help. I'll look up the the group you sent too. I appreciate all the extra effort you went to. Many thanks!!! :) On Wed, Mar 23, 2011 at 12:26 PM, taserian wrote: > On Wed, Mar 23, 2011 at 11:11 AM, Lezlie Kline wrote: > >> I have a question for the list about the homework rule and the tutoring >> list. If you have a question and you're not asking for your homework or >> past homework to be done for you but you just have questions to be explained >> isn't that what tutoring and learning is all about. For example, on my >> question here. I have a problem that is not homework for a grade and I >> don't understand it. I can't find a tutor. I'm frustrated and you guys can >> provide help for my understanding which you were doing. Not by giving me an >> answer, but by asking me questions and helping me to understand. Isn't that >> what tutoring and open forum is all about. Unfortunately, I still don't >> quite have it I feel like I got left hanging on the edge of almost... >> > I tend to err on the side of caution and try not to give away too much, > just so that the student achieves more by themselves than by giving them the > answer outright. What's the quandary on that "edge of almost"? > > >> I called the Dean of Graduate students at NC State to try to find someone >> to tutor me and the response was helpful but Python isn't taught at NC >> State. UNC - the same. Wake Technical - the same. I've looked on Craig's >> list and Googled with no luck I'm taking an intro to computer science class >> online through Utica for Cybersecurity and I would just like some help >> understanding. I'm not one to easily give up!! >> >> Anyway, I understand having rules and why, but I also think that when >> those rules don't make sense under the situation exceptions should be made. >> Just saying... >> >> L. > > > Have you tried any of the online Python tutorials? > > http://docs.python.org/tutorial/ > > http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf > > http://www.freenetpages.co.uk/hp/alan.gauld/ > > Even though Python has been around long enough, it isn't taught formally in > as many institutions as we'd like. I'd venture to guess that most of the > Python experts on this list are self-taught rather than having taken a > formal course. The above links would be great for you if you're up for > learning on your own. > > One thing I've found: http://trizpug.org/ , which seems to be a Python > group that meets monthly in the Durham area (not sure how close that is to > you). You might want to subscribe to their mailing list and see if there's > anyone willing to tutor you, if that's more your style; it looks like they > have a meeting tomorrow 3/24/11. I'd contact them and see how welcome they > are to newcomers. > > Hoping this helps, > > Tony R. > > > >> On Wed, Mar 23, 2011 at 10:54 AM, taserian wrote: >> >>> When replying to the Python Tutor list, please use "Reply All" instead of >>> just "Reply". I meant to put this in my previous message, but it remained in >>> "meant to" phase and never got implemented properly. 8-) >>> >>> >>> I don't think it's been initialized properly, but that's where I don't >>> understand about the accumulator for strings. I originally thought this for >>> the accumulator: >>> >>> output="" >>> for i in range(len(message[i])" >>> >>> >>>>>> print"The value of message[i] is ", message[i] >>>>>> output=output+" " + ord(message[i]) >>>>>> >>>>>> print"The value of the message is ", output >>>>>> >>>>>> but strings and integers don't concatentate AND my ord(value) isn't >>>>>> accumulating AND I thing my output is getting overwritten. >>>>>> >>>>> You don't want to mix apples and oranges. Your variable "message" >>>>> contains a full name in the test case, "John X. Doe", for example, so it's >>>>> made up of characters. What should the accumulator contain, if you're going >>>>> to be adding numbers? Numbers >>>>> >>>> >>> Then your code above should look something like this: >>> >>> output= 0 >>> for i in message: >>> print"Character i in message: ", message[i] >>> >>> output=output + ord(message[i]) >>> print "The value of the message is ", output >>> >>> >>> In pseudocode: >>> Start with the value for an empty message in the variable "output". >>> For every character in "message": >>> Print the character >>> Add the ASCII value of the character to the accumulator "output". >>> After all of the characters have been processed, show the final value of >>> "output" >>> >>> >>>> >>>>> Is this homework? Not anymore I'm past that and I live in NC and I've >>>>> been desperately looking for a tutor but I'm having difficulty finding >>>>> anyone who does Python programming. They don't teach it at NC State or UNC >>>>> or Wake Tech. If you don't want to help. I understand. This was my last >>>>> resort. >>>>> >>>> >>>>> >>>> >>> Not at all. It's just that we have a rule about not doing >>> anyone's homework on the list. It robs them of the learning experience, and >>> can provide a grade which hasn't been earned properly. >>> >>> Tony R. >>> >>> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Mar 23 23:19:30 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 23 Mar 2011 17:19:30 -0500 Subject: [Tutor] Fwd: Checksum program In-Reply-To: References: Message-ID: Forwarding on to the list, as there are many other people who can also answer the questions. ---------- Forwarded message ---------- From: Lezlie Kline Date: Wed, Mar 23, 2011 at 9:30 AM Subject: Re: [Tutor] Checksum program To: Wayne Werner Wayne, Thanks! That helped tremendously. Here's my problem with the accumulator understanding. I have two examples: This one is for an empty string: output="" print"Please enter 4 words, one at a time." for i in range(4): word=raw_input("Enter a word: ") output=output+" " + word print "\tThe accumulator so far has: ", output print "The words you entered are: ", output The other one is for a non-empty string: output="*" word=raw_input("Enter a word: ") for letter in word: output=output+letter+"*" print"The result is: ", output These are the two that I was going off of I'm not really getting an understanding of how this is working. Do you mind explaining? Is my ord(message[i]) correct for getting the ASCII numbers in the string? My thinking was that "message[i]" is the length so ord(value) is what provides the ASCII numbers therefore if I use ord(message[i]) that would work. My problem was that I didn't know which of the two patterns above to follow because I don't really understand how they work. Any further help is truly appreciated. As you might perceive, I'm a bit frazzled. Thanks so much. Lezlie On Wed, Mar 23, 2011 at 9:50 AM, Wayne Werner wrote: > On Wed, Mar 23, 2011 at 8:09 AM, Lezlie Kline wrote: > >> Hi, >> >> I'm trying to work out the bugs in a program for calculating the checksum >> (modulo 256) of an input string. I'm testing it with my full name and I'm a >> beginner with Python. Here's what I have so far. >> > > Welcome to the list and to Python! > > >> >> def main(): >> print"This program creates a checksum for a message." >> name=raw_input("Please enter the message to encode: ") >> message=name >> output=name >> for i in range(len(message)): >> > > Using the range in this case is superfluous twice; Range is a function that > returns a list - in this case a list containing 0-len(message)-1. xrange is > the preferred function, which creates an generator instead. It uses a lot > less memory. But in *this* case, the only thing you're using i for is to > index a string - which is already iterable. You could say: > > for letter in message: > print "The letter is: ", letter > > >> print"The value of message[i] is ", message[i] >> output=output+name+ord(message[i]) >> print"The value of the message is ", output >> checksum=(output)%256 >> print"The checksum is ", checksum >> >> main() >> >> I know I'm offbase somewhere, but I'm not understanding some parts of the >> accumulator part of the program. I need it to work with the message[i] >> intact. In other words, I need the pseudo code to go something like this: >> >> print message >> get input >> find length >> using length in range function accumulate ASCII numbers >> calculate checksum >> print checksum >> > > Actually, you could even improve your pseudo code - rather than describing > *what* you need to do, you've described *how* you need to do it - the how > should always be your last step, even if you're doing it just in your head. > So in this case, you could do something like this: > > get a string > display string > get ASCII numbers for each character in the string > add all the ascii values together > calculate checksum > display checksum > > So let's take a look at your function to see which steps you've got, and > where you're missing: > > def main(): > print"This program creates a checksum for a message." > # Okay, here you're getting a string. Looks good so far > name=raw_input("Please enter the message to encode: ") > # I'm not really sure what the purpose of this reassignment is. > # Your pseudo code doesn't mention anything that would need these > copies for anything > message=name > output=name > for i in range(len(message)): > print"The value of message[i] is ", message[i] > # What is stored in output the first loop through? How about name? > # If this is where you *think* you're accumulating ASCII digits, > you're definitely not. > output=output+name+ord(message[i]) > print"The value of the message is ", output > # This certainly does %256, but it requires a number. > checksum=(output)%256 > print"The checksum is ", checksum > > So really you're only missing the most crucial step - totalling the ASCII > numbers. > > Rather than "output", a more appropriate name might be "total", since > that's what you're really trying to store. > > Good luck! > HTH, > Wayne > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Mar 23 23:43:32 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 23 Mar 2011 17:43:32 -0500 Subject: [Tutor] Checksum program In-Reply-To: References: Message-ID: On Wed, Mar 23, 2011 at 5:19 PM, Wayne Werner wrote: > > ---------- Forwarded message ---------- > From: Lezlie Kline > Date: Wed, Mar 23, 2011 at 9:30 AM > Subject: Re: [Tutor] Checksum program > To: Wayne Werner > > > Wayne, > > Thanks! That helped tremendously. Here's my problem with the accumulator > understanding. I have two examples: > > This one is for an empty string: > > output="" > print"Please enter 4 words, one at a time." > for i in range(4): > word=raw_input("Enter a word: ") > output=output+" " + word > print "\tThe accumulator so far has: ", output > print "The words you entered are: ", output > > The other one is for a non-empty string: > > output="*" > word=raw_input("Enter a word: ") > for letter in word: > output=output+letter+"*" > print"The result is: ", output > > These are the two that I was going off of > > I'm not really getting an understanding of how this is working. Do you > mind explaining? Is my ord(message[i]) correct for getting the ASCII > numbers in the string? > Yes, that part works fine. If you fire up an interactive interpreter you can try it out (I use IPython, so my prompt looks a little different than normal). In [12]: string = 'ASCII set' In [13]: for i in xrange(len(string)): ....: print ord(string[i]) You'll see that the output are indeed numbers. > My thinking was that "message[i]" is the length so ord(value) is what > provides the ASCII numbers therefore if I use ord(message[i]) that would > work. My problem was that I didn't know which of the two patterns above to > follow because I don't really understand how they work. > The best way to learn how something works is to modify it, or try to break it. Take the first example. What happens if you put more than one word in at a time? What if you do numbers instead? What happens if you wrap int() around the raw_input, so you have int(raw_input('Enter a word: ')) ? When you get errors, read them! Python is one of the few languages that gives you very helpful error messages (usually). Also, make sure you post the full text of any and all errors here. Also it helps to explain 1) What were you doing? (And what were you trying to do? Sometimes these are two different things!) 2) What did you expect to happen? 3) What happened instead? Copying and pasting is a very good way to answer #3. For instance, say you had this code: In [14]: number = 'four' In [15]: int(number) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/wayne/ in () ValueError: invalid literal for int() with base 10: 'four' You could say the following: I was trying to turn a string into a number, but it didn't work. I got this error instead: In this case, Python tells you with the last line that there's something wrong with the value (hence ValueError). Of course the latter part of the message might seem cryptic if you're not familiar with bases... But if you got that error and were confused, then you could have sent an email to the list and it would get answered fairly quickly. Of course, if you copy/paste the last line into Google, you also tend to get some good results. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From shahdharmit at gmail.com Thu Mar 24 06:10:44 2011 From: shahdharmit at gmail.com (Dharmit Shah) Date: Thu, 24 Mar 2011 10:40:44 +0530 Subject: [Tutor] Recursively flatten the list Message-ID: Hello, I am learning Python and yesterday I cam across a definition wherein I was supposed to flatten a list recursively. I am getting the solution properly but wanted to know if I can optimize the code further. #!/usr/bin/env python new_list=[] def flatten(num_list): """ >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) [2, 9, 2, 1, 13, 2, 8, 2, 6] >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) [9, 7, 1, 13, 2, 8, 7, 6] >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) [9, 7, 1, 13, 2, 8, 2, 6] >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]]) [5, 5, 1, 5, 5, 5, 5, 6] """ global new_list for i in num_list: if type(i) == type([]): new_list = flatten(i) else: new_list.append(i) tmp = new_list new_list=[] return tmp if __name__=="__main__": import doctest doctest.testmod() PS - My knowledge of Python is still very basic and I am trying to dive into it as deeper as I can. Solutions on Stackoverflow.com were beyond my understandability. -- Regards Dharmit Shah -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Mar 24 09:09:28 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Mar 2011 09:09:28 +0100 Subject: [Tutor] Recursively flatten the list References: Message-ID: Dharmit Shah wrote: > I am learning Python and yesterday I cam across a definition wherein I was > supposed to flatten a list recursively. I am getting the solution properly > but wanted to know if I can optimize the code further. > > #!/usr/bin/env python > new_list=[] > def flatten(num_list): > """ > >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) > [2, 9, 2, 1, 13, 2, 8, 2, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) > [9, 7, 1, 13, 2, 8, 7, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) > [9, 7, 1, 13, 2, 8, 2, 6] > >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]]) > [5, 5, 1, 5, 5, 5, 5, 6] > """ > global new_list > for i in num_list: > if type(i) == type([]): > new_list = flatten(i) > else: > new_list.append(i) > tmp = new_list > new_list=[] > return tmp > > if __name__=="__main__": > import doctest > doctest.testmod() > > PS - My knowledge of Python is still very basic and I am trying to dive > into it as deeper as I can. Solutions on Stackoverflow.com were beyond my > understandability. You have a working solution, and you have tests to prove it. That's a good start! Now let's think more tests to break it: (1) Deeply nested lists: items = [] for i in range(2000): items = [items] flatten(items) Python has a limited stacksize, i. e. allows only for a limited number of nested function calls. There's not much you can do about that other than switch to a non-recursive implementation of flatten(). Most of the time it's not a problem in practice; you should just know about it. (2) Lists that contain themselves: items = [] items.append(items) flatten(items) This one would run forever were it not for the limited stack size. You are even less likely to run into that in practice, but it might still be an interesting challenge for you to come up with a solution for the problem. (3) Multithreaded programs: Because you use a global variable you cannot run two instances of the function simultaneously. This problem leads to intermittent bugs that are really hard to find. You should try to eliminate the global new_list variable from your flatten() function. Unfortunately the demo is a bit messy, so don't waste too much time on trying to understand it. You can revisit it later if you like. Just remember the rule of thumb: don't use global variables if you can avoid them. if __name__=="__main__": import threading def set_flattened(num_list, index): results[index] = flatten(num_list) A = [5, [5, [1, 5], 5], 5], [5, 6] B = [[50, [50, [10, 50], 50], 50], [50, 60]] EXPECTED = [flatten(A), flatten(B)] print "expected output:" print EXPECTED i = 1 results = [None, None] while True: # run flatten() in two threads simultaneously... a = threading.Thread(target=set_flattened, args=(A, 0)) b = threading.Thread(target=set_flattened, args=(B, 1)) for t in a, b: t.start() for t in a, b: t.join() #... until we see an unexpected result if results != EXPECTED: print "The %dth attempt gave this preculiar result:" % i print results break i += 1 From freethinker at pobox.com Thu Mar 24 09:37:05 2011 From: freethinker at pobox.com (Tom Zych) Date: Thu, 24 Mar 2011 04:37:05 -0400 Subject: [Tutor] Recursively flatten the list In-Reply-To: References: Message-ID: <4D8B02B1.70400@pobox.com> Dharmit Shah wrote: > I am learning Python and yesterday I cam across a definition wherein I was > supposed to flatten a list recursively. I am getting the solution properly > but wanted to know if I can optimize the code further. > > #!/usr/bin/env python > new_list=[] > def flatten(num_list): > """ > >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) > [2, 9, 2, 1, 13, 2, 8, 2, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) > [9, 7, 1, 13, 2, 8, 7, 6] > >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) > [9, 7, 1, 13, 2, 8, 2, 6] > >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]]) > [5, 5, 1, 5, 5, 5, 5, 6] > """ > global new_list > for i in num_list: > if type(i) == type([]): > new_list = flatten(i) > else: > new_list.append(i) > tmp = new_list > new_list=[] > return tmp > > if __name__=="__main__": > import doctest > doctest.testmod() > > PS - My knowledge of Python is still very basic and I am trying to dive into > it as deeper as I can. Solutions on Stackoverflow.com were beyond my > understandability. Using doctest and getting a recursive function right don't strike me as basic. This is pretty good for a beginner. I'll second Peter Otten regarding the use of a global. It's best to avoid using globals whenever possible, not just for reentrancy, but for more readable and maintainable code. A function should be self-contained if possible. There's no reason you can't use a local variable in this code (and you only need one, not two), and the resulting code would be more readable. Regarding this line: if type(i) == type([]): This also works: if type(i) == list: But this is better: if isinstance(i, list): isinstance(obj, class) means "is obj an instance of class or a subtype of class", so it's more general. Does anyone see a way to do this with a list comprehension? I don't. Would be a neat hack if it can be done. -- Tom Zych / freethinker at pobox.com "Because if they didn't vote for a lizard," said Ford, "the wrong lizard might get in." -- DNA From rafadurancastaneda at gmail.com Thu Mar 24 10:44:12 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 24 Mar 2011 10:44:12 +0100 Subject: [Tutor] Recursively flatten the list In-Reply-To: <4D8B02B1.70400@pobox.com> References: <4D8B02B1.70400@pobox.com> Message-ID: I can do it with two list comprehensions: >>> list_ = [1, 2, [3, 4], 5, [6, 7, 8], 9] >>> [x[i] for x in list_ if isinstance(x, list) for i in range(len(x))] + [x for x in list_ if not isinstance(x, list)] [3, 4, 6, 7, 8, 1, 2, 5, 9] >>> But i loose original order, Can anyone do it with just one list comprehension and/or keeping the order? I also tryied: >>> [x if not isinstance(x, list) else (x[i] for i in range(len(x))) for x in list_] [1, 2, at 0x187f7d0>, 5, at 0x187f870>, 9] >>> [x if not isinstance(x, list) else [x[i] for i in range(len(x))] for x in list_] [1, 2, [3, 4], 5, [6, 7, 8], 9] >>> 2011/3/24 Tom Zych > Dharmit Shah wrote: > > I am learning Python and yesterday I cam across a definition wherein I > was > > supposed to flatten a list recursively. I am getting the solution > properly > > but wanted to know if I can optimize the code further. > > > > #!/usr/bin/env python > > new_list=[] > > def flatten(num_list): > > """ > > >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) > > [2, 9, 2, 1, 13, 2, 8, 2, 6] > > >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) > > [9, 7, 1, 13, 2, 8, 7, 6] > > >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) > > [9, 7, 1, 13, 2, 8, 2, 6] > > >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]]) > > [5, 5, 1, 5, 5, 5, 5, 6] > > """ > > global new_list > > for i in num_list: > > if type(i) == type([]): > > new_list = flatten(i) > > else: > > new_list.append(i) > > tmp = new_list > > new_list=[] > > return tmp > > > > if __name__=="__main__": > > import doctest > > doctest.testmod() > > > > PS - My knowledge of Python is still very basic and I am trying to dive > into > > it as deeper as I can. Solutions on Stackoverflow.com were beyond my > > understandability. > > Using doctest and getting a recursive function right don't strike me as > basic. This is pretty good for a beginner. > > I'll second Peter Otten regarding the use of a global. It's best to > avoid using globals whenever possible, not just for reentrancy, but for > more readable and maintainable code. A function should be self-contained > if possible. There's no reason you can't use a local variable in this > code (and you only need one, not two), and the resulting code would be > more readable. > > Regarding this line: > if type(i) == type([]): > > This also works: > if type(i) == list: > > But this is better: > if isinstance(i, list): > > isinstance(obj, class) means "is obj an instance of class or a subtype > of class", so it's more general. > > Does anyone see a way to do this with a list comprehension? I don't. > Would be a neat hack if it can be done. > > -- > Tom Zych / freethinker at pobox.com > "Because if they didn't vote for a lizard," said Ford, "the wrong lizard > might get in." -- DNA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Mar 24 10:55:48 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 24 Mar 2011 10:55:48 +0100 Subject: [Tutor] Recursively flatten the list In-Reply-To: References: <4D8B02B1.70400@pobox.com> Message-ID: 2011/3/24 Rafael Dur?n Casta?eda : > I can do it with two list comprehensions: > >>>> list_ = [1, 2, [3, 4], 5, [6, 7, 8], 9] >>>> [x[i] for x in list_ if isinstance(x, list) for i in range(len(x))] + [x >>>> for x in list_ if not isinstance(x, list)] > [3, 4, 6, 7, 8, 1, 2, 5, 9] >>>> > > But i loose original order, Can anyone do it with just one list > comprehension and/or keeping the order? A more important problem is that it is flattening only one level. Multi-level flattening is I think not possible without using some kind of recursion. -- Andr? Engels, andreengels at gmail.com From l.leichtnam at gmail.com Thu Mar 24 13:34:51 2011 From: l.leichtnam at gmail.com (louis leichtnam) Date: Thu, 24 Mar 2011 08:34:51 -0400 Subject: [Tutor] Parsing data from a csv file Message-ID: Hello, I am to extract a csv file from the web and parse it in python and after that make it into an html page. I want to get the data out of the csv file, get rid of the "," and make it readable. Questions: I would like to be able to print the line I want but I don't know how to do it. I would like to modify some lines, and make them cleaner Can you help me? import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv" simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') a=[] b=[] c=[] d=[] e=[] for char,meal,ate,qty,com in reader: for x in char: a.append(x) for y in meal: b.append(y) for z in ate: c.append(z) for aa in qty: d.append(aa) for bb in com: e.append(bb) for i in range(1::): print a[i]+b[i]+c[i]+d[i]+e[i] -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 24 14:24:54 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Mar 2011 09:24:54 -0400 Subject: [Tutor] Parsing data from a csv file In-Reply-To: References: Message-ID: On Thu, Mar 24, 2011 at 8:34 AM, louis leichtnam wrote: > Hello, > > I am to extract a csv file from the web and parse it in python and after > that make it into an html page. > > I want to get the data out of the csv file, get rid of the "," and make it > readable. > > Questions: > I would like to be able to print the line I want but I don't know how to do > it. > I would like to modify some lines, and make them cleaner > > Can you help me? > > > > > import urllib, csv > url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv > " > simpsons=urllib.urlopen(url) > reader=csv.reader(simpsons,delimiter=',',quotechar='"') > a=[] > b=[] > c=[] > d=[] > e=[] > for char,meal,ate,qty,com in reader: > at this point you have the five fields you want if you do print char, meal, ate, qty,com you will see your data with the commas gone > for x in char: > a.append(x) > for y in meal: > b.append(y) > for z in ate: > c.append(z) > for aa in qty: > d.append(aa) > for bb in com: > e.append(bb) > for i in range(1::): > print a[i]+b[i]+c[i]+d[i]+e[i] > > These for loops puzzle me. It looks like you are iterating over each character in each variable, then creating a list containing each character. I don't think you want to do that. The for i in range(1::): will give you an error. The range parameter needs to be something with a length, like a string, or a list, or a tuple. Can you show a little bit of your data file, and give us the traceback and output of your program? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.leichtnam at gmail.com Thu Mar 24 14:50:34 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Thu, 24 Mar 2011 13:50:34 +0000 Subject: [Tutor] Fw: Fw: Parsing data from a csv file [NC] Message-ID: <1967919397-1300974635-cardhu_decombobulator_blackberry.rim.net-588827835-@bda740.bisx.prod.on.blackberry> Thank you for your help Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Louis LEICHTNAM Date: Thu, 24 Mar 2011 09:48:04 To: Subject: Re: Fw: [Tutor] Parsing data from a csv file [NC] Hello the loops are a bit different, and I definitely don't know if it's correct but I want to be able to put each part of the cvs into my future html code. the cvs file is this one: and can be found there http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv l.leichtnam at gmail.com 03/24/2011 09:42 AM Please respond to l.leichtnam at gmail.com To Louis LEICHTNAM/us/socgen at socgen cc Subject Fw: [Tutor] Parsing data from a csv file On Thu, Mar 24, 2011 at 8:34 AM, louis leichtnam wrote: Hello, I am to extract a csv file from the web and parse it in python and after that make it into an html page. I want to get the data out of the csv file, get rid of the "," and make it readable. Questions: I would like to be able to print the line I want but I don't know how to do it. I would like to modify some lines, and make them cleaner Can you help me? import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv " simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') a=[] b=[] c=[] d=[] e=[] for char,meal,ate,qty,com in reader: at this point you have the five fields you want if you do print char, meal, ate, qty,com you will see your data with the commas gone for x in char: a.append(x) for y in meal: b.append(y) for z in ate: c.append(z) for aa in qty: d.append(aa) for bb in com: e.append(bb) for i in range(1::): print a[i]+b[i]+c[i]+d[i]+e[i] These for loops puzzle me. It looks like you are iterating over each character in each variable, then creating a list containing each character. I don't think you want to do that. The for i in range(1::): will give you an error. The range parameter needs to be something with a length, like a string, or a list, or a tuple. Can you show a little bit of your data file, and give us the traceback and output of your program? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick ************************************************************************* This message and any attachments (the "message") are confidential, intended solely for the addressee(s), and may contain legally privileged information. Any unauthorised use or dissemination is prohibited. E-mails are susceptible to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or affiliates shall be liable for the message if altered, changed or falsified. ************************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: simpsons_diet.csv Type: application/octet-stream Size: 665 bytes Desc: not available URL: From rafadurancastaneda at gmail.com Thu Mar 24 15:51:34 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 24 Mar 2011 15:51:34 +0100 Subject: [Tutor] Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: <1967919397-1300974635-cardhu_decombobulator_blackberry.rim.net-588827835-@bda740.bisx.prod.on.blackberry> References: <1967919397-1300974635-cardhu_decombobulator_blackberry.rim.net-588827835-@bda740.bisx.prod.on.blackberry> Message-ID: I don't know what are you going to do with data, but you can save all data in either a list or a dictionary, for example: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv" simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') diet_list = [] diet_dict = {} for char,meal,ate,qty,com in reader: if char != 'Character': diet_list.append([char, meal, ate, qty, com]) if diet_dict.has_key(char): diet_dict[char].append([meal, ate, qty, com]) else: diet_dict[char] = [[meal, ate, qty, com],] print diet_list print diet_dict 2011/3/24 > Thank you for your help > > Sent from my BlackBerry? on the MetroPCS Network > ------------------------------ > *From: * Louis LEICHTNAM > *Date: *Thu, 24 Mar 2011 09:48:04 -0400 > *To: * > *Subject: *Re: Fw: [Tutor] Parsing data from a csv file [NC] > > > Hello the loops are a bit different, and I definitely don't know if it's > correct but I want to be able to put each part of the cvs into my future > html code. > > the cvs file is this one: > > > and can be found there * > http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv* > > > > *l.leichtnam at gmail.com* > > 03/24/2011 09:42 AM > Please respond to > l.leichtnam at gmail.com > > To > Louis LEICHTNAM/us/socgen at socgen > cc > Subject > Fw: [Tutor] Parsing data from a csv file > > > > > > > On Thu, Mar 24, 2011 at 8:34 AM, louis leichtnam <*l.leichtnam at gmail.com*> > wrote: > Hello, > > I am to extract a csv file from the web and parse it in python and after > that make it into an html page. > > I want to get the data out of the csv file, get rid of the "," and make it > readable. > > Questions: > I would like to be able to print the line I want but I don't know how to do > it. > I would like to modify some lines, and make them cleaner > > Can you help me? > > > > > import urllib, csv > url=r"* > http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv* > " > simpsons=urllib.urlopen(url) > reader=csv.reader(simpsons,delimiter=',',quotechar='"') > a=[] > b=[] > c=[] > d=[] > e=[] > for char,meal,ate,qty,com in reader: > > at this point you have the five fields you want > if you do print char, meal, ate, qty,com you will see your data with the > commas gone > > for x in char: > a.append(x) > for y in meal: > b.append(y) > for z in ate: > c.append(z) > for aa in qty: > d.append(aa) > for bb in com: > e.append(bb) > for i in range(1::): > print a[i]+b[i]+c[i]+d[i]+e[i] > > > These for loops puzzle me. It looks like you are iterating over each > character in each variable, then creating a list containing each character. > I don't think you want to do that. > > The for i in range(1::): will give you an error. The range parameter needs > to be something with a length, like a string, or a list, or a tuple. > > Can you show a little bit of your data file, and give us the traceback and > output of your program? > _______________________________________________ > Tutor maillist - *Tutor at python.org* > To unsubscribe or change subscription options:* > **http://mail.python.org/mailman/listinfo/tutor* > > > > > -- > Joel Goldstick > > ************************************************************************* > This message and any attachments (the "message") are confidential, intended > solely for the addressee(s), and may contain legally privileged information. > Any unauthorised use or dissemination is prohibited. E-mails are susceptible > to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or > affiliates shall be liable for the message if altered, changed or falsified. > ************************************************************************* > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxchux at gmail.com Thu Mar 24 15:56:10 2011 From: duxchux at gmail.com (Chuck) Date: Thu, 24 Mar 2011 10:56:10 -0400 Subject: [Tutor] Pygame install error Message-ID: Hi, I'm trying to install pygame on my Win XP machine. I'm running Python 3.2. I can successfully use IDLE to run python scripts, and from the windows command line can run python from any directory. My PATH statement includes c:\python32;c:\python32\lib. pygame .msi file I used: pygame-1.9.1.win32-py3.1.msi After running the pygame install, the python32 site-packages directory does include a pygame folder and the file: pygame-1.9.1-py3.1.egg-info I'm wondering if pygame is supported for python 3.2 since the msi file indicates 3.1? Here's the error I'm getting: ==================== Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import pygame Traceback (most recent call last): File "", line 1, in import pygame File "C:\Python32\lib\site-packages\pygame\__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: The specified module could not be found. >>> -- ========================== Chuck DuxChux at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.leichtnam at gmail.com Thu Mar 24 16:07:33 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Thu, 24 Mar 2011 15:07:33 +0000 Subject: [Tutor] Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: References: <1967919397-1300974635-cardhu_decombobulator_blackberry.rim.net-588827835-@bda740.bisx.prod.on.blackberry> Message-ID: <1165056713-1300979254-cardhu_decombobulator_blackberry.rim.net-1939001982-@bda740.bisx.prod.on.blackberry> Thanks, what I'm trying to do is extract the data from the csv file, clean it to make each line into a sentence. But for this I think I need to use a dictionary for each and enter the words of each columns in one no? Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Rafael Dur?n Casta?eda Sender: tutor-bounces+l.leichtnam=gmail.com at python.org Date: Thu, 24 Mar 2011 15:51:34 To: Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From susana.delgado_s at utzmg.edu.mx Thu Mar 24 16:22:56 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 24 Mar 2011 09:22:56 -0600 Subject: [Tutor] if os.path.exists() or if not os.path.exists()? Message-ID: Hello everyone! I'm doing a python script that walks through files in my PC. Basically I'm searching files that end up with .shp, but these files must have extensions with .shx and .dbf. I want to write a .txt document which tells the user if a file doesn't exist in the directory. But I haven't been sucessful, I got the txt with wrong data, it shows an existing file. import os, csv, time, socket from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [ folders = Non for root, folders, files in os.walk( "C:\\" ): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(".shp")) writer = csv.writer(open('csv_pruebita.csv', "wb")) ruta = 'Ruta' archivo = 'archivo' prj = '.prj' proyeccion = 'proyeccion' campos = [ruta,archivo,prj,proyeccion] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepat log = open ("errors.txt","w+") if shapeData is None: print shp log.write(shp + "\n") else: #I splitted the filepath because I need the same filepath but with different extension n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' dbf = n[0]+'.dbf' filepath = ''+filepath+'' filename = ''+filename+'' #This block is wrong, I think here is the problem if os.path.exists(shx): print 'El archivo ' +shx +' existe' else: log.write('No existe el archivo ' +shx + "\n") if os.path.exists(dbf): print 'El archivo ' +dbf +' existe' log.write('No existe el archivo ' +dbf + "\n") #This block works properly if os.path.exists(p): prj_text = open(p, 'r').read() prjtext = ''+prj_text+'' aRow= [ filepath, filename, 1, prjtext] writer.writerow(aRow) else: no_prj = 'Sin prj, no se puede determinar la proyeccion' aRow1= [ filepath, filename, 0, no_prj] writer.writerow(aRow1) log.close() print "El archivo esta listo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Thu Mar 24 16:37:01 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 24 Mar 2011 16:37:01 +0100 Subject: [Tutor] Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: <1165056713-1300979254-cardhu_decombobulator_blackberry.rim.net-1939001982-@bda740.bisx.prod.on.blackberry> References: <1967919397-1300974635-cardhu_decombobulator_blackberry.rim.net-588827835-@bda740.bisx.prod.on.blackberry> <1165056713-1300979254-cardhu_decombobulator_blackberry.rim.net-1939001982-@bda740.bisx.prod.on.blackberry> Message-ID: Ok, I think what you are trying is to get all data in a string list: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv" simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') list_string = [] for char,meal,ate,qty,com in reader: if char != 'Character': list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) print list_string Doing something like this you can format all strings as you want and keep them into a list 2011/3/24 > Thanks, what I'm trying to do is extract the data from the csv file, clean > it to make each line into a sentence. > > But for this I think I need to use a dictionary for each and enter the > words of each columns in one no? > Sent from my BlackBerry? on the MetroPCS Network > > -----Original Message----- > From: Rafael Dur?n Casta?eda > > Sender: tutor-bounces+l.leichtnam=gmail.com at python.org > Date: Thu, 24 Mar 2011 15:51:34 > To: > Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From freethinker at pobox.com Thu Mar 24 16:41:57 2011 From: freethinker at pobox.com (Tom Zych) Date: Thu, 24 Mar 2011 11:41:57 -0400 Subject: [Tutor] if os.path.exists() or if not os.path.exists()? In-Reply-To: References: Message-ID: <1300981317.28956.1433425877@webmail.messagingengine.com> On Thu, 24 Mar 2011 09:22 -0600, "Susana Iraiis Delgado Rodriguez" wrote: > #This block is wrong, I think here is the problem > if os.path.exists(shx): > print 'El archivo ' +shx +' existe' > else: > log.write('No existe el archivo ' +shx + "\n") > if os.path.exists(dbf): > print 'El archivo ' +dbf +' existe' > log.write('No existe el archivo ' +dbf + "\n") I don't know about the rest, but you're missing an "else:" between the last two lines. -- Tom Zych / freethinker at pobox.com "Because if they didn't vote for a lizard," said Ford, "the wrong lizard might get in." -- DNA From l.leichtnam at gmail.com Thu Mar 24 16:53:18 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Thu, 24 Mar 2011 15:53:18 +0000 Subject: [Tutor] Fw: Fw: Fw: Parsing data from a csv file [NC] Message-ID: <881126721-1300981997-cardhu_decombobulator_blackberry.rim.net-274780746-@bda740.bisx.prod.on.blackberry> Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Louis LEICHTNAM Date: Thu, 24 Mar 2011 11:51:26 To: Subject: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] ----- Forwarded by Louis LEICHTNAM/us/socgen on 03/24/2011 11:51 AM ----- Louis LEICHTNAM/us/socgen 03/24/2011 11:48 AM To tutor-bounces+l.leichtnam=gmail.com at python.org, joel.goldstick at gmail.com, tutor at python.org, rafadurancastaneda at gmail.com cc Subject Re: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] For example the line 1 in the csv file is: Barney Gumble, Breakfast, Duffbeer, 1, I could?ve gone to Harvard and I want to be able to clean it and turn it into: Barney Gumble had for beakfast 1 Duffbeer while thinking "I coul?ve gone to Harvard" so basically using in this line the column0 + "had for " + column 1 + column3 + column2 + "while thinking"+column4 and I want to be able to do this for every line, except for line0. My end game is, after I'm able to do this, I want to write an Html using python that shows those cleand lines Thanks for your help l.leichtnam at gmail.com 03/24/2011 11:39 AM Please respond to l.leichtnam at gmail.com To Louis LEICHTNAM/us/socgen at socgen cc Subject Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] Ok, I think what you are trying is to get all data in a string list: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv " simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') list_string = [] for char,meal,ate,qty,com in reader: if char != 'Character': list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) print list_string Doing something like this you can format all strings as you want and keep them into a list 2011/3/24 Thanks, what I'm trying to do is extract the data from the csv file, clean it to make each line into a sentence. But for this I think I need to use a dictionary for each and enter the words of each columns in one no? Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Rafael Dur?n Casta?eda Sender: tutor-bounces+l.leichtnam=gmail.com at python.org Date: Thu, 24 Mar 2011 15:51:34 To: Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ************************************************************************* This message and any attachments (the "message") are confidential, intended solely for the addressee(s), and may contain legally privileged information. Any unauthorised use or dissemination is prohibited. E-mails are susceptible to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or affiliates shall be liable for the message if altered, changed or falsified. ************************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From l.leichtnam at gmail.com Thu Mar 24 18:45:40 2011 From: l.leichtnam at gmail.com (l.leichtnam at gmail.com) Date: Thu, 24 Mar 2011 17:45:40 +0000 Subject: [Tutor] Fw: Fw: Fw: Parsing data from a csv file [NC] Message-ID: <1765369308-1300988742-cardhu_decombobulator_blackberry.rim.net-757317861-@bda740.bisx.prod.on.blackberry> Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Louis LEICHTNAM Date: Thu, 24 Mar 2011 11:51:26 To: Subject: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] ----- Forwarded by Louis LEICHTNAM/us/socgen on 03/24/2011 11:51 AM ----- Louis LEICHTNAM/us/socgen 03/24/2011 11:48 AM To tutor-bounces+l.leichtnam=gmail.com at python.org, joel.goldstick at gmail.com, tutor at python.org, rafadurancastaneda at gmail.com cc Subject Re: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] For example the line 1 in the csv file is: Barney Gumble, Breakfast, Duffbeer, 1, I could?ve gone to Harvard and I want to be able to clean it and turn it into: Barney Gumble had for beakfast 1 Duffbeer while thinking "I coul?ve gone to Harvard" so basically using in this line the column0 + "had for " + column 1 + column3 + column2 + "while thinking"+column4 and I want to be able to do this for every line, except for line0. My end game is, after I'm able to do this, I want to write an Html using python that shows those cleand lines Thanks for your help l.leichtnam at gmail.com 03/24/2011 11:39 AM Please respond to l.leichtnam at gmail.com To Louis LEICHTNAM/us/socgen at socgen cc Subject Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] Ok, I think what you are trying is to get all data in a string list: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv " simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') list_string = [] for char,meal,ate,qty,com in reader: if char != 'Character': list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) print list_string Doing something like this you can format all strings as you want and keep them into a list 2011/3/24 Thanks, what I'm trying to do is extract the data from the csv file, clean it to make each line into a sentence. But for this I think I need to use a dictionary for each and enter the words of each columns in one no? Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Rafael Dur?n Casta?eda Sender: tutor-bounces+l.leichtnam=gmail.com at python.org Date: Thu, 24 Mar 2011 15:51:34 To: Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ************************************************************************* This message and any attachments (the "message") are confidential, intended solely for the addressee(s), and may contain legally privileged information. Any unauthorised use or dissemination is prohibited. E-mails are susceptible to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or affiliates shall be liable for the message if altered, changed or falsified. ************************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Thu Mar 24 20:25:09 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 24 Mar 2011 20:25:09 +0100 Subject: [Tutor] Fw: Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: <1064588056-1300993013-cardhu_decombobulator_blackberry.rim.net-1484955654-@bda740.bisx.prod.on.blackberry> References: <1064588056-1300993013-cardhu_decombobulator_blackberry.rim.net-1484955654-@bda740.bisx.prod.on.blackberry> Message-ID: Look again the code from my last message: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv" simpsons=urllib.urlopen(url) reader=csv.reader(simpsons, delimiter=',',quotechar='"') list_string = [] for char,meal,ate,qty,com in reader: if char != 'Character': list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) print list_string Run it and look the output, you will see that the strings from list_string are very close to the output you want. If you look specially this line: list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) You will see you need just change the variable's order and add some words to the string and you will get exactly the output you want, just try it! 2011/3/24 > Can you help me please? > > Sent from my BlackBerry? on the MetroPCS Network > ------------------------------ > *From: * Louis LEICHTNAM > *Date: *Thu, 24 Mar 2011 11:51:26 -0400 > *To: * > *Subject: *Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > > ----- Forwarded by Louis LEICHTNAM/us/socgen on 03/24/2011 11:51 AM ----- > *Louis LEICHTNAM/us/socgen* > > 03/24/2011 11:48 AM > To > tutor-bounces+l.leichtnam=gmail.com at python.org, joel.goldstick at gmail.com, > tutor at python.org, rafadurancastaneda at gmail.com > cc > Subject > Re: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC]Link > > > > For example the line 1 in the csv file is: > > Barney Gumble, Breakfast, Duffbeer, 1, I could?ve gone to Harvard > > and I want to be able to clean it and turn it into: > > Barney Gumble had for beakfast 1 Duffbeer while thinking "I coul?ve gone to > Harvard" > > so basically using in this line the column0 + "had for " + column 1 + > column3 + column2 + "while thinking"+column4 > > and I want to be able to do this for every line, except for line0. > > My end game is, after I'm able to do this, I want to write an Html using > python that shows those cleand lines > > Thanks for your help > > > > > *l.leichtnam at gmail.com* > > 03/24/2011 11:39 AM > Please respond to > l.leichtnam at gmail.com > > To > Louis LEICHTNAM/us/socgen at socgen > cc > Subject > Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > > > > Ok, I think what you are trying is to get all data in a string list: > > import urllib, csv > url=r"* > http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv* > " > simpsons=urllib.urlopen(url) > reader=csv.reader(simpsons,delimiter=',',quotechar='"') > > list_string = [] > > for char,meal,ate,qty,com in reader: > if char != 'Character': > list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) > > print list_string > > Doing something like this you can format all strings as you want and keep > them into a list > > 2011/3/24 <*l.leichtnam at gmail.com* > > Thanks, what I'm trying to do is extract the data from the csv file, clean > it to make each line into a sentence. > > But for this I think I need to use a dictionary for each and enter the > words of each columns in one no? > Sent from my BlackBerry? on the MetroPCS Network > > -----Original Message----- > From: Rafael Dur?n Casta?eda > <*rafadurancastaneda at gmail.com* > > Sender: tutor-bounces+l.leichtnam=*gmail.com* @* > python.org* > Date: Thu, 24 Mar 2011 15:51:34 > To: <*tutor at python.org* > > Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > _______________________________________________ > Tutor maillist - *Tutor at python.org* > To unsubscribe or change subscription options:* > **http://mail.python.org/mailman/listinfo/tutor* > > > ************************************************************************* > This message and any attachments (the "message") are confidential, intended > solely for the addressee(s), and may contain legally privileged information. > Any unauthorised use or dissemination is prohibited. E-mails are susceptible > to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or > affiliates shall be liable for the message if altered, changed or falsified. > ************************************************************************* > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 24 21:09:04 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Mar 2011 16:09:04 -0400 Subject: [Tutor] Fw: Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: <1765369308-1300988742-cardhu_decombobulator_blackberry.rim.net-757317861-@bda740.bisx.prod.on.blackberry> References: <1765369308-1300988742-cardhu_decombobulator_blackberry.rim.net-757317861-@bda740.bisx.prod.on.blackberry> Message-ID: On Thu, Mar 24, 2011 at 1:45 PM, wrote: > Sent from my BlackBerry? on the MetroPCS Network > ------------------------------ > *From: * Louis LEICHTNAM > *Date: *Thu, 24 Mar 2011 11:51:26 -0400 > *To: * > *Subject: *Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > > ----- Forwarded by Louis LEICHTNAM/us/socgen on 03/24/2011 11:51 AM ----- > > *Louis LEICHTNAM/us/socgen* > > 03/24/2011 11:48 AM > To > tutor-bounces+l.leichtnam=gmail.com at python.org, joel.goldstick at gmail.com, > tutor at python.org, rafadurancastaneda at gmail.com > cc > Subject > Re: Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC]Link > > > > For example the line 1 in the csv file is: > > Barney Gumble, Breakfast, Duffbeer, 1, I could?ve gone to Harvard > > and I want to be able to clean it and turn it into: > > Barney Gumble had for beakfast 1 Duffbeer while thinking "I coul?ve gone to > Harvard" > > so basically using in this line the column0 + "had for " + column 1 + > column3 + column2 + "while thinking"+column4 > > and I want to be able to do this for every line, except for line0. > > My end game is, after I'm able to do this, I want to write an Html using > python that shows those cleand lines > > Thanks for your help > > If the code below is doing what you like: list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) change it to this: list_string.append("%s had for %s %s %s while thinking '%s'" % (char, meal, qty, ate, com)) > > *l.leichtnam at gmail.com* > > 03/24/2011 11:39 AM > Please respond to > l.leichtnam at gmail.com > > To > Louis LEICHTNAM/us/socgen at socgen > cc > Subject > Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > > > > Ok, I think what you are trying is to get all data in a string list: > > import urllib, csv > url=r"* > http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv* > " > simpsons=urllib.urlopen(url) > reader=csv.reader(simpsons,delimiter=',',quotechar='"') > > list_string = [] > > for char,meal,ate,qty,com in reader: > if char != 'Character': > list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) > > print list_string > > Doing something like this you can format all strings as you want and keep > them into a list > > 2011/3/24 <*l.leichtnam at gmail.com* > > Thanks, what I'm trying to do is extract the data from the csv file, clean > it to make each line into a sentence. > > But for this I think I need to use a dictionary for each and enter the > words of each columns in one no? > Sent from my BlackBerry? on the MetroPCS Network > > -----Original Message----- > From: Rafael Dur?n Casta?eda > <*rafadurancastaneda at gmail.com* > > Sender: tutor-bounces+l.leichtnam=*gmail.com* @* > python.org* > Date: Thu, 24 Mar 2011 15:51:34 > To: <*tutor at python.org* > > Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] > > _______________________________________________ > Tutor maillist - *Tutor at python.org* > To unsubscribe or change subscription options:* > **http://mail.python.org/mailman/listinfo/tutor* > > > ************************************************************************* > This message and any attachments (the "message") are confidential, intended > solely for the addressee(s), and may contain legally privileged information. > Any unauthorised use or dissemination is prohibited. E-mails are susceptible > to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or > affiliates shall be liable for the message if altered, changed or falsified. > ************************************************************************* > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Thu Mar 24 22:01:21 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 24 Mar 2011 15:01:21 -0600 Subject: [Tutor] if os.path.exists() or if not os.path.exists()? Message-ID: OK!! I see the problem now! I also did a little change to the code, I open the .txt before the for stamentet. The script is working properly gdal.AllRegister() file_list = [ folders = Non for root, folders, files in os.walk( "C:\\" ): file_list.extend(os.path.join( root,fi) for fi in files if fi.endswith(".shp")) f = open('csv_pruebita.csv', 'wb') log = open ('errors.txt','wb') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' prj = '.prj' proyeccion = 'proyeccion' campos = [ruta,archivo,prj,proyeccion] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): #Partir la ruta del archivo en dos, ruta y nombre del archivo (ruta, filename) = os.path.split(filepath) #Escribir el nombre del archivo shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath #Abrir archivo de errores if shapeData is None: print shp log.write(shp+"\n") #Obtener la capa del shape else: ...... -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Fri Mar 25 04:54:55 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Thu, 24 Mar 2011 23:54:55 -0400 Subject: [Tutor] Guessing Game Program Message-ID: Hi folks, This is a little program I've written to bring together some things I've been trying to learn (not an attempt, of course, to make an interesting game).. I've been working my way through a beginner's tutorial, and except for a very basic program I wrote in C++ one time, I think this is the first program I've ever done from scratch. Of course, I've incorporated ideas I've learned from folks on the Internet, my tutorial, and this list. I"m sure I've broken some rules along the way, but it does work without any errors (that I have found). So, how could I improve it? Is it readable to you, or a mess? Thanks for your time, Don #Author D.Bedsole #drbedsole at gmail.com #3/24/10 #License: Public Domain import random from sys import exit #A guessing game where user must guess a number between 1 and 10 def start_up(): print "Hello, and welcome to the Guessing Game. Here are the rules:\n" print "Try to guess the correct number. It is between 1 and 10." print "You have ten chances." print "To quit the game just type 'quit' (w/o the quotes) at the prompt.\n" print "Here we go!\n" def ran_num(): the_number = random.randint(1,10) return the_number def guess_loop(the_number): start_number = 0 while start_number < 10: print "Please guess a number between 1-10. Enter your guess at the prompt." guess = (raw_input("> ")) if "exit" in guess: #Give user a chance to exit w/o finishing game print "Thanks for playing. Goodbye!" exit() if guess.isdigit(): #validate input guess = int(guess) else: print "You didn't enter a number." continue #Return to top of the loop so user can enter number if guess > the_number: print "Sorry. You guessed too high." start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries elif guess < the_number: print "Sorry. That was too low.\n" start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries else: print "Congratulations. You guessed it!\n" print "Do you want to play again? Type 'y' for yes and 'n' for no" response = raw_input("> ") if 'y' in response: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #Track guesses attempted and warn of end of game when chances exhausted def attempt_counter(start_number, the_number): print "That was attempt #%d." % (start_number) if start_number == 10: print "That was your last chance. The correct answer was %d." % (the_number) print "Do you want to start a new game. Type 'y' for yes and 'n' for no." answer = raw_input("> ") if 'y' in answer: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #function calls to start program start_up() guess_loop(ran_num()) From malcolm.newsome at gmail.com Fri Mar 25 05:37:18 2011 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Thu, 24 Mar 2011 23:37:18 -0500 Subject: [Tutor] Guessing Game Program In-Reply-To: References: Message-ID: <00f401cbeaa6$54049bd0$fc0dd370$@gmail.com> Hey Don! I posted an eerily similar request to another python group about two weeks ago! I, too, am very new to programming and the guessing game was my first shot at writing a script from scratch! Below is my code (improved with some help from others). I still would like to make some improvements to it also. But, perhaps there will be some ideas in it that can help you as well! Looking forward to learning and growing! All the best! Malcolm # guess.py # a simple number guessing game import random #helper method---------------------------------------------------------------------- ----------- def nope_message(random_num): return "Nope! I'm smarter than you!\nI was thinking of the number: %d" % int(random_num) def right_message(retried=False): message = "That was right! I guess you ARE smarter than me" if retried: message += "... even though it took you another try!" return message def reread_input(message): return int(input("You were too %s. Type another number: " % message)) def retry(message, random_num): guess_iflow = reread_input(message) if guess_iflow == random_num: return right_message(True) else: return nope_message(random_num) #--------------------------------------------------------------------------- ------------------ def main(): print "Do you think you're smarter than me?" print "I guess we'll see!" print "I'm thinking of a number between 1 - 100. Can you guess what it is?" random_num = random.randint(1, 100) guess = int(input("Type a number between 1 - 100: ")) error = guess < 1, guess < 100 if guess == random_num: print right_message() elif guess < random_num:# user gets second chance if number is too low print retry("low", random_num) elif guess > random_num:# user gets second chance if number is too high print retry("high", random_num) else: print nope_message(random_num) if __name__ == "__main__": main() -----Original Message----- From: tutor-bounces+malcolm.newsome=gmail.com at python.org [mailto:tutor-bounces+malcolm.newsome=gmail.com at python.org] On Behalf Of Donald Bedsole Sent: Thursday, March 24, 2011 10:55 PM To: tutor Subject: [Tutor] Guessing Game Program Hi folks, This is a little program I've written to bring together some things I've been trying to learn (not an attempt, of course, to make an interesting game).. I've been working my way through a beginner's tutorial, and except for a very basic program I wrote in C++ one time, I think this is the first program I've ever done from scratch. Of course, I've incorporated ideas I've learned from folks on the Internet, my tutorial, and this list. I"m sure I've broken some rules along the way, but it does work without any errors (that I have found). So, how could I improve it? Is it readable to you, or a mess? Thanks for your time, Don #Author D.Bedsole #drbedsole at gmail.com #3/24/10 #License: Public Domain import random from sys import exit #A guessing game where user must guess a number between 1 and 10 def start_up(): print "Hello, and welcome to the Guessing Game. Here are the rules:\n" print "Try to guess the correct number. It is between 1 and 10." print "You have ten chances." print "To quit the game just type 'quit' (w/o the quotes) at the prompt.\n" print "Here we go!\n" def ran_num(): the_number = random.randint(1,10) return the_number def guess_loop(the_number): start_number = 0 while start_number < 10: print "Please guess a number between 1-10. Enter your guess at the prompt." guess = (raw_input("> ")) if "exit" in guess: #Give user a chance to exit w/o finishing game print "Thanks for playing. Goodbye!" exit() if guess.isdigit(): #validate input guess = int(guess) else: print "You didn't enter a number." continue #Return to top of the loop so user can enter number if guess > the_number: print "Sorry. You guessed too high." start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries elif guess < the_number: print "Sorry. That was too low.\n" start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries else: print "Congratulations. You guessed it!\n" print "Do you want to play again? Type 'y' for yes and 'n' for no" response = raw_input("> ") if 'y' in response: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #Track guesses attempted and warn of end of game when chances exhausted def attempt_counter(start_number, the_number): print "That was attempt #%d." % (start_number) if start_number == 10: print "That was your last chance. The correct answer was %d." % (the_number) print "Do you want to start a new game. Type 'y' for yes and 'n' for no." answer = raw_input("> ") if 'y' in answer: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #function calls to start program start_up() guess_loop(ran_num()) _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From drbedsole at gmail.com Fri Mar 25 05:55:33 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 25 Mar 2011 00:55:33 -0400 Subject: [Tutor] Guessing Game Program In-Reply-To: References: <00f401cbeaa6$54049bd0$fc0dd370$@gmail.com> Message-ID: On Fri, Mar 25, 2011 at 12:53 AM, Donald Bedsole wrote: > Hi Malcolm :-) > > On Fri, Mar 25, 2011 at 12:37 AM, Malcolm Newsome > wrote: >> Hey Don! >> >> I posted an eerily similar request to another python group about two weeks >> ago! ?I, too, am very new to programming and the guessing game was my first >> shot at writing a script from scratch! > > I got interested in writing a guessing game because I was trying to > fix a C++ program that wouldn't compile with g++ because they were > using a non-standard randomizer() function. ?(I really don't know C++, > but I thought trying to fix the problems with someone else's program > might help me to learn). ?I didn't make much headway in understanding > how to generate random numbers in C++, but it made me curious about > how to do it in Python. ?Python seems much easier! > >> >> Below is my code (improved with some help from others). ?I still would like >> to make some improvements to it also. ?But, perhaps there will be some ideas >> in it that can help you as well! ?Looking forward to learning and growing! >> >> All the best! >> >> Malcolm > > > Thanks for posting your code. ?I will look at it later (closing in on > 1:00 AM here) to see what I can learn from it. ?Tutorials are great, > but it seems looking at code makes it easier for me to learn. > > Thanks for taking the time to post, and I hope you're successful in > your programming studies. > > Don > From lea-parker at bigpond.com Fri Mar 25 06:27:41 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Fri, 25 Mar 2011 16:27:41 +1100 Subject: [Tutor] Error in programming Message-ID: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> Hello Just wondering if you have some time to cast your eyes over another basic program. # Prompt user for data def main(): print 'This program is to calculate your ticket sales to the softball game' print #blank line # Value of each level of seat a_seat = 15.00 b_seat = 12.00 c_seat = 9.00 # Obtain data sales_a = int (raw_input('Enter the number of class A tickets sold ')) sales_b = int (raw_input('Enter the number of class B tickets sold ')) sales_c = int (raw_input('Enter the number of class C tickets sold ')) income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) # Obtain data to determine income generated from sales def income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c): total_sales = """times the seat value by the number of seats sold for each seat and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c * c_seat) #Display result to user print int ('Your total sales for the softball game are: $ ', total_sales) # Call the main function main() I get the following errors: >>> ================================ RESTART ================================ >>> This program is to calculate your ticket sales to the softball game Enter the number of class A tickets sold 5 Enter the number of class B tickets sold 5 Enter the number of class C tickets sold 10 Traceback (most recent call last): File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 29, in main() File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 18, in main income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 23, in income_generated and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c * c_seat) NameError: global name 'sale_a' is not defined >>> My way of thinking is firstly I need to fix line 29 which is main(), I tried to do this by adding the brackets around text output in line 26. This seemed to allow me to type main against margin rather than it wanting to indent but didn't fix the problem. Your suggestions would be appreciated. Thank Lea -------------- next part -------------- An HTML attachment was scrubbed... URL: From drbedsole at gmail.com Fri Mar 25 06:37:44 2011 From: drbedsole at gmail.com (Donald Bedsole) Date: Fri, 25 Mar 2011 01:37:44 -0400 Subject: [Tutor] Error in programming In-Reply-To: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> References: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> Message-ID: Hi Lea, On Fri, Mar 25, 2011 at 1:27 AM, Lea Parker wrote: > Hello > > > > Just wondering if you have some time to cast your eyes over another? basic > program. > > > > # Prompt user for data > > def main(): > > ??? print 'This program is to calculate your ticket sales to the softball > game' > > ??? print?????????????????????????????????? #blank line > > > > ??? # Value of each level of seat > > ??? a_seat = 15.00 > > ??? b_seat = 12.00 > > ??? c_seat = 9.00 > > > > ??? # Obtain data > > ??? sales_a = int (raw_input('Enter the number of class A tickets sold ')) > > ??? sales_b = int (raw_input('Enter the number of class B tickets sold ')) > > ??? sales_c = int (raw_input('Enter the number of class C tickets sold ')) > > ????income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) > > > > # Obtain data to determine income generated from sales > > def income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c): > > ??? total_sales = """times the seat value by the number of seats sold for > each seat > > ??? and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c > * c_seat) > > > > ??? #Display result to user > > ??? print int ('Your total sales for the softball game are: $ ', > total_sales) > > > > # Call the main function > > main() > > > > I get the following errors: > >>>> ================================ RESTART >>>> ================================ > >>>> > > This program is to calculate your ticket sales to the softball game > > > > Enter the number of class A tickets sold 5 > > Enter the number of class B tickets sold 5 > > Enter the number of class C tickets sold 10 > > > > Traceback (most recent call last): > > ? File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - > Programming Principles/2011/Assessment Tasks/Assessment 1b and > 1c/Stadium_Seating.py", line 29, in > > ??? main() > > ? File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - > Programming Principles/2011/Assessment Tasks/Assessment 1b and > 1c/Stadium_Seating.py", line 18, in main > > ??? income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) > > ? File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - > Programming Principles/2011/Assessment Tasks/Assessment 1b and > 1c/Stadium_Seating.py", line 23, in income_generated > > ??? and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c > * c_seat) > > NameError: global name 'sale_a' is not defined > >>>> > > > > My way of thinking is firstly I need to fix line 29 which is main(), I tried > to do this by adding the brackets around text output in line 26. This seemed > to allow me to type main against margin rather than it wanting to indent but > didn?t fix the problem. Your suggestions would be appreciated. > > > > Thank > > Lea > Don't know if it's the only problem, but : > NameError: global name 'sale_a' is not defined I think this comes from the fact that you spelled one variable name "sale_a" in one place, and up where you originally assigned it you spelled it, "sales_a." Don From bgailer at gmail.com Fri Mar 25 07:00:10 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 25 Mar 2011 01:00:10 -0500 Subject: [Tutor] Error in programming In-Reply-To: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> References: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> Message-ID: <4D8C2F6A.3020605@gmail.com> On 3/25/2011 12:27 AM, Lea Parker wrote: > > *Hello* > > ** > > *Just wondering if you have some time to cast your eyes over another > basic program.* > Donald pointed out the first error. (actually there are 3 such spelling errors). When you get "name xxx is not defined" use your editor's find feature to find where the name is defined. In this case you would not find it which should lead you to the problem. When you fix that you will then get TypeError: 'str' object is not callable on the same line of code. Do you see why? When you fix that you will then get either ValueError: invalid literal for int() or ValueError: int() base must be >= 2 and <= 36 Before returning with "why" attempt to apply the error message to the code to see what the problems are. Look up int() in the Python documentation > > ** > > # Prompt user for data > > def main(): > > print 'This program is to calculate your ticket sales to the > softball game' > > print #blank line > > # Value of each level of seat > > a_seat = 15.00 > > b_seat = 12.00 > > c_seat = 9.00 > > # Obtain data > > sales_a = int (raw_input('Enter the number of class A tickets sold ')) > > sales_b = int (raw_input('Enter the number of class B tickets sold ')) > > sales_c = int (raw_input('Enter the number of class C tickets sold > ')) > > income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) > > # Obtain data to determine income generated from sales > > def income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c): > > total_sales = """times the seat value by the number of seats sold > for each seat > > and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + > (sale_c * c_seat) > > #Display result to user > > print int ('Your total sales for the softball game are: $ ', > total_sales) > > # Call the main function > > main() > > *I get the following errors:* > > >>> ================================ RESTART > ================================ > > >>> > > This program is to calculate your ticket sales to the softball game > > Enter the number of class A tickets sold 5 > > Enter the number of class B tickets sold 5 > > Enter the number of class C tickets sold 10 > > Traceback (most recent call last): > > File "F:/Backups/MY Documents26.2.11/Documents/Lea > University/CSU/ITC10 - Programming Principles/2011/Assessment > Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 29, in > > main() > > File "F:/Backups/MY Documents26.2.11/Documents/Lea > University/CSU/ITC10 - Programming Principles/2011/Assessment > Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 18, in main > > income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) > > File "F:/Backups/MY Documents26.2.11/Documents/Lea > University/CSU/ITC10 - Programming Principles/2011/Assessment > Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 23, in > income_generated > > and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + > (sale_c * c_seat) > > NameError: global name 'sale_a' is not defined > > >>> > > *My way of thinking is firstly I need to fix line 29 which is main(), > I tried to do this by adding the brackets around text output in line > 26. This seemed to allow me to type main against margin rather than it > wanting to indent but didn't fix the problem. Your suggestions would > be appreciated.* > > ** > > *Thank* > > *Lea* > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lea-parker at bigpond.com Fri Mar 25 07:04:15 2011 From: lea-parker at bigpond.com (Lea Parker) Date: Fri, 25 Mar 2011 17:04:15 +1100 Subject: [Tutor] Tutor Digest, Vol 85, Issue 91 In-Reply-To: References: Message-ID: <000501cbeab2$786fc420$694f4c60$@bigpond.com> Message 3 - I solved my problem. Yah Me!!! Thanks P.S I hope this is the right way to let you know so you don't waste your time. Lea -----Original Message----- From: tutor-bounces+lea-parker=bigpond.com at python.org [mailto:tutor-bounces+lea-parker=bigpond.com at python.org] On Behalf Of tutor-request at python.org Sent: Friday, 25 March 2011 4:28 PM To: tutor at python.org Subject: Tutor Digest, Vol 85, Issue 91 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Guessing Game Program (Malcolm Newsome) 2. Re: Guessing Game Program (Donald Bedsole) 3. Error in programming (Lea Parker) ---------------------------------------------------------------------- Message: 1 Date: Thu, 24 Mar 2011 23:37:18 -0500 From: "Malcolm Newsome" To: "'Donald Bedsole'" , Subject: Re: [Tutor] Guessing Game Program Message-ID: <00f401cbeaa6$54049bd0$fc0dd370$@gmail.com> Content-Type: text/plain; charset="us-ascii" Hey Don! I posted an eerily similar request to another python group about two weeks ago! I, too, am very new to programming and the guessing game was my first shot at writing a script from scratch! Below is my code (improved with some help from others). I still would like to make some improvements to it also. But, perhaps there will be some ideas in it that can help you as well! Looking forward to learning and growing! All the best! Malcolm # guess.py # a simple number guessing game import random #helper method---------------------------------------------------------------------- ----------- def nope_message(random_num): return "Nope! I'm smarter than you!\nI was thinking of the number: %d" % int(random_num) def right_message(retried=False): message = "That was right! I guess you ARE smarter than me" if retried: message += "... even though it took you another try!" return message def reread_input(message): return int(input("You were too %s. Type another number: " % message)) def retry(message, random_num): guess_iflow = reread_input(message) if guess_iflow == random_num: return right_message(True) else: return nope_message(random_num) #--------------------------------------------------------------------------- ------------------ def main(): print "Do you think you're smarter than me?" print "I guess we'll see!" print "I'm thinking of a number between 1 - 100. Can you guess what it is?" random_num = random.randint(1, 100) guess = int(input("Type a number between 1 - 100: ")) error = guess < 1, guess < 100 if guess == random_num: print right_message() elif guess < random_num:# user gets second chance if number is too low print retry("low", random_num) elif guess > random_num:# user gets second chance if number is too high print retry("high", random_num) else: print nope_message(random_num) if __name__ == "__main__": main() -----Original Message----- From: tutor-bounces+malcolm.newsome=gmail.com at python.org [mailto:tutor-bounces+malcolm.newsome=gmail.com at python.org] On Behalf Of Donald Bedsole Sent: Thursday, March 24, 2011 10:55 PM To: tutor Subject: [Tutor] Guessing Game Program Hi folks, This is a little program I've written to bring together some things I've been trying to learn (not an attempt, of course, to make an interesting game).. I've been working my way through a beginner's tutorial, and except for a very basic program I wrote in C++ one time, I think this is the first program I've ever done from scratch. Of course, I've incorporated ideas I've learned from folks on the Internet, my tutorial, and this list. I"m sure I've broken some rules along the way, but it does work without any errors (that I have found). So, how could I improve it? Is it readable to you, or a mess? Thanks for your time, Don #Author D.Bedsole #drbedsole at gmail.com #3/24/10 #License: Public Domain import random from sys import exit #A guessing game where user must guess a number between 1 and 10 def start_up(): print "Hello, and welcome to the Guessing Game. Here are the rules:\n" print "Try to guess the correct number. It is between 1 and 10." print "You have ten chances." print "To quit the game just type 'quit' (w/o the quotes) at the prompt.\n" print "Here we go!\n" def ran_num(): the_number = random.randint(1,10) return the_number def guess_loop(the_number): start_number = 0 while start_number < 10: print "Please guess a number between 1-10. Enter your guess at the prompt." guess = (raw_input("> ")) if "exit" in guess: #Give user a chance to exit w/o finishing game print "Thanks for playing. Goodbye!" exit() if guess.isdigit(): #validate input guess = int(guess) else: print "You didn't enter a number." continue #Return to top of the loop so user can enter number if guess > the_number: print "Sorry. You guessed too high." start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries elif guess < the_number: print "Sorry. That was too low.\n" start_number += 1 attempt_counter(start_number, the_number)#warn user of remaining tries else: print "Congratulations. You guessed it!\n" print "Do you want to play again? Type 'y' for yes and 'n' for no" response = raw_input("> ") if 'y' in response: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #Track guesses attempted and warn of end of game when chances exhausted def attempt_counter(start_number, the_number): print "That was attempt #%d." % (start_number) if start_number == 10: print "That was your last chance. The correct answer was %d." % (the_number) print "Do you want to start a new game. Type 'y' for yes and 'n' for no." answer = raw_input("> ") if 'y' in answer: start_up(guess_loop(ran_num())) else: print "Thanks for playing. Goodbye." exit() #function calls to start program start_up() guess_loop(ran_num()) _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 2 Date: Fri, 25 Mar 2011 00:55:33 -0400 From: Donald Bedsole To: tutor Subject: Re: [Tutor] Guessing Game Program Message-ID: Content-Type: text/plain; charset=ISO-8859-1 On Fri, Mar 25, 2011 at 12:53 AM, Donald Bedsole wrote: > Hi Malcolm :-) > > On Fri, Mar 25, 2011 at 12:37 AM, Malcolm Newsome > wrote: >> Hey Don! >> >> I posted an eerily similar request to another python group about two >> weeks ago! ?I, too, am very new to programming and the guessing game >> was my first shot at writing a script from scratch! > > I got interested in writing a guessing game because I was trying to > fix a C++ program that wouldn't compile with g++ because they were > using a non-standard randomizer() function. ?(I really don't know C++, > but I thought trying to fix the problems with someone else's program > might help me to learn). ?I didn't make much headway in understanding > how to generate random numbers in C++, but it made me curious about > how to do it in Python. ?Python seems much easier! > >> >> Below is my code (improved with some help from others). ?I still >> would like to make some improvements to it also. ?But, perhaps there >> will be some ideas in it that can help you as well! ?Looking forward to learning and growing! >> >> All the best! >> >> Malcolm > > > Thanks for posting your code. ?I will look at it later (closing in on > 1:00 AM here) to see what I can learn from it. ?Tutorials are great, > but it seems looking at code makes it easier for me to learn. > > Thanks for taking the time to post, and I hope you're successful in > your programming studies. > > Don > ------------------------------ Message: 3 Date: Fri, 25 Mar 2011 16:27:41 +1100 From: "Lea Parker" To: Subject: [Tutor] Error in programming Message-ID: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> Content-Type: text/plain; charset="us-ascii" Hello Just wondering if you have some time to cast your eyes over another basic program. # Prompt user for data def main(): print 'This program is to calculate your ticket sales to the softball game' print #blank line # Value of each level of seat a_seat = 15.00 b_seat = 12.00 c_seat = 9.00 # Obtain data sales_a = int (raw_input('Enter the number of class A tickets sold ')) sales_b = int (raw_input('Enter the number of class B tickets sold ')) sales_c = int (raw_input('Enter the number of class C tickets sold ')) income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) # Obtain data to determine income generated from sales def income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c): total_sales = """times the seat value by the number of seats sold for each seat and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c * c_seat) #Display result to user print int ('Your total sales for the softball game are: $ ', total_sales) # Call the main function main() I get the following errors: >>> ================================ RESTART ================================ >>> This program is to calculate your ticket sales to the softball game Enter the number of class A tickets sold 5 Enter the number of class B tickets sold 5 Enter the number of class C tickets sold 10 Traceback (most recent call last): File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 29, in main() File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 18, in main income_generated(a_seat, b_seat, c_seat, sales_a, sales_b, sales_c) File "F:/Backups/MY Documents26.2.11/Documents/Lea University/CSU/ITC10 - Programming Principles/2011/Assessment Tasks/Assessment 1b and 1c/Stadium_Seating.py", line 23, in income_generated and add totals togeter"""(sale_a * a_seat) + (sale_b * b_seat) + (sale_c * c_seat) NameError: global name 'sale_a' is not defined >>> My way of thinking is firstly I need to fix line 29 which is main(), I tried to do this by adding the brackets around text output in line 26. This seemed to allow me to type main against margin rather than it wanting to indent but didn't fix the problem. Your suggestions would be appreciated. Thank Lea -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 85, Issue 91 ************************************* From steve at pearwood.info Fri Mar 25 08:14:29 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Mar 2011 18:14:29 +1100 Subject: [Tutor] Tutor Digest, Vol 85, Issue 91 In-Reply-To: <000501cbeab2$786fc420$694f4c60$@bigpond.com> References: <000501cbeab2$786fc420$694f4c60$@bigpond.com> Message-ID: <4D8C40D5.3030703@pearwood.info> Lea Parker wrote: > Message 3 - I solved my problem. Yah Me!!! > > Thanks > > P.S I hope this is the right way to let you know so you don't waste your > time. Hi Lea, glad you solved the problem, and welcome. For the future though, when replying to a digest, you should edit the subject line to be something more meaningful than "Re: Tutor Digest". Using the original subject line of your post is probably best (plus "Re:" at the start of course). Also, there's no need to quote the *entire* digest, potentially hundreds or even thousands of lines, just to refer to one small part of it. Grumpy old curmudgeons like me have a tendency to bark if you do. (We rarely bite though.) So please trim your reply to only include enough quoting to establish context: [...] > Message: 3 > Date: Fri, 25 Mar 2011 16:27:41 +1100 > From: "Lea Parker" > To: > Subject: [Tutor] Error in programming > Message-ID: <000001cbeaad$5ce95b30$16bc1190$@bigpond.com> > Content-Type: text/plain; charset="us-ascii" > > Hello > > Just wondering if you have some time to cast your eyes over another basic > program. [...] > My way of thinking is firstly I need to fix line 29 which is main(), I tried > to do this by adding the brackets around text output in line 26. This seemed > to allow me to type main against margin rather than it wanting to indent but > didn't fix the problem. Your suggestions would be appreciated. If you're going to hang around asking a lot of questions, you'll probably find it easy to have discussions if you don't use the Digest feature and instead receive individual emails. Regards, -- Steven From robert.sjoblom at gmail.com Fri Mar 25 12:52:37 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 25 Mar 2011 12:52:37 +0100 Subject: [Tutor] if value not in dictionary, do a? Message-ID: Hi again, list! A quick question about dictionary behaviour. I have a dictionary of keys, and the user should be able to enter values into said dictionary. My idea was this: def addData(key, value): dictionary[key] += int(value) return None dictionary = {"a":0, "b":0, "c":0, "d":0} for key in dictionary: a = input("Enter key: ") b = int(input("Enter value: ")) try: addData(a, b) except: continue Which works fine, but the problem is that I need to ensure that every key gets a value above 0; the try/except is clearly not doing that (and it can't deal with b=int(input("Enter value:" )) because there's no try for that, which I suppose there should be). How would I go about making sure that each key gets a value above 0 in this case? Also, is there a better way to do what I'm trying to do than what I've come up with? I'm trying to translate a paper form into data arrays for later use (and this particular part is simple in comparison to some other parts where you get one name and multiple values to that name, which I have no idea how to solve, but I figure one step at a time, and the current step is this one), but I'm quite the newbie at programming. Still. best regards, Robert S. From ajarncolin at gmail.com Fri Mar 25 13:07:49 2011 From: ajarncolin at gmail.com (col speed) Date: Fri, 25 Mar 2011 19:07:49 +0700 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: I am a newbie too, but.... from collections import defaultdict Then you can do: data = defaultdict(int) Everything (all keys) start at 0, so you can do "+=" with no problem. I'm sure somebody else has a better solution though! Cheers Colin On 25 March 2011 18:52, Robert Sjoblom wrote: > Hi again, list! A quick question about dictionary behaviour. I have a > dictionary of keys, and the user should be able to enter values into > said dictionary. My idea was this: > > def addData(key, value): > dictionary[key] += int(value) > return None > > dictionary = {"a":0, "b":0, "c":0, "d":0} > > for key in dictionary: > a = input("Enter key: ") > b = int(input("Enter value: ")) > try: > addData(a, b) > except: > continue > > Which works fine, but the problem is that I need to ensure that every > key gets a value above 0; the try/except is clearly not doing that > (and it can't deal with b=int(input("Enter value:" )) because there's > no try for that, which I suppose there should be). How would I go > about making sure that each key gets a value above 0 in this case? > Also, is there a better way to do what I'm trying to do than what I've > come up with? I'm trying to translate a paper form into data arrays > for later use (and this particular part is simple in comparison to > some other parts where you get one name and multiple values to that > name, which I have no idea how to solve, but I figure one step at a > time, and the current step is this one), but I'm quite the newbie at > programming. Still. > > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Mar 25 13:13:44 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 25 Mar 2011 13:13:44 +0100 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: On Fri, Mar 25, 2011 at 12:52 PM, Robert Sjoblom wrote: > Hi again, list! A quick question about dictionary behaviour. I have a > dictionary of keys, and the user should be able to enter values into > said dictionary. My idea was this: > > def addData(key, value): > ? ?dictionary[key] += int(value) > ? ?return None > > dictionary = {"a":0, "b":0, "c":0, "d":0} > > for key in dictionary: > ? ?a = input("Enter key: ") > ? ?b = int(input("Enter value: ")) > ? ?try: > ? ? ? ?addData(a, b) > ? ?except: > ? ? ? ?continue > Why are you asking for the user to enter a key? you're iterating over all keys in the dictionary, so there's no need to ask the user for keys, you already know them. Why not do this: b = int(input("Enter value for key %s: " % key)) dictionary[key] = b This way you can be sure a value is entered for every key, and no key is entered twice. You'll still need to check the user doesn't just enter 0 though. Another few points: * you don't ave to add return None in that function. If you get to the end of a function and there's no return statement, None is automatically returned. * don't use a blank except. *ever*. If you really want to catch everything, do "except Exception:" otherwise, catch what you expect to be thrown in this case, "except KeyError" Hugo From rafadurancastaneda at gmail.com Fri Mar 25 13:26:33 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Fri, 25 Mar 2011 13:26:33 +0100 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: In addition I think defaultdict doesn't avoid neither entering negatives nor something that isn't an integer, you could try something like this: >>> dictionary = {} >>> for _ in range(4): key = input("Enter key: ") value = 0 while value <= 0: try: value = int(input("Enter a value: ")) except ValueError: print("Value must be an integer!") else: if(value <= 0): print("Value must be greater than 0") dictionary[key] = value Enter key: a Enter a value: 1 Enter key: b Enter a value: 0 Value must be greater than 0 Enter a value: -1 Value must be greater than 0 Enter a value: sdf Value must be an integer! Enter a value: 2 Enter key: c Enter a value: 3 Enter key: d Enter a value: 4 >>> dictionary {'a': 1, 'c': 3, 'b': 2, 'd': 4} >>> 2011/3/25 Hugo Arts > On Fri, Mar 25, 2011 at 12:52 PM, Robert Sjoblom > wrote: > > Hi again, list! A quick question about dictionary behaviour. I have a > > dictionary of keys, and the user should be able to enter values into > > said dictionary. My idea was this: > > > > def addData(key, value): > > dictionary[key] += int(value) > > return None > > > > dictionary = {"a":0, "b":0, "c":0, "d":0} > > > > for key in dictionary: > > a = input("Enter key: ") > > b = int(input("Enter value: ")) > > try: > > addData(a, b) > > except: > > continue > > > > Why are you asking for the user to enter a key? you're iterating over > all keys in the dictionary, so there's no need to ask the user for > keys, you already know them. Why not do this: > > b = int(input("Enter value for key %s: " % key)) > dictionary[key] = b > > This way you can be sure a value is entered for every key, and no key > is entered twice. You'll still need to check the user doesn't just > enter 0 though. > > Another few points: > * you don't ave to add return None in that function. If you get to the > end of a function and there's no return statement, None is > automatically returned. > * don't use a blank except. *ever*. If you really want to catch > everything, do "except Exception:" otherwise, catch what you expect to > be thrown in this case, "except KeyError" > > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Fri Mar 25 16:46:13 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 25 Mar 2011 11:46:13 -0400 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: On Fri, Mar 25, 2011 at 7:52 AM, Robert Sjoblom wrote: > Hi again, list! A quick question about dictionary behaviour. I have a > dictionary of keys, and the user should be able to enter values into > said dictionary. My idea was this: > > def addData(key, value): > dictionary[key] += int(value) > return None > > dictionary = {"a":0, "b":0, "c":0, "d":0} > > for key in dictionary: > a = input("Enter key: ") > b = int(input("Enter value: ")) > try: > addData(a, b) > except: > continue > > Which works fine, but the problem is that I need to ensure that every > key gets a value above 0; the try/except is clearly not doing that > (and it can't deal with b=int(input("Enter value:" )) because there's > no try for that, which I suppose there should be). How would I go > about making sure that each key gets a value above 0 in this case? > Also, is there a better way to do what I'm trying to do than what I've > come up with? I'm trying to translate a paper form into data arrays > for later use (and this particular part is simple in comparison to > some other parts where you get one name and multiple values to that > name, which I have no idea how to solve, but I figure one step at a > time, and the current step is this one), but I'm quite the newbie at > programming. Still. > > best regards, > Robert S. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > How would I go > about making sure that each key gets a value above 0 in this case? I would probably add a separate function with an if / then type structure. The separate function would simply be activated if the value is 0, at which point the input would say "You didn't enter a value greater than 0, please enter a value" or some such. Also, is there a better way to do what I'm trying to do than what I've > come up with? I'm not 100% what you are trying to accomplish. I'm trying to translate a paper form into data arrays > for later use (and this particular part is simple in comparison to > some other parts where you get one name and multiple values to that > name This sounds like a database. For example, I have many attributes, some of these I share with others, some are unique to me, some are variations on a common theme. So, for example, Jamie is 6'00, brown eyes, brown hair, etc. Or {Jamie : [72, Brown, Brown,...]} You can store the attributes in a list so long as they are always in the same order, and then just look up the attributes as you need them, so person[Jamie][0] will yield 72. The other way to go, depending on your data of course and its complexity would be to use a relational database. Python comes with SQlite in it, and if you don't know SQL, this could be a good opportunity to learn some of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Mar 25 16:56:25 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 25 Mar 2011 10:56:25 -0500 Subject: [Tutor] Tutoring Message-ID: <4D8CBB29.2040901@gmail.com> I have recently become a tutor to several Python students. I enjoy tutoring and they benefit from it. I work with some students using remote access, so we can be geographically far apart. Who do you know who might benefit from receiving one-on-one tutoring? -- Bob Gailer 919-636-4239 Chapel Hill NC From robert.sjoblom at gmail.com Fri Mar 25 17:11:00 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 25 Mar 2011 17:11:00 +0100 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: -- Hugo Arts wrote -- >Why are you asking for the user to enter a key? you're iterating over >all keys in the dictionary, so there's no need to ask the user for >keys, you already know them. Why not do this: >b = int(input("Enter value for key %s: " % key)) >dictionary[key] = b I have a great answer to that, actually. I simply forgot that you could. I _knew_ that there was a better way of doing what I was trying to accomplish, but I needed the user to know which key was being entered, and I completely forgot about %s. >* don't use a blank except. *ever*. If you really want to catch >everything, do "except Exception:" otherwise, catch what you expect to >be thrown in this case, "except KeyError" I received your email just as I left my computer, and didn't want to type out an answer on my phone (because smartphones aren't smart enough for that yet), and my first reaction was "why?" followed by "I need my program to continue even if I get the errors at this part, so why?" I soon realized that catching all errors would mean never seeing the errors you might not foresee. I know that I could get either ValueError or KeyError, but there could be something else somewhere else in the code that could send an error (unlikely as it is) down that path and with a blank except I would never actually see that happen. Am I somewhat close to the real reason why? -- James Reynolds wrote -- >> ?I'm trying to translate a paper form into data arrays >> for later use (and this particular part is simple in comparison to >> some other parts where you get one name and multiple values to that >> name > > This sounds like a database. For example, I have many attributes, some of > these I share with others, some are unique to me, some are variations on a > common theme. > So, for example, Jamie is 6'00, brown eyes, brown hair, etc. Or {Jamie : > [72, Brown, Brown,...]} > You can store the attributes in a list so long as they are always in the > same order, and then just look up the attributes as you need them, so > person[Jamie][0] will yield 72. > The other way to go, depending on your data of course and its complexity > would be to use a relational database. Python comes with SQlite in it, and > if you don't know SQL, this could be a good opportunity to learn some of > it. Both of those are great ideas that I'm happy to steal -- thank you! I dabbled some in databases a couple of years back, but I never really focused on learning any of it properly, so what little I knew has long since been lost to me. I think that for now it'll be enough to store the data in a list but I'll definitely keep databases in mind. I know that I'll probably have to learn them sooner or later, if not for this project then for some other project down the road. My issue (small as it may have been) have been resolved by the answers I've received today, so thank you all for your time and help. -- best regards, Robert S. From hugo.yoshi at gmail.com Fri Mar 25 17:24:07 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 25 Mar 2011 17:24:07 +0100 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: On Fri, Mar 25, 2011 at 5:11 PM, Robert Sjoblom wrote: > -- Hugo Arts wrote -- > >>Why are you asking for the user to enter a key? you're iterating over >>all keys in the dictionary, so there's no need to ask the user for >>keys, you already know them. Why not do this: > >>b = int(input("Enter value for key %s: " % key)) >>dictionary[key] = b > > I have a great answer to that, actually. I simply forgot that you > could. I _knew_ that there was a better way of doing what I was trying > to accomplish, but I needed the user to know which key was being > entered, and I completely forgot about %s. > >>* don't use a blank except. *ever*. If you really want to catch >>everything, do "except Exception:" otherwise, catch what you expect to >>be thrown in this case, "except KeyError" > > I received your email just as I left my computer, and didn't want to > type out an answer on my phone (because smartphones aren't smart > enough for that yet), and my first reaction was "why?" followed by "I > need my program to continue even if I get the errors at this part, so > why?" I soon realized that catching all errors would mean never seeing > the errors you might not foresee. I know that I could get either > ValueError or KeyError, but there could be something else somewhere > else in the code that could send an error (unlikely as it is) down > that path and with a blank except I would never actually see that > happen. Am I somewhat close to the real reason why? > Pretty much. The point here is that blank exceptions hide errors, and therefore bugs, in your code. Suppose you make a typo inside the exception, "dicionary" for example. Normally, that is not a very big deal, because python will see a name that doesn't exist, and complain. But how will it complain? By throwing a NameError! And inside that try statement, te blank except will swallow the NameError quite happily and moving along, leaving you clueless as to what actually went wrong. It's not a big deal in small programs like this, but in big ones, you won't have a clue, and a simple typo turns into a frustrating bughunt. From breamoreboy at yahoo.co.uk Fri Mar 25 17:56:25 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Fri, 25 Mar 2011 16:56:25 +0000 Subject: [Tutor] if value not in dictionary, do a? In-Reply-To: References: Message-ID: On 25/03/2011 16:11, Robert Sjoblom wrote: > I received your email just as I left my computer, and didn't want to > type out an answer on my phone (because smartphones aren't smart > enough for that yet), and my first reaction was "why?" followed by "I > need my program to continue even if I get the errors at this part, so > why?" I soon realized that catching all errors would mean never seeing > the errors you might not foresee. I know that I could get either > ValueError or KeyError, but there could be something else somewhere > else in the code that could send an error (unlikely as it is) down > that path and with a blank except I would never actually see that > happen. Am I somewhat close to the real reason why? > If you accidentally create an infinite loop you can't break out of it with Ctrl-C or whatever if you're catching all exceptions :) From ranceh at gmail.com Fri Mar 25 19:26:39 2011 From: ranceh at gmail.com (Rance Hall) Date: Fri, 25 Mar 2011 13:26:39 -0500 Subject: [Tutor] script conversion windows -> linux error Message-ID: I wrote a script on a windows box for python 3.1 after a meeting with the client for this project we agreed to port it to Linux so that I could make use of enscript and ps2pdf to email customers documents right from the script. Client uses a Centos server so I did some reading and installed python 3.2 in its own directory with a shortcut link named python3. Parallel instances of python seem to be fine. I fixed the standard line feed issues and am getting interpreter errors that I don't understand. for example: I am making use of the config module to store some database configuration details. I have this line in my code: config_version = config.get('versions','configver',0) This line fails under 3.2 Linux with the error message: TypeError: get() takes exactly 3 positional arguments (4 given) What could the 4th argument be? I only see three. This same code worked on python 3.1 under windows. What am I missing? From wprins at gmail.com Fri Mar 25 19:54:49 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 25 Mar 2011 18:54:49 +0000 Subject: [Tutor] script conversion windows -> linux error In-Reply-To: References: Message-ID: On 25 March 2011 18:26, Rance Hall wrote: > config_version = config.get('versions','configver',0) > > This line fails under 3.2 Linux with the error message: > > TypeError: get() takes exactly 3 positional arguments (4 given) > > What could the 4th argument be? I only see three. > > This same code worked on python 3.1 under windows. > > What am I missing? > OK, off the top of my head and not having checked anything, here's me thinking out loud: Recall that all methods get one extra parameter, namely the instance reference of the object that the method applies to/is being called on. Regardless, the message is telling you that you're passing one more parameter than expected. This makes me think that the version of config module that you're using is older than the one you used on Windows, and that perhaps this older version had one less parameter, which is why it's complaining about too many parameters. As I say, that's just educated guesswork/inference, I've not checked whether the above hypothesis holds water under examination... Best wishes, Walter 2) Consequently always adjust error messages, taking into account that the real number of paramers passed to a method is always one more than the "real" parameters. 3) Given that you're explicitly passing 3 parameters in the code, this means that in reality 4 is passed, your 3 + the instance reference. 4) Since the error is that only 3 is expected (e.g. 2 + instance) this implies that you're -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri Mar 25 19:56:30 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 25 Mar 2011 18:56:30 +0000 Subject: [Tutor] script conversion windows -> linux error In-Reply-To: References: Message-ID: Ugh, please excuse my tardiness and ignore the numbered items below my signature which I was intending to delete, I accidentally hit "end" before I cleaned up the post... :red faced: -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Mar 25 20:16:55 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 25 Mar 2011 15:16:55 -0400 Subject: [Tutor] script conversion windows -> linux error In-Reply-To: References: Message-ID: have you tried help(config.get) in the python interactive shell? -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Fri Mar 25 20:46:08 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 25 Mar 2011 12:46:08 -0700 Subject: [Tutor] un-buffered web output Message-ID: <4D8CF100.2040003@iandouglas.com> Hey List, In Perl, I can manipulate a special variable called $| to control buffered output, even on web pages, so I can watch something run (like CGI processes reading files or running system commands) as Perl processes it (pseudo real-time), as opposed to languages like PHP which buffers all output and draws it all in one shot. I saw this on Stack Overflow, and was curious if this is still the best practice to do the same thing in Python? sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) Thanks, Ian From ranceh at gmail.com Fri Mar 25 21:17:19 2011 From: ranceh at gmail.com (Rance Hall) Date: Fri, 25 Mar 2011 15:17:19 -0500 Subject: [Tutor] script conversion windows -> linux error In-Reply-To: References: Message-ID: On Fri, Mar 25, 2011 at 1:54 PM, Walter Prins wrote: > > > On 25 March 2011 18:26, Rance Hall wrote: >> >> config_version = ?config.get('versions','configver',0) >> >> This line fails under 3.2 Linux with the error message: >> >> TypeError: ?get() takes exactly 3 positional arguments (4 given) >> >> What could the 4th argument be? ?I only see three. >> >> This same code worked on python 3.1 under windows. >> >> What am I missing? > > OK, off the top of my head and not having checked anything, here's me > thinking out loud: > > Recall that all methods get one extra parameter, namely the instance > reference of the object that the method applies to/is being called on. > Thanks for this, I could not have recalled this, because I don't think I knew it prior to you mentioning it. > Regardless, the message is telling you that you're passing one more > parameter than expected.? This makes me think that the version of config > module that you're using is older than the one you used on Windows, and that > perhaps this older version had one less parameter, which is why it's > complaining about too many parameters. > The version of config on the linux box should be NEWER than the one I used in windows. Recall in my OP that Windows was python 3.1 and Linux is now 3.2 > As I say, that's just educated guesswork/inference, I've not checked whether > the above hypothesis holds water under examination... Likely explanation. But I don't think it holds water when compared against the configparser documentation. Interactive help documentation seems to suggest that my syntax is ok. But the compiler clearly doesnt like it. Rance PS, I just took the original zero third argument out, and now it works. I think that confirms your theory. From ramit.prasad at jpmchase.com Fri Mar 25 23:08:17 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Fri, 25 Mar 2011 18:08:17 -0400 Subject: [Tutor] Recursively flatten the list In-Reply-To: References: <4D8B02B1.70400@pobox.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF9F83A75@EMARC112VS01.exchad.jpmchase.net> " A more important problem is that it is flattening only one level. Multi-level flattening is I think not possible without using some kind of recursion." Not true, just requires more iterations to check each element. Each iteration could check if every element is a list and then unpack if it is a list. When you finally have an iteration that has no lists, you can end the loop. Not time efficient or pretty but it would certainly work without recursion. I am sure people on this list can provide a better answer than I can :) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From mahesh.mach at gmail.com Sat Mar 26 06:22:06 2011 From: mahesh.mach at gmail.com (Mahesh Narayanamurthi) Date: Sat, 26 Mar 2011 05:22:06 +0000 (UTC) Subject: [Tutor] BLAS Implementation on Python References: <4D74DD98.1020908@googlemail.com><201103080844.37036.steve@pearwood.info> <4D75B623.1020506@googlemail.com> <4D768F63.7040201@googlemail.com> Message-ID: Thank you all for your replies. I wonder why I din't get any updates from the mailing list. Now I feel I have more reasons to proceed with the implementation. Only that I don't know where to start :) Thanks, Mahesh Narayanamurthi From davea at ieee.org Sat Mar 26 12:47:40 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Mar 2011 07:47:40 -0400 Subject: [Tutor] Recursively flatten the list In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF9F83A75@EMARC112VS01.exchad.jpmchase.net> References: <4D8B02B1.70400@pobox.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2CF9F83A75@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D8DD25C.5060307@ieee.org> On 01/-10/-28163 02:59 PM, Prasad, Ramit wrote:" >A more important problem is that it is flattening only one level. >Multi-level flattening is I think not possible without using some kind >of recursion." > >Not true, just requires more iterations to check each element. Each >iteration could check if every element is a list and then unpack if it >is a list. When you finally have an iteration that has no lists, you >can end the loop. > >Not time efficient or pretty but it would certainly work without >recursion. I am sure people on this list can provide a better answer >than I can :) > > >Ramit Indeed, something like the following would suffice, in one "pass". Untested: index = 0 while index < len(mylist): if isinstance(mylist[index), list): mylist[index:index+1] = mylist[index] else index += 1 DaveA From __peter__ at web.de Sat Mar 26 14:01:07 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Mar 2011 14:01:07 +0100 Subject: [Tutor] script conversion windows -> linux error References: Message-ID: Rance Hall wrote: > On Fri, Mar 25, 2011 at 1:54 PM, Walter Prins wrote: >> >> On 25 March 2011 18:26, Rance Hall wrote: >>> config_version = config.get('versions','configver',0) >>> This line fails under 3.2 Linux with the error message: >>> TypeError: get() takes exactly 3 positional arguments (4 given) >>> What could the 4th argument be? I only see three. >>> This same code worked on python 3.1 under windows. >>> What am I missing? > Likely explanation. But I don't think it holds water when compared > against the configparser documentation. Speaking of the documentation, I think that http://docs.python.org/py3k/library/configparser.html#configparser.ConfigParser.get """ get(section, option, raw=False[, vars, fallback]) [...] Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol). """ makes it clear that instead of config.get(section, option, rawflag) # 3.1 you now have to write config.get(section, option, raw=rawflag) # 3.2 because many people erroneously assumed that the third argument was the fallback value. Peter From louis.leichtnam at sgcib.com Thu Mar 24 16:48:52 2011 From: louis.leichtnam at sgcib.com (Louis LEICHTNAM) Date: Thu, 24 Mar 2011 11:48:52 -0400 Subject: [Tutor] Fw: Fw: Fw: Parsing data from a csv file [NC] In-Reply-To: <3149743-1300981190-cardhu_decombobulator_blackberry.rim.net-322676703-@bda740.bisx.prod.on.blackberry> Message-ID: For example the line 1 in the csv file is: Barney Gumble, Breakfast, Duffbeer, 1, I could?ve gone to Harvard and I want to be able to clean it and turn it into: Barney Gumble had for beakfast 1 Duffbeer while thinking "I coul?ve gone to Harvard" so basically using in this line the column0 + "had for " + column 1 + column3 + column2 + "while thinking"+column4 and I want to be able to do this for every line, except for line0. My end game is, after I'm able to do this, I want to write an Html using python that shows those cleand lines Thanks for your help l.leichtnam at gmail.com 03/24/2011 11:39 AM Please respond to l.leichtnam at gmail.com To Louis LEICHTNAM/us/socgen at socgen cc Subject Fw: [Tutor] Fw: Fw: Parsing data from a csv file [NC] Ok, I think what you are trying is to get all data in a string list: import urllib, csv url=r"http://www.cs.columbia.edu/~joshua/teaching/cs3101/simpsons_diet.csv " simpsons=urllib.urlopen(url) reader=csv.reader(simpsons,delimiter=',',quotechar='"') list_string = [] for char,meal,ate,qty,com in reader: if char != 'Character': list_string.append("%s %s %s %s %s" % (char, meal, ate, qty, com)) print list_string Doing something like this you can format all strings as you want and keep them into a list 2011/3/24 Thanks, what I'm trying to do is extract the data from the csv file, clean it to make each line into a sentence. But for this I think I need to use a dictionary for each and enter the words of each columns in one no? Sent from my BlackBerry? on the MetroPCS Network -----Original Message----- From: Rafael Dur?n Casta?eda Sender: tutor-bounces+l.leichtnam=gmail.com at python.org Date: Thu, 24 Mar 2011 15:51:34 To: Subject: Re: [Tutor] Fw: Fw: Parsing data from a csv file [NC] _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ************************************************************************* This message and any attachments (the "message") are confidential, intended solely for the addressee(s), and may contain legally privileged information. Any unauthorised use or dissemination is prohibited. E-mails are susceptible to alteration. Neither SOCIETE GENERALE nor any of its subsidiaries or affiliates shall be liable for the message if altered, changed or falsified. ************************************************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Sat Mar 26 19:52:40 2011 From: ranceh at gmail.com (Rance Hall) Date: Sat, 26 Mar 2011 13:52:40 -0500 Subject: [Tutor] Installing python3.2 from source on Centos 5.5 Message-ID: I thought I had successfully installed python3.2 parallel to the python2.x that is required by Centos. Im getting error messages from python scripts indicating that the _ssl module is not installed. I thought that this would be installed by default, but apparently you need to have -with-ssl in the configure line? Is there anything else I should be looking for since Im going to have to reinstall python3 anyway? Rance From matthew.speltz at gmail.com Sat Mar 26 20:05:52 2011 From: matthew.speltz at gmail.com (Matthew Speltz) Date: Sat, 26 Mar 2011 14:05:52 -0500 Subject: [Tutor] Python closes out on attempt to run script Message-ID: I'm trying to teach myself python and have run across a rather annoying error. I'm not sure exactly where the fault lies, so please pardon me for posting too much information, I'm not sure what would be relevant. I'm running the Python 3.2 Windows X86-64 MSI Installer found on http://www.python.org/download It opens fine, seems to run other scripts fine, but fails when I try to run my temperature converter script. I have tried uninstalling and reinstalling Python a couple times, but it fails the exact same way. I try to leave debugging on in IDLE, but all the windows simply close and the processes exit. Any ideas on what to try next to fix this? [code] #!usr/bin/python # Filename Temp_converter.py print('''Temperature converter, by ***** *****.\n' Please enter the Temperature you wish to convert, followed by the unit (C or F).''') while True: #This forces the program to come back to the beginning if the units end up being entered incorrectly. raw = input(' > ') #prompt for temp windchill = False #used later, defining now if raw.endswith('F') or raw.endswith('f'): #Fahrenheit statement temp = int(raw.strip('Ff ')) #Returns just the numeric value unit = 'Celsius' #notes what we're converting to if temp <= 40: #if appropriate, offers to calculate wind chill windchill = True tempf = temp #sets tempf for use as the fahrenheit format for windchill global tempf temp = (5/9)*(temp-32) #Converts Temperature break #operation completed, move to close elif raw.endswith('C') or raw.endswith('c'): #Celsius statement temp = int(raw.strip('Cc ')) #Returns just the numberic value unit = 'Fahrenheit' temp = (9/5)*temp+32 #Converts Temperature if temp <= 40: #if appropriate, offers to calculate wind chill windchill = True tempf = temp #sets tempf for use as the fahrenheit format for windchill global tempf break #operation completed, move to close else: print('Incorrect format, please try again') print ('Temperature in {0} is {1} .'.format(unit, temp)) #Prints results from while loop if windchill is True: print ('For the wind chill, please enter the average wind speed in mph') raw = input(' > ') wind = int(raw.strip('mph ')) #in here to force last user input to a float number, also wind is used in windchill calulation chill = 35.74 + (.6215 * tempf) - 35.75(wind**.16) + .4275 * tempf(wind**.16) #formula for wind chill print ('The windchill for {0} degrees {1} at {2} mph is {3}'.format(temp, unit, wind, chill)) [/code] -- -Matthew Speltz From davea at ieee.org Sat Mar 26 21:14:18 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Mar 2011 16:14:18 -0400 Subject: [Tutor] Python closes out on attempt to run script In-Reply-To: References: Message-ID: <4D8E491A.2020001@ieee.org> On 01/-10/-28163 02:59 PM, Matthew Speltz wrote: > I'm trying to teach myself python and have run across a rather > annoying error. I'm not sure exactly where the fault lies, so please > pardon me for posting too much information, I'm not sure what would be > relevant. > > I'm running the Python 3.2 Windows X86-64 MSI Installer found on > http://www.python.org/download > > It opens fine, seems to run other scripts fine, but fails when I try > to run my temperature converter script. I have tried uninstalling and > reinstalling Python a couple times, but it fails the exact same way. > I try to leave debugging on in IDLE, but all the windows simply close > and the processes exit. Any ideas on what to try next to fix this? > > [code] > #!usr/bin/python > # Filename Temp_converter.py > > print('''Temperature converter, by ***** *****.\n' > Please enter the Temperature you wish to convert, followed > by the unit (C or F).''') > > while True: #This forces the program to come back to the beginning if > the units end up being entered incorrectly. > raw = input('> ') #prompt for temp > > windchill = False #used later, defining now > > if raw.endswith('F') or raw.endswith('f'): #Fahrenheit statement > temp = int(raw.strip('Ff ')) #Returns just the numeric value > unit = 'Celsius' #notes what we're converting to > > if temp<= 40: #if appropriate, offers to calculate wind chill > windchill = True > tempf = temp #sets tempf for use as the fahrenheit format > for windchill > global tempf > > temp = (5/9)*(temp-32) #Converts Temperature > > > break #operation completed, move to close > > elif raw.endswith('C') or raw.endswith('c'): #Celsius statement > temp = int(raw.strip('Cc ')) #Returns just the numberic value > unit = 'Fahrenheit' > > temp = (9/5)*temp+32 #Converts Temperature > > if temp<= 40: #if appropriate, offers to calculate wind chill > windchill = True > tempf = temp #sets tempf for use as the fahrenheit format > for windchill > global tempf > > break #operation completed, move to close > > else: > print('Incorrect format, please try again') > > print ('Temperature in {0} is {1} .'.format(unit, temp)) #Prints > results from while loop > > if windchill is True: > print ('For the wind chill, please enter the average wind speed in mph') > raw = input('> ') > > wind = int(raw.strip('mph ')) #in here to force last user input to > a float number, also wind is used in windchill calulation > > chill = 35.74 + (.6215 * tempf) - 35.75(wind**.16) + .4275 * > tempf(wind**.16) #formula for wind chill > > print ('The windchill for {0} degrees {1} at {2} mph is > {3}'.format(temp, unit, wind, chill)) > [/code] > All that information is useful, but you left out the stack trace of the error message. You say it "fails" but not how. Run it from a CMD prompt, and carefully paste the entire stack trace of the error you get. I've no experience with IDLE, and you say it closes on you anyway. So don't use it. Just run from a command prompt, and notice what it displays. DaveA From david at pythontoo.com Sat Mar 26 21:44:53 2011 From: david at pythontoo.com (David Abbott) Date: Sat, 26 Mar 2011 16:44:53 -0400 Subject: [Tutor] Python closes out on attempt to run script In-Reply-To: <4D8E491A.2020001@ieee.org> References: <4D8E491A.2020001@ieee.org> Message-ID: On Sat, Mar 26, 2011 at 4:14 PM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Matthew Speltz wrote: >> >> I'm trying to teach myself python and have run across a rather >> annoying error. ?I'm not sure exactly where the fault lies, so please >> pardon me for posting too much information, I'm not sure what would be >> relevant. Hi Matthew, I am using linux and ran your program from a terminal I had to change; #!usr/bin/python to #!/usr/bin/python also get the error; ./temp_test.py ./temp_test.py:20: SyntaxWarning: name 'tempf' is assigned to before global declaration global tempf ./temp_test.py:36: SyntaxWarning: name 'tempf' is assigned to before global declaration global tempf Temperature converter, by ***** *****. ' Please enter the Temperature you wish to convert, followed by the unit (C or F). > 50 f Temperature in Celsius is 10.0 . HTH David From km_wawa at vp.pl Sat Mar 26 22:08:43 2011 From: km_wawa at vp.pl (Mateusz K) Date: Sat, 26 Mar 2011 22:08:43 +0100 Subject: [Tutor] how to join two text files ? Message-ID: <4D8E55DB.60604@vp.pl> Hello, I have many text files, where data is delimited by space. Each file contain three colums: coordinate x, coordinate y and value for this location. I would like to join this data to get one big file which will contain columns: coordinate x, coordinate y, value1,value2,..., value_n and save it to another text file. I wrote script, but there's some stupid error (like "\n" character although I have added .rstrip() command). Coul You tell me what is most convenient way to join this data (maybe by using csv module?)? ========= Best regards, Mateusz From malcolm.newsome at gmail.com Sun Mar 27 03:48:34 2011 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Sat, 26 Mar 2011 20:48:34 -0500 Subject: [Tutor] Guessing Game Program In-Reply-To: References: <00f401cbeaa6$54049bd0$fc0dd370$@gmail.com> Message-ID: <002b01cbec21$16762af0$436280d0$@gmail.com> I noticed an error in my code...and got a cool tip on how to add an "out of range" response if the user types in a number outside of 1-100. Enjoy! Malcolm # guess.py # a simple number guessing game import random #--------------------------------------------------------------------------- ------------------- def nope_message(random_num): return "Nope! I'm smarter than you!\nI was thinking of the number: %d" % int(random_num) def right_message(retried=False): message = "That was right! I guess you ARE smarter than me" if retried: message += "... even though it took you another try!" return message def reread_input(message): return int(input("You were too %s. Type another number: " % message)) def retry(message, random_num): guess_iflow = reread_input(message) if guess_iflow == random_num: return right_message(True) else: return nope_message(random_num) #--------------------------------------------------------------------------- ------------------ def main(): print "Do you think you're smarter than me?" print "I guess we'll see!" print "I'm thinking of a number between 1 - 100. Can you guess what it is?" random_num = random.randint(1, 100) while True: guess = int(input("Type a number between 1 - 100: ")) if guess < 1 or guess > 100: print "%s is out of range try again" % guess continue break if guess == random_num: print right_message() elif guess < random_num:# user gets second chance if number is too low print retry("low", random_num) elif guess > random_num:# user gets second chance if number is too high print retry("high", random_num) else: print nope_message(random_num) if __name__ == "__main__": main() -----Original Message----- From: Donald Bedsole [mailto:drbedsole at gmail.com] Sent: Thursday, March 24, 2011 11:54 PM To: Malcolm Newsome Subject: Re: [Tutor] Guessing Game Program Hi Malcolm :-) On Fri, Mar 25, 2011 at 12:37 AM, Malcolm Newsome wrote: > Hey Don! > > I posted an eerily similar request to another python group about two > weeks ago! ?I, too, am very new to programming and the guessing game > was my first shot at writing a script from scratch! I got interested in writing a guessing game because I was trying to fix a C++ program that wouldn't compile with g++ because they were using a non-standard randomizer() function. (I really don't know C++, but I thought trying to fix the problems with someone else's program might help me to learn). I didn't make much headway in understanding how to generate random numbers in C++, but it made me curious about how to do it in Python. Python seems much easier! > > Below is my code (improved with some help from others). ?I still would > like to make some improvements to it also. ?But, perhaps there will be > some ideas in it that can help you as well! ?Looking forward to learning and growing! > > All the best! > > Malcolm Thanks for posting your code. I will look at it later (closing in on 1:00 AM here) to see what I can learn from it. Tutorials are great, but it seems looking at code makes it easier for me to learn. Thanks for taking the time to post, and I hope you're successful in your programming studies. Don From breamoreboy at yahoo.co.uk Sun Mar 27 15:44:08 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Sun, 27 Mar 2011 14:44:08 +0100 Subject: [Tutor] how to join two text files ? In-Reply-To: <4D8E55DB.60604@vp.pl> References: <4D8E55DB.60604@vp.pl> Message-ID: On 26/03/2011 21:08, Mateusz K wrote: > Hello, > > I have many text files, where data is delimited by space. > Each file contain three colums: coordinate x, coordinate y and value for > this location. > > I would like to join this data to get one big file which will contain > columns: > coordinate x, coordinate y, value1,value2,..., value_n and save it to > another text file. > > I wrote script, but there's some stupid error (like "\n" character although > I have added .rstrip() command). > > Coul You tell me what is most convenient way to join this data > (maybe by using csv module?)? > > ========= > Best regards, > Mateusz > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Maybe use split like this, 'x y 123.456\n'.split() ['x', 'y', '123.456'] then store the x and y coords in a dict with a list of values, perhaps sort according to your needs, write output to file. HTH. Mark L. From fomcl at yahoo.com Sun Mar 27 15:41:33 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 27 Mar 2011 06:41:33 -0700 (PDT) Subject: [Tutor] how to join two text files ? In-Reply-To: <4D8E55DB.60604@vp.pl> References: <4D8E55DB.60604@vp.pl> Message-ID: <146626.57899.qm@web110714.mail.gq1.yahoo.com> Hello, If the files are not too big, you could do something like: with open("/home/me/Desktop/test.csv", "wb") as w: writer = csv.writer(w) for f in glob.glob("/home/me/Desktop/files/*.txt"): rows = open(f, "rb").readlines() writer.writerows(rows) Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Mateusz K To: tutor at python.org Sent: Sat, March 26, 2011 10:08:43 PM Subject: [Tutor] how to join two text files ? Hello, I have many text files, where data is delimited by space. Each file contain three colums: coordinate x, coordinate y and value for this location. I would like to join this data to get one big file which will contain columns: coordinate x, coordinate y, value1,value2,..., value_n and save it to another text file. I wrote script, but there's some stupid error (like "\n" character although I have added .rstrip() command). Coul You tell me what is most convenient way to join this data (maybe by using csv module?)? ========= Best regards, Mateusz _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From duxchux at gmail.com Sun Mar 27 19:31:20 2011 From: duxchux at gmail.com (Chuck) Date: Sun, 27 Mar 2011 13:31:20 -0400 Subject: [Tutor] Pygame install help Message-ID: Does anyone have familiarity with installing pygame? It seems simple and straight forward enough, then why do I get the following from IDLE? This is the 3.1 Windows pygame .msi install... Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import pygame Traceback (most recent call last): File "", line 1, in import pygame File "C:\Python32\lib\site- packages\pygame\__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: The specified module could not be found. >>> -- ========================== Chuck DuxChux at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sun Mar 27 21:57:24 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 27 Mar 2011 12:57:24 -0700 (PDT) Subject: [Tutor] how to optimize this code? Message-ID: <307628.7181.qm@web110713.mail.gq1.yahoo.com> Hello, I made a program that reads spss data files. I ran cProfile to see if I can optimize things (see #1 below). It seems that the function getValueNumeric is a pain spot (see #2 below). This function calls a C function in a dll for each numerical cell value. On the basis of this limited amount of info, what could I do to further optimize the code? I heard about psyco, but I didn't think such tricks would be necessary as the function spssGetValueNumeric is is implemented in C already (which should be fast). 1 ## cProfile output 50018706 function calls in 521.261 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 521.261 521.261 :1() 247 0.001 0.000 0.001 0.000 :1(fileno) 1 0.275 0.275 0.436 0.436 SPSSio12.py:102(loadSavFile) 1 0.000 0.000 0.000 0.000 SPSSio12.py:125(getNumberofVariables) 200 0.002 0.000 0.004 0.000 SPSSio12.py:132(getVarNameAndType) 1 0.001 0.001 0.005 0.005 SPSSio12.py:140(getVarInfo) 1 0.000 0.000 0.000 0.000 SPSSio12.py:150(getNumberofCases) 100 0.002 0.000 0.002 0.000 SPSSio12.py:157(getVarHandle) 10000000 96.090 0.000 103.074 0.000 SPSSio12.py:177(getValueNumeric) 100 0.002 0.000 0.002 0.000 SPSSio12.py:206(getVarPrintFormat) 10000000 57.937 0.000 57.937 0.000 SPSSio12.py:224(formatValue) 1 0.007 0.007 1.403 1.403 SPSSio12.py:260(getFileReport) 10000002 313.049 0.000 486.674 0.000 SPSSio12.py:270(savReader) 1 34.181 34.181 521.261 521.261 SPSSio12.py:349(main) ## most time consuming function def getValueNumeric(fh, spssio, varHandle): numValue = ctypes.c_double() numValuePtr = ctypes.byref(numValue) retcode = spssio.spssGetValueNumeric(fh, ctypes.c_double(varHandle), numValuePtr) return retcode, numValue.value Thanks in advance for your thoughts! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Mar 28 07:43:16 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 28 Mar 2011 07:43:16 +0200 Subject: [Tutor] how to optimize this code? In-Reply-To: <307628.7181.qm@web110713.mail.gq1.yahoo.com> References: <307628.7181.qm@web110713.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam, 27.03.2011 21:57: > I made a program that reads spss data files. I ran cProfile to see if I can > optimize things (see #1 below). First thing to note here: sort the output by "time", which refers to the "tottime" column. That will make it more obvious where most time is really spent. > It seems that the function getValueNumeric is a pain spot (see #2 > below). This function calls a C function in a dll for each numerical > cell value. On the basis of this limited amount of info, what could I do > to further optimize the code? I heard about psyco, but I didn't think > such tricks would be necessary as the function spssGetValueNumeric is is > implemented in C already (which should be fast). The problem is that you are using ctypes to call it. It's useful for simple things, but it's not usable for performance critical things, such as calling a C function ten million times in your example. Since you're saying "dll", is this under Windows? It's a bit more tricky to set up Cython on that platform than on pretty much all others, since you additionally need to install a C compiler, but if you want to go that route, it will reward you with a much faster way to call your C code, and will allow you to also speed up the code that does the calls. That being said, see below. > ## most time consuming function > > def getValueNumeric(fh, spssio, varHandle): > numValue = ctypes.c_double() > numValuePtr = ctypes.byref(numValue) > retcode = spssio.spssGetValueNumeric(fh, > ctypes.c_double(varHandle), > numValuePtr) You may still be able to make this code a tad faster, by avoiding the function name lookups on both the ctypes module and "spssio", and by using a constant pointer for numValue (is you're not using threads). That may not make enough of a difference, but it should at least be a little faster. Stefan From emafrs at gmail.com Mon Mar 28 10:27:13 2011 From: emafrs at gmail.com (ema francis) Date: Mon, 28 Mar 2011 13:57:13 +0530 Subject: [Tutor] server used in python Message-ID: I am learnning python for 3 months from now. I wanted to know how and what *server* is used in python web development?Looking for your help .... -------------- next part -------------- An HTML attachment was scrubbed... URL: From mast.ratna at gmail.com Mon Mar 28 10:43:52 2011 From: mast.ratna at gmail.com (Ratna Banjara) Date: Mon, 28 Mar 2011 14:28:52 +0545 Subject: [Tutor] How to read remote text file? Message-ID: Hey all, I need to read text file from remote server and generate excel file from local computer using python. Is it possible? If so how? -- Regards, Ratna P Banjara -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Mar 28 12:53:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2011 21:53:54 +1100 Subject: [Tutor] How to read remote text file? In-Reply-To: References: Message-ID: <4D9068C2.20304@pearwood.info> Ratna Banjara wrote: > Hey all, > > I need to read text file from remote server and generate excel file from > local computer using python. Is it possible? If so how? Possibly. Do you have access to the server? If so, you have to download the file using whatever protocol the server supports: http, https, ftp, gopher, something else. Once you have copied the file, you can read the file and write it to a CSV file using the csv module. Excel can read CSV files. If you need an actual .xls file, this is a secret, proprietary format. There are some projects that have tried to reverse-engineer the format, like the xlrd package. Google for "excel python" and you will find about 13 million hits. -- Steven From steve at pearwood.info Mon Mar 28 12:55:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Mar 2011 21:55:16 +1100 Subject: [Tutor] server used in python In-Reply-To: References: Message-ID: <4D906914.9010302@pearwood.info> ema francis wrote: > I am learnning python for 3 months from now. I wanted to know how and what > *server* is used in python web development?Looking for your help .... There are several. I suggest you start with CherryPy: www.cherrypy.org/ -- Steven From wprins at gmail.com Mon Mar 28 13:11:16 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 28 Mar 2011 12:11:16 +0100 Subject: [Tutor] How to read remote text file? In-Reply-To: <4D9068C2.20304@pearwood.info> References: <4D9068C2.20304@pearwood.info> Message-ID: Hi On 28 March 2011 11:53, Steven D'Aprano wrote: > There are some projects that have tried to reverse-engineer the format, > like the xlrd package. > Yes, just to add, xlrd is the "reader" module, the Excel "writer" is xlwt, available here: http://pypi.python.org/pypi/xlwt Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From james at jamesthornton.com Mon Mar 28 13:29:47 2011 From: james at jamesthornton.com (James Thornton) Date: Mon, 28 Mar 2011 06:29:47 -0500 Subject: [Tutor] server used in python In-Reply-To: References: Message-ID: On Mon, Mar 28, 2011 at 3:27 AM, ema francis wrote: > I am learnning python for? 3 months from now. I wanted to know how and what > server is used in python web development?Looking for your help .... When you're developing a Python Web application, most people use a development server that automatically detects when you update a file and reloads it for you so you don't have to restart the Web server each time. When you're ready to take your site live, you have several options. If you design your Web application as a WSGI app (http://www.wsgi.org/wsgi/), you can hook into any WSGI server. Many people use Apache with mod_wsgi, but you can also proxy back to your Web app. Look at using the Flask Web Framework (http://flask.pocoo.org/docs/). Flask is a modern, lightweight, and well-documented Python Web framework so you won't have to spend much time learning it or fighting with it so you won't find yourself asking, "Will I be able to do what I want in the framework without hacking it?" Flask let's you program in Python rather than writing to the framework like you typically have to in larger, opinionated framework's like Django and Rails. It comes with a development server, and its documentation (http://flask.pocoo.org/docs/) explains several different types of deployment options for when you're ready to go live (http://flask.pocoo.org/docs/deploying/). - James -- Latest Blog: http://jamesthornton.com/blog/how-to-get-to-genius From susana.delgado_s at utzmg.edu.mx Mon Mar 28 17:12:05 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 28 Mar 2011 09:12:05 -0600 Subject: [Tutor] Write new line(enter) in txt Message-ID: Hello list!! This is a very simple question!! I want to write some lines in a txt file, but my output looks like this: No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo existe el archivo C:\?ndice_raster.dbf I need it to look like this: No existe el archivo C:\?ndice.dbf No existe el archivo C:\?ndice_dwg.dbf No existe el archivo C:\?ndice_raster.dbf The code I wrote is: log = open ('errors.txt','wb') shp = 'Error al abrir el archivo' +filepath log.write(shp+"\n") n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' dbf = n[0]+'.dbf' if os.path.exists(shx): print 'El archivo ' +shx +' existe' else: log.write('No existe el archivo ' +shx+"\n") if os.path.exists(dbf): print 'El archivo ' +dbf +' existe' else: log.write('No existe el archivo ' +dbf+"\n") log.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Mar 28 17:21:39 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Mar 2011 11:21:39 -0400 Subject: [Tutor] Write new line(enter) in txt In-Reply-To: References: Message-ID: On Mon, Mar 28, 2011 at 11:12 AM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Hello list!! > > This is a very simple question!! I want to write some lines in a txt file, > but my output looks like this: > No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo > existe el archivo C:\?ndice_raster.dbf > I need it to look like this: > No existe el archivo C:\?ndice.dbf > No existe el archivo C:\?ndice_dwg.dbf > No existe el archivo C:\?ndice_raster.dbf > > The code I wrote is: > log = open ('errors.txt','wb') > shp = 'Error al abrir el archivo' +filepath > log.write(shp+"\n") > n = os.path.splitext(filepath) > p = n[0]+'.prj' > shx = n[0]+'.shx' > dbf = n[0]+'.dbf' > if os.path.exists(shx): > print 'El archivo ' +shx +' existe' > else: > log.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print 'El archivo ' +dbf +' existe' > else: > log.write('No existe el archivo ' +dbf+"\n") > log.close() > > > Windows systems I believe need cr/lf for end of line character. You should first try opening your file in text mode, not binary. Then your \n will be translated into whatever end of line sequence your operating system requires. http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Mar 28 17:27:25 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 28 Mar 2011 10:27:25 -0500 Subject: [Tutor] Pygame install help In-Reply-To: References: Message-ID: On Sun, Mar 27, 2011 at 12:31 PM, Chuck wrote: > Does anyone have familiarity with installing pygame? It seems simple and > straight forward enough, then why do I get the following from IDLE? This is > the 3.1 Windows pygame .msi install... > > Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] > on win32 > Type "copyright", "credits" or "license()" for more information. > >>> import pygame > Traceback (most recent call last): > File "", line 1, in > import pygame > File "C:\Python32\lib\site- > packages\pygame\__init__.py", line 95, in > from pygame.base import * > ImportError: DLL load failed: The specified module could not be found. > >>> > Pygame support for Python 3 is a bit spotty (AFAIK). It will probably be easier using an earlier version of Python when working with Pygame. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Mon Mar 28 17:28:18 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 28 Mar 2011 09:28:18 -0600 Subject: [Tutor] Write new line(enter) in txt In-Reply-To: References: Message-ID: Ok Flyyn! Thank you for answered my question. I think I didn't explain what I need. The printing statement is used to print a message to the Windows console, then the other line written in the else statement is: log.write('No existe el archivo ' +shx+"\n") This is the part I'm struggling with, I don't know how to add the "new line" to the txt 2011/3/28 Flynn, Stephen (L & P - IT) > You don't "print" a newline when you print each line of the file > contents... > > > print 'El archivo ' +shx +' existe' > > > > > > You need to add a newline: > > print 'El archivo ' +shx +' existe' + '\n' > > > > > ________________________________________ > From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto: > tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Susana > Iraiis Delgado Rodriguez > Sent: Monday, March 28, 2011 4:12 PM > To: tutor at python.org > Subject: [Tutor] Write new line(enter) in txt > > Hello list!! > > This is a very simple question!! I want to write some lines in a txt file, > but my output looks like this: > No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo > existe el archivo C:\?ndice_raster.dbf > I need it to look like this: > No existe el archivo C:\?ndice.dbf > No existe el archivo C:\?ndice_dwg.dbf > No existe el archivo C:\?ndice_raster.dbf > > The code I wrote is: > log = open ('errors.txt','wb') > shp = 'Error al abrir el archivo' +filepath > log.write(shp+"\n") > n = os.path.splitext(filepath) > p = n[0]+'.prj' > shx = n[0]+'.shx' > dbf = n[0]+'.dbf' > if os.path.exists(shx): > print 'El archivo ' +shx +' existe' > else: > log.write('No existe el archivo ' +shx+"\n") > if os.path.exists(dbf): > print 'El archivo ' +dbf +' existe' > else: > log.write('No existe el archivo ' +dbf+"\n") > log.close() > > > This email has been scanned for all viruses by the MessageLabs SkyScan > service. > > This email and any attachment to it are confidential. Unless you are the > intended recipient, you may not use, copy or disclose either the message or > any information contained in the message. If you are not the intended > recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, > unless otherwise stated. All copyright in any Capita material in this email > is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored > for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting > from the receipt, use or transmission of this email to the fullest extent > permitted by law. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Mar 28 17:43:25 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Mar 2011 11:43:25 -0400 Subject: [Tutor] Write new line(enter) in txt In-Reply-To: References: Message-ID: On Mon, Mar 28, 2011 at 11:28 AM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Ok Flyyn! > Thank you for answered my question. I think I didn't explain what I need. > The printing statement is used to print a message to the Windows console, > then the other line written in the else statement is: > > log.write('No existe el archivo ' +shx+"\n") > This is the part I'm struggling with, I don't know how to add the "new > line" to the txt > > 2011/3/28 Flynn, Stephen (L & P - IT) > >> You don't "print" a newline when you print each line of the file >> contents... >> >> >> >> print 'El archivo ' +shx +' existe' >> >> >> >> >> >> You need to add a newline: >> >> print 'El archivo ' +shx +' existe' + '\n' >> >> >> >> >> ________________________________________ >> From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto: >> tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Susana >> Iraiis Delgado Rodriguez >> Sent: Monday, March 28, 2011 4:12 PM >> To: tutor at python.org >> Subject: [Tutor] Write new line(enter) in txt >> >> >> Hello list!! >> >> This is a very simple question!! I want to write some lines in a txt file, >> but my output looks like this: >> No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo >> existe el archivo C:\?ndice_raster.dbf >> I need it to look like this: >> No existe el archivo C:\?ndice.dbf >> No existe el archivo C:\?ndice_dwg.dbf >> No existe el archivo C:\?ndice_raster.dbf >> >> The code I wrote is: >> log = open ('errors.txt','wb') >> > Change the above line to log = open('errors.txt, 'w') You are opening your log file in binary mode, so your operating system doesn't convert your '\n' to what it needs for new line > shp = 'Error al abrir el archivo' +filepath >> log.write(shp+"\n") >> n = os.path.splitext(filepath) >> p = n[0]+'.prj' >> shx = n[0]+'.shx' >> dbf = n[0]+'.dbf' >> if os.path.exists(shx): >> print 'El archivo ' +shx +' existe' >> else: >> log.write('No existe el archivo ' +shx+"\n") >> if os.path.exists(dbf): >> print 'El archivo ' +dbf +' existe' >> else: >> log.write('No existe el archivo ' +dbf+"\n") >> log.close() >> >> >> This email has been scanned for all viruses by the MessageLabs SkyScan >> service. >> >> This email and any attachment to it are confidential. Unless you are the >> intended recipient, you may not use, copy or disclose either the message or >> any information contained in the message. If you are not the intended >> recipient, you should delete this email and notify the sender immediately. >> >> Any views or opinions expressed in this email are those of the sender >> only, unless otherwise stated. All copyright in any Capita material in this >> email is reserved. >> >> All emails, incoming and outgoing, may be recorded by Capita and monitored >> for legitimate business purposes. >> >> Capita exclude all liability for any loss or damage arising or resulting >> from the receipt, use or transmission of this email to the fullest extent >> permitted by law. >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From Steve.Flynn at capita.co.uk Mon Mar 28 17:38:15 2011 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Mon, 28 Mar 2011 16:38:15 +0100 Subject: [Tutor] Write new line(enter) in txt In-Reply-To: References: Message-ID: Ahhh - my mistake. You open your file in binary mode - open it in text mode instead and the '\n' will be translated to '\n\r' (carriage return and line feed). I do most of my coding on AIX / Unix where only the Newline is required, so that was the first thing I looked for... you're on Windows where an end of line is marked via a CR + LF. S. ________________________________________ From: Susana Iraiis Delgado Rodriguez [mailto:susana.delgado_s at utzmg.edu.mx] Sent: Monday, March 28, 2011 4:28 PM To: Flynn, Stephen (L & P - IT) Cc: tutor at python.org Subject: Re: [Tutor] Write new line(enter) in txt Ok Flyyn! Thank you for answered my question. I think I didn't explain what I need. The printing statement is used to print a message to? the Windows console, then the other line written in the else statement is: log.write('No existe el archivo ' +shx+"\n") This is the part I'm struggling with, I don't know how to add the "new line" to the txt 2011/3/28 Flynn, Stephen (L & P - IT) You don't "print" a newline when you print each line of the file contents... print 'El archivo ' +shx +' existe' You need to add a newline: print 'El archivo ' +shx +' existe' + '\n' ________________________________________ From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto:tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Susana Iraiis Delgado Rodriguez Sent: Monday, March 28, 2011 4:12 PM To: tutor at python.org Subject: [Tutor] Write new line(enter) in txt Hello list!! This is a very simple question!! I want to write some lines in a txt file, but my output looks like this: No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo existe el archivo C:\?ndice_raster.dbf I need it to look like this: No existe el archivo C:\?ndice.dbf No existe el archivo C:\?ndice_dwg.dbf No existe el archivo C:\?ndice_raster.dbf The code I wrote is: log = open ('errors.txt','wb') shp = 'Error al abrir el archivo' +filepath log.write(shp+"\n") n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' dbf = n[0]+'.dbf' if os.path.exists(shx): ??????????????????????? print 'El archivo ' +shx +' existe' ??????????????? else: ??????????????????????? log.write('No existe el archivo ' +shx+"\n") ??????????????? if os.path.exists(dbf): ??????????????????????? print 'El archivo ' +dbf +' existe' ??????????????? else: ??????????????????????? log.write('No existe el archivo ' +dbf+"\n") log.close() This email has been scanned for all viruses by the MessageLabs SkyScan service. This email and any attachment to it are confidential. ?Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. ?All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. This email has been scanned for all viruses by the MessageLabs SkyScan service. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From tommy.kaas at kaasogmulvad.dk Mon Mar 28 17:21:35 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Mon, 28 Mar 2011 17:21:35 +0200 Subject: [Tutor] Write new line(enter) in txt In-Reply-To: References: Message-ID: <004201cbed5b$d3d17ec0$7b747c40$@kaasogmulvad.dk> Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org [mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] P? vegne af Susana Iraiis Delgado Rodriguez Sendt: 28. marts 2011 17:12 Til: tutor at python.org Emne: [Tutor] Write new line(enter) in txt Hello list!! This is a very simple question!! I want to write some lines in a txt file, but my output looks like this: No existe el archivo C:\?ndice.dbfNo existe el archivo C:\?ndice_dwg.dbfNo existe el archivo C:\?ndice_raster.dbf I need it to look like this: No existe el archivo C:\?ndice.dbf No existe el archivo C:\?ndice_dwg.dbf No existe el archivo C:\?ndice_raster.dbf else: log.write('No existe el archivo ' +shx+"\n") if os.path.exists(dbf): print 'El archivo ' +dbf +' existe' else: log.write('No existe el archivo ' +dbf+"\n") log.close() Try: ?\r\n? Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Ikke-navngivet vedh?ftet fil 00058.txt URL: From susana.delgado_s at utzmg.edu.mx Mon Mar 28 18:02:50 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 28 Mar 2011 10:02:50 -0600 Subject: [Tutor] Tutor Digest, Vol 85, Issue 103 In-Reply-To: References: Message-ID: Thank you to everyone! I changed the txt mode for my system, from 'wb' to 'w' and finally I got what I need. Than you! 2011/3/28 > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Pygame install help (Wayne Werner) > 2. Re: Write new line(enter) in txt (Susana Iraiis Delgado Rodriguez) > 3. Re: Write new line(enter) in txt (Joel Goldstick) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 28 Mar 2011 10:27:25 -0500 > From: Wayne Werner > To: Chuck > Cc: tutor at python.org > Subject: Re: [Tutor] Pygame install help > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On Sun, Mar 27, 2011 at 12:31 PM, Chuck wrote: > > > Does anyone have familiarity with installing pygame? It seems simple and > > straight forward enough, then why do I get the following from IDLE? This > is > > the 3.1 Windows pygame .msi install... > > > > Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] > > on win32 > > Type "copyright", "credits" or "license()" for more information. > > >>> import pygame > > Traceback (most recent call last): > > File "", line 1, in > > import pygame > > File "C:\Python32\lib\site- > > packages\pygame\__init__.py", line 95, in > > from pygame.base import * > > ImportError: DLL load failed: The specified module could not be found. > > >>> > > > > Pygame support for Python 3 is a bit spotty (AFAIK). It will probably be > easier using an earlier version of Python when working with Pygame. > > HTH, > Wayne > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110328/4d663213/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 28 Mar 2011 09:28:18 -0600 > From: Susana Iraiis Delgado Rodriguez > To: "Flynn, Stephen (L & P - IT)" > Cc: tutor at python.org > Subject: Re: [Tutor] Write new line(enter) in txt > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Ok Flyyn! > Thank you for answered my question. I think I didn't explain what I need. > The printing statement is used to print a message to the Windows console, > then the other line written in the else statement is: > log.write('No existe el archivo ' +shx+"\n") > This is the part I'm struggling with, I don't know how to add the "new > line" > to the txt > > 2011/3/28 Flynn, Stephen (L & P - IT) > > > You don't "print" a newline when you print each line of the file > > contents... > > > > > > print 'El archivo ' +shx +' existe' > > > > > > > > > > > > You need to add a newline: > > > > print 'El archivo ' +shx +' existe' + '\n' > > > > > > > > > > ________________________________________ > > From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto: > > tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Susana > > Iraiis Delgado Rodriguez > > Sent: Monday, March 28, 2011 4:12 PM > > To: tutor at python.org > > Subject: [Tutor] Write new line(enter) in txt > > > > Hello list!! > > > > This is a very simple question!! I want to write some lines in a txt > file, > > but my output looks like this: > > No existe el archivo C:\?ndice.dbfNo existe el archivo > C:\?ndice_dwg.dbfNo > > existe el archivo C:\?ndice_raster.dbf > > I need it to look like this: > > No existe el archivo C:\?ndice.dbf > > No existe el archivo C:\?ndice_dwg.dbf > > No existe el archivo C:\?ndice_raster.dbf > > > > The code I wrote is: > > log = open ('errors.txt','wb') > > shp = 'Error al abrir el archivo' +filepath > > log.write(shp+"\n") > > n = os.path.splitext(filepath) > > p = n[0]+'.prj' > > shx = n[0]+'.shx' > > dbf = n[0]+'.dbf' > > if os.path.exists(shx): > > print 'El archivo ' +shx +' existe' > > else: > > log.write('No existe el archivo ' +shx+"\n") > > if os.path.exists(dbf): > > print 'El archivo ' +dbf +' existe' > > else: > > log.write('No existe el archivo ' +dbf+"\n") > > log.close() > > > > > > This email has been scanned for all viruses by the MessageLabs SkyScan > > service. > > > > This email and any attachment to it are confidential. Unless you are the > > intended recipient, you may not use, copy or disclose either the message > or > > any information contained in the message. If you are not the intended > > recipient, you should delete this email and notify the sender > immediately. > > > > Any views or opinions expressed in this email are those of the sender > only, > > unless otherwise stated. All copyright in any Capita material in this > email > > is reserved. > > > > All emails, incoming and outgoing, may be recorded by Capita and > monitored > > for legitimate business purposes. > > > > Capita exclude all liability for any loss or damage arising or resulting > > from the receipt, use or transmission of this email to the fullest extent > > permitted by law. > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110328/bc0814df/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Mon, 28 Mar 2011 11:43:25 -0400 > From: Joel Goldstick > To: Susana Iraiis Delgado Rodriguez > Cc: tutor at python.org > Subject: Re: [Tutor] Write new line(enter) in txt > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > On Mon, Mar 28, 2011 at 11:28 AM, Susana Iraiis Delgado Rodriguez < > susana.delgado_s at utzmg.edu.mx> wrote: > > > Ok Flyyn! > > Thank you for answered my question. I think I didn't explain what I need. > > The printing statement is used to print a message to the Windows > console, > > then the other line written in the else statement is: > > > > log.write('No existe el archivo ' +shx+"\n") > > This is the part I'm struggling with, I don't know how to add the "new > > line" to the txt > > > > 2011/3/28 Flynn, Stephen (L & P - IT) > > > >> You don't "print" a newline when you print each line of the file > >> contents... > >> > >> > >> > >> print 'El archivo ' +shx +' existe' > >> > >> > >> > >> > >> > >> You need to add a newline: > >> > >> print 'El archivo ' +shx +' existe' + '\n' > >> > >> > >> > >> > >> ________________________________________ > >> From: tutor-bounces+steve.flynn=capita.co.uk at python.org [mailto: > >> tutor-bounces+steve.flynn=capita.co.uk at python.org] On Behalf Of Susana > >> Iraiis Delgado Rodriguez > >> Sent: Monday, March 28, 2011 4:12 PM > >> To: tutor at python.org > >> Subject: [Tutor] Write new line(enter) in txt > >> > >> > >> Hello list!! > >> > >> This is a very simple question!! I want to write some lines in a txt > file, > >> but my output looks like this: > >> No existe el archivo C:\?ndice.dbfNo existe el archivo > C:\?ndice_dwg.dbfNo > >> existe el archivo C:\?ndice_raster.dbf > >> I need it to look like this: > >> No existe el archivo C:\?ndice.dbf > >> No existe el archivo C:\?ndice_dwg.dbf > >> No existe el archivo C:\?ndice_raster.dbf > >> > >> The code I wrote is: > >> log = open ('errors.txt','wb') > >> > > > > Change the above line to > log = open('errors.txt, 'w') > > You are opening your log file in binary mode, so your operating system > doesn't convert your '\n' to what it needs for new line > > > > shp = 'Error al abrir el archivo' +filepath > >> log.write(shp+"\n") > >> n = os.path.splitext(filepath) > >> p = n[0]+'.prj' > >> shx = n[0]+'.shx' > >> dbf = n[0]+'.dbf' > >> if os.path.exists(shx): > >> print 'El archivo ' +shx +' existe' > >> else: > >> log.write('No existe el archivo ' +shx+"\n") > >> if os.path.exists(dbf): > >> print 'El archivo ' +dbf +' existe' > >> else: > >> log.write('No existe el archivo ' +dbf+"\n") > >> log.close() > >> > >> > >> This email has been scanned for all viruses by the MessageLabs SkyScan > >> service. > >> > >> This email and any attachment to it are confidential. Unless you are > the > >> intended recipient, you may not use, copy or disclose either the message > or > >> any information contained in the message. If you are not the intended > >> recipient, you should delete this email and notify the sender > immediately. > >> > >> Any views or opinions expressed in this email are those of the sender > >> only, unless otherwise stated. All copyright in any Capita material in > this > >> email is reserved. > >> > >> All emails, incoming and outgoing, may be recorded by Capita and > monitored > >> for legitimate business purposes. > >> > >> Capita exclude all liability for any loss or damage arising or resulting > >> from the receipt, use or transmission of this email to the fullest > extent > >> permitted by law. > >> > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Joel Goldstick > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20110328/9812ccbb/attachment.html > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 85, Issue 103 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From markrivet at gsoftcon.com Mon Mar 28 19:04:59 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Mon, 28 Mar 2011 13:04:59 -0400 (EDT) Subject: [Tutor] Replying Message-ID: <1301331899.32219005@192.168.4.58> When replying to the mailing list, does everyone just hit the reply button in your email program. Because that sends the email directly to your email. Also everyone is cc'ng the mailing list; is that the exceptable way to reply so everyone in the list gets the replies? Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From swiftone at swiftone.org Mon Mar 28 19:22:38 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 28 Mar 2011 13:22:38 -0400 Subject: [Tutor] Replying In-Reply-To: <1301331899.32219005@192.168.4.58> References: <1301331899.32219005@192.168.4.58> Message-ID: On Mon, Mar 28, 2011 at 1:04 PM, wrote: > When replying to the mailing list, does everyone just hit the reply button in your email program. Because that sends the email directly to your email. Also everyone is cc'ng the mailing list; is that the exceptable way to reply so everyone in the list gets the replies? Fully functional email clients (generally only found on Linux/BSD) have a "reply to Group" function that works as intended. Most email clients lack such ability, so the process on this list is to use "Reply to All", which CC's the list as you describe. How email lists function is an oft-debated topic. Many (most?) lists will make the "reply-to" header in the email reflect the list address (instead of the original sender), so a simple "Reply" will go to the list. However, the "Reply To" header is not intended by the email RFC to function this way. It ends up in a battle of "follow the spec as intended" vs "follow the generally expected results". You can read much on this debate by googling for "Reply To munging harmful" and "Reply To munging useful", but further discussion is definitely outside the scope of this list. Technical mailing lists and/or long-existing mailing lists will often take stances on subjects such as reply to, top-quoting, quote trimming, signatures, plain text vs HTML, etc because many of those standards came about from a time when communicating detailed and in-depth topics over email to a large group was pretty much the only way to communicate if not in person. Today's web-forum lol outlook-trained populace is generally ignorant of such reasonings, but trust me, the rules have a reason beyond techie elitism for existing. (*steps off soapbox*). You can google "Eternal September" for more on that general topic. TL;DR Version: Yes, that's perfectly acceptable. *bites tongue to resist going off on a rant about TL;DR* Hope that was helpful! -- Brett Ritter / SwiftOne swiftone at swiftone.org From kb1pkl at aim.com Mon Mar 28 19:18:55 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 28 Mar 2011 13:18:55 -0400 Subject: [Tutor] Replying In-Reply-To: <1301331899.32219005@192.168.4.58> References: <1301331899.32219005@192.168.4.58> Message-ID: <4D90C2FF.5010801@aim.com> On 03/28/2011 01:04 PM, markrivet at gsoftcon.com wrote: > When replying to the mailing list, does everyone just hit the reply button in your email program. Because that sends the email directly to your email. Also everyone is cc'ng the mailing list; is that the exceptable way to reply so everyone in the list gets the replies? > Thunderbird has a "reply list" button that I use. From susana.delgado_s at utzmg.edu.mx Mon Mar 28 19:24:22 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Mon, 28 Mar 2011 11:24:22 -0600 Subject: [Tutor] Read arguments from command line Message-ID: Hello everyone! I want to run a python script which reads arguments from command line. I searched in web and the module sys.argv came up. But I don't understand how it works. I need to know how to pass arguments from command line and make the python script works from MS-DOS instead of run my program from the python console. Is there any documentation? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Mar 28 19:52:00 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Mon, 28 Mar 2011 18:52:00 +0100 Subject: [Tutor] Read arguments from command line In-Reply-To: References: Message-ID: On 28/03/2011 18:24, Susana Iraiis Delgado Rodriguez wrote: > Hello everyone! > > I want to run a python script which reads arguments from command line. I > searched in web and the module sys.argv came up. But I don't understand > how it works. I need to know how to pass arguments from command line and > make the python script works from MS-DOS instead of run my program from > the python console. > > Is there any documentation? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor See this from a well known Python tutorial http://www.faqs.org/docs/diveintopython/kgp_commandline.html From joel.goldstick at gmail.com Mon Mar 28 19:51:34 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 28 Mar 2011 13:51:34 -0400 Subject: [Tutor] Read arguments from command line In-Reply-To: References: Message-ID: On Mon, Mar 28, 2011 at 1:24 PM, Susana Iraiis Delgado Rodriguez < susana.delgado_s at utzmg.edu.mx> wrote: > Hello everyone! > > I want to run a python script which reads arguments from command line. I > searched in web and the module sys.argv came up. But I don't understand how > it works. I need to know how to pass arguments from command line and make > the python script works from MS-DOS instead of run my program from the > python console. > > Is there any documentation? > > if you have the following command: python myprogram.py first second third sys.argv[0] will be "myprogram.py" sys.argv[1] will be "first" sys.argv[2] will be "second" and so forth If you need more complicated command line parsing you should look into argparse _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Mar 28 21:37:53 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 28 Mar 2011 15:37:53 -0400 Subject: [Tutor] Pygame install help In-Reply-To: References: Message-ID: On Sun, Mar 27, 2011 at 1:31 PM, Chuck wrote: > Does anyone have familiarity with installing pygame? It seems simple and > straight forward enough, then why do I get the following from IDLE? This is > the 3.1 Windows pygame .msi install... You're using pygame (probably pygame 1.9.1) built for python 3.1, but... > Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on ...you're using python 3.2. Don't do that. Your versions need to match. Since I don't see a version of pygame built for python 3.2 on windows, you'll need to either go back to python 3.1, or wait for someone to build pygame for 3.2. You might be able to build it yourself, but I don't know how convoluted that is. -- Jerry From fomcl at yahoo.com Mon Mar 28 21:37:32 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 28 Mar 2011 12:37:32 -0700 (PDT) Subject: [Tutor] how to optimize this code? In-Reply-To: References: <307628.7181.qm@web110713.mail.gq1.yahoo.com> Message-ID: <647452.65323.qm@web110703.mail.gq1.yahoo.com> Hi Stefan, Thanks for your advice. I seriously thought ctypes was the module to use. That was before I found out the evaluating all 10**9 values of my test data set is glacially slow (several hours). You're right, the dll implies the program is running on windows. I've also been trying to make it work under Linux but I wanted to get the basic algorithm right first. Also, it was quite a PIA to get all the dependencies of the (old) .so files. Your speed tip reminded me of: http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... Does this mean that "from ctypes import *" gives slightly faster code than "import ctypes"? If so: wow! I've always avoided the first notation like the plague. What do you mean with '... using a constant pointer for numValue' ? Is this the byref/pointer object distinction? I replaced a the pointer object with a byref object, which reduced processing time by about 10 %. Cython might be interesting as a hobby project, but I'm affraid I'll never get the ICT droids in my office to install that. Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Stefan Behnel To: tutor at python.org Sent: Mon, March 28, 2011 7:43:16 AM Subject: Re: [Tutor] how to optimize this code? Albert-Jan Roskam, 27.03.2011 21:57: > I made a program that reads spss data files. I ran cProfile to see if I can > optimize things (see #1 below). First thing to note here: sort the output by "time", which refers to the "tottime" column. That will make it more obvious where most time is really spent. > It seems that the function getValueNumeric is a pain spot (see #2 > below). This function calls a C function in a dll for each numerical > cell value. On the basis of this limited amount of info, what could I do > to further optimize the code? I heard about psyco, but I didn't think > such tricks would be necessary as the function spssGetValueNumeric is is > implemented in C already (which should be fast). The problem is that you are using ctypes to call it. It's useful for simple things, but it's not usable for performance critical things, such as calling a C function ten million times in your example. Since you're saying "dll", is this under Windows? It's a bit more tricky to set up Cython on that platform than on pretty much all others, since you additionally need to install a C compiler, but if you want to go that route, it will reward you with a much faster way to call your C code, and will allow you to also speed up the code that does the calls. That being said, see below. > ## most time consuming function > > def getValueNumeric(fh, spssio, varHandle): > numValue = ctypes.c_double() > numValuePtr = ctypes.byref(numValue) > retcode = spssio.spssGetValueNumeric(fh, > ctypes.c_double(varHandle), > numValuePtr) You may still be able to make this code a tad faster, by avoiding the function name lookups on both the ctypes module and "spssio", and by using a constant pointer for numValue (is you're not using threads). That may not make enough of a difference, but it should at least be a little faster. Stefan _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Mar 28 22:07:57 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 28 Mar 2011 13:07:57 -0700 Subject: [Tutor] how to optimize this code? In-Reply-To: <647452.65323.qm@web110703.mail.gq1.yahoo.com> References: <307628.7181.qm@web110713.mail.gq1.yahoo.com> <647452.65323.qm@web110703.mail.gq1.yahoo.com> Message-ID: On 3/28/2011 12:37 PM Albert-Jan Roskam said... > Hi Stefan, > > Thanks for your advice. I seriously thought ctypes was the module to > use. That was before I found out the evaluating all 10**9 values of my > test data set is glacially slow (several hours). You're right, the dll > implies the program is running on windows. I've also been trying to make > it work under Linux but I wanted to get the basic algorithm right first. > Also, it was quite a PIA to get all the dependencies of the (old) .so files. > > Your speed tip reminded me of: > http://wiki.python.org/moin/PythonSpeed/Performan ceTips#Avoiding_dots > ... > Does this mean that "from ctypes import *" That's not necessary. You can also make them local by performing the name lookup only once: import ctypes myXxx = ctypes.Xxx Then use myXxx going forward. > gives slightly faster code > than "import ctypes"? If so: wow! I've always avoided the first notation > like the plague. > > What do you mean with '... using a constant pointer for numValue' ? It looks like your function can reuse a once-set value where you set numValue outside your function and refer to it. Emile > Is > this the byref/pointer object distinction? I replaced a the pointer > object with a byref object, which reduced processing time by about 10 %. > > Cython might be interesting as a hobby project, but I'm affraid I'll > never get the ICT droids in my office to install that. > > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, wine, > public order, irrigation, roads, a fresh water system, and public > health, what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > *From:* Stefan Behnel > *To:* tutor at python.org > *Sent:* Mon, March 28, 2011 7:43:16 AM > *Subject:* Re: [Tutor] how to optimize this code? > > Albert-Jan Roskam, 27.03.2011 21:57: > > I made a program that reads spss data files. I ran cProfile to see if > I can > > optimize things (see #1 below). > > First thing to note here: sort the output by "time", which refers to the > "tottime" column. That will make it more obvious where most time is > really spent. > > > > It seems that the function getValueNumeric is a pain spot (see #2 > > below). This function calls a C function in a dll for each numerical > > cell value. On the basis of this limited amount of info, what could I do > > to further optimize the code? I heard about psyco, but I didn't think > > such tricks would be necessary as the function spssGetValueNumeric is is > > implemented in C already (which should be fast). > > The problem is that you are using ctypes to call it. It's useful for > simple things, but it's not usable for performance critical things, such > as calling a C function ten million times in your example. Since you're > saying "dll", is this under Windows? It's a bit more tricky to set up > Cython on that platform than on pretty much all others, since you > additionally need to install a C compiler, but if you want to go that > route, it will reward you with a much faster way to call your C code, > and will allow you to also speed up the code that does the calls. > > That being said, see below. > > > > ## most time consuming function > > > > def getValueNumeric(fh, spssio, varHandle): > > numValue = ctypes.c_double() > > numValuePtr = ctypes.byref(numValue) > > retcode = spssio.spssGetValueNumeric(fh, > > &n bsp; ctypes.c_double(varHandle), > > numValuePtr) > > You may still be able to make this code a tad faster, by avoiding the > function name lookups on both the ctypes module and "spssio", and by > using a constant pointer for numValue (is you're not using threads). > That may not make enough of a difference, but it should at least be a > little faster. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From element.effect at gmail.com Mon Mar 28 18:53:44 2011 From: element.effect at gmail.com (Eric Stevens) Date: Mon, 28 Mar 2011 11:53:44 -0500 Subject: [Tutor] List sorting issues Message-ID: I am currently designing an address book program, and am trying to design a method for organizing the keys (which are the names of the entries) for displaying purposes. I have created a list by doing sortedKeys = self.addbook.keys() {the self.addbook refers to a dictionary in a custom class}, and then i try to do a sortedKeys.sort() but never get an alphabetical list of the keys. All i get is 'None'. I know that a 'list.sort()' returns a None value but all of the tutorials I see show this giving an alphabetized list. I have also tried doing a 'sorted(self.addbook)' which gives me a list but not alphabetized. The dictionary keys I am using are 'Eric', 'Kyle', and 'dfd' and they always appear in that order when i use the sorted() feature (obviously not alphabetized). Could you please let me know what I am doing wrong or let me know of another way to alphabetize an iterable object. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Mar 29 00:14:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 09:14:56 +1100 Subject: [Tutor] Replying In-Reply-To: <1301331899.32219005@192.168.4.58> References: <1301331899.32219005@192.168.4.58> Message-ID: <4D910860.3050504@pearwood.info> markrivet at gsoftcon.com wrote: > When replying to the mailing list, does everyone just hit the reply button in your email program. Because that sends the email directly to your email. Also everyone is cc'ng the mailing list; is that the exceptable way to reply so everyone in the list gets the replies? Depends on the mail client I am using to reply. In mutt or kmail, I hit "Reply to list", and the reply just goes to the list. In Thunderbird, I use "Reply All", and edit the recipients by hand so that it just goes to the list, and curse the Thunderbird developers. You should not reply to the individual unless you have something private to tell them. Keep replies on the list, for the benefit of anyone else reading. Personally, I get annoyed when people CC me on replies that I'm also getting from the list, but I've long since stopped trying to hold the tide back :) Thank you for asking, and welcome! -- Steven From steve at pearwood.info Tue Mar 29 00:17:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 09:17:04 +1100 Subject: [Tutor] Replying In-Reply-To: <4D90C2FF.5010801@aim.com> References: <1301331899.32219005@192.168.4.58> <4D90C2FF.5010801@aim.com> Message-ID: <4D9108E0.9040004@pearwood.info> Corey Richardson wrote: > Thunderbird has a "reply list" button that I use. It does? What version are you using? -- Steven From jigenbakuda at yahoo.com Tue Mar 29 00:14:46 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Mon, 28 Mar 2011 15:14:46 -0700 (PDT) Subject: [Tutor] User Made Dictionaries In-Reply-To: References: Message-ID: <63364.99867.qm@web130210.mail.mud.yahoo.com> Hello, I'm trying to find out the best course of action for the next stage of my program. I want to hold information on various idols. I first thought to do this with classes, but realised that I could represent the data the same way with a dictionary. So I am now just concentrating on dictionaries. So lets say for example I wanted to have a dictionary with keys like this. chiaki = { "name" : "Chiaki Kuriyama", "age" : "26", "charm_point" : "nose", "profile_pic" : "/home/jigenbakuda/Pictures/chiaki/chiaki.jpg", "pic_quantity" : 120, "bio" : "First met this lady in kill bill, and the descent afterwards was horrible, I fan boy over this chick hard, etc..."} I understand, or at least I have pretty good ideas about how to get this information (the keys and their values) from a user. I was thinking something like this for my general flow (this is all just fake code trying to represent my thought process) mold = { "name" : " ", "age" : " ", "charm_point" : " ", "profile_pic" : " ", "pic_quantity" : 0 , "bio" : " "} chiaki = copy.copy(mold) #have the user fill in the data here natalie = copy.copy(mold) #have the user fill in the data here # etc... But my question is how do I repeatedly automate new names for the dictionaries? Like how do I get the user to create the dictionary name (chiaki, natalie, etc...)? Would it be better to represent this data with classes? If so, how do I have users create new class names? Ex. chiaki = Idol(), how do I get the user to create the chiaki name? Any hints, answers, or links to recommended reading would be greatly appreciated :) ---- What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Tue Mar 29 00:24:15 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 28 Mar 2011 17:24:15 -0500 Subject: [Tutor] List sorting issues In-Reply-To: References: Message-ID: <2D255DF7-11BA-4B59-8098-5FDFB711BFDC@gmail.com> Sort returns none because it changes your list in-place. Print your list out after calling sort and you should see the new one. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Mar 28, 2011, at 11:53 AM, Eric Stevens wrote: > I am currently designing an address book program, and am trying to design a method for organizing the keys (which are the names of the entries) for displaying purposes. I have created a list by doing sortedKeys = self.addbook.keys() {the self.addbook refers to a dictionary in a custom class}, and then i try to do a sortedKeys.sort() but never get an alphabetical list of the keys. All i get is 'None'. I know that a 'list.sort()' returns a None value but all of the tutorials I see show this giving an alphabetized list. > > I have also tried doing a 'sorted(self.addbook)' which gives me a list but not alphabetized. The dictionary keys I am using are 'Eric', 'Kyle', and 'dfd' and they always appear in that order when i use the sorted() feature (obviously not alphabetized). > > Could you please let me know what I am doing wrong or let me know of another way to alphabetize an iterable object. Thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Tue Mar 29 00:28:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 09:28:11 +1100 Subject: [Tutor] List sorting issues In-Reply-To: References: Message-ID: <4D910B7B.1030600@pearwood.info> Eric Stevens wrote: > I am currently designing an address book program, and am trying to design a > method for organizing the keys (which are the names of the entries) for > displaying purposes. I have created a list by doing sortedKeys = > self.addbook.keys() {the self.addbook refers to a dictionary in a custom > class}, and then i try to do a sortedKeys.sort() but never get an > alphabetical list of the keys. All i get is 'None'. I know that a > 'list.sort()' returns a None value but all of the tutorials I see show this > giving an alphabetized list. If you see any tutorial showing list.sort() *returning* a sorted list, the tutorial is wrong. But more likely you have misunderstood what you are seeing. list.sort() is an in-place list. So you have to do this: mylist = ["Fred", "Wilma", "Barney", "Betty"] mylist.sort() # Returns None, which we don't bother to keep. print(mylist) Or you can use the sorted() function, which returns a new list, leaving the original alone: mylist = ["Fred", "Wilma", "Barney", "Betty"] print(sorted(mylist)) print(mylist) > I have also tried doing a 'sorted(self.addbook)' which gives me a list but > not alphabetized. The dictionary keys I am using are 'Eric', 'Kyle', and > 'dfd' and they always appear in that order when i use the sorted() feature > (obviously not alphabetized). Sorting is case sensitive, so "Z" comes before "a". For case insensitive sorting, pass a key function to either sorted() or list.sort(): sorted(mylist, key=string.lower) # Can also use string.upper Technically, this is not really case-insensitive according to the (very complex!) rules for sorting international text, but if your data is all English (or at least mostly English) you won't notice the difference. -- Steven From kb1pkl at aim.com Tue Mar 29 00:31:41 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 28 Mar 2011 18:31:41 -0400 Subject: [Tutor] Replying In-Reply-To: <4D9108E0.9040004@pearwood.info> References: <1301331899.32219005@192.168.4.58> <4D90C2FF.5010801@aim.com> <4D9108E0.9040004@pearwood.info> Message-ID: <4D910C4D.7020806@aim.com> On 03/28/2011 06:17 PM, Steven D'Aprano wrote: > Corey Richardson wrote: > >> Thunderbird has a "reply list" button that I use. > > It does? What version are you using? 3.1.8 I don't know how it knows what a mailing list is and isn't, but it does. After inspecting the headers of emails from a few different lists, it appears: List-Id, Lust-Unsubscribe, List-Archive, List-Post, List-Help, and List-Subscribe may be helping thunderbird along. Also common among them is a "Precedence: list" header. -- Corey Richardson From steve at pearwood.info Tue Mar 29 00:51:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 09:51:28 +1100 Subject: [Tutor] User Made Dictionaries In-Reply-To: <63364.99867.qm@web130210.mail.mud.yahoo.com> References: <63364.99867.qm@web130210.mail.mud.yahoo.com> Message-ID: <4D9110F0.7020703@pearwood.info> michael scott wrote: > I was thinking something like this for my general flow (this is all just fake > code trying to represent my thought process) > > mold = { "name" : " ", > "age" : " ", > "charm_point" : " ", > "profile_pic" : " ", > "pic_quantity" : 0 , > "bio" : " "} > > > chiaki = copy.copy(mold) > #have the user fill in the data here > natalie = copy.copy(mold) > #have the user fill in the data here > # etc... > > > But my question is how do I repeatedly automate new names for the dictionaries? > Like how do I get the user to create the dictionary name (chiaki, natalie, > etc...)? You don't. Instead of something like this: chiaki = {...} natalie = {...} ... You have a second dictionary, keyed by the names: girls = {'chiaki': {...}, 'natalie': {...}, ... } Something like this: girls = {} while True: template = copy.copy(mold) name = raw_input("What's the name of an actress?") # See below. if name == "exit": break # Exit the loop. #have the user fill in rest of the data here girls[name] = template Or you could use a real database, like sqlite, or even a *real* database. If you are using Python 3 or better, change raw_input to input. -- Steven From ranceh at gmail.com Tue Mar 29 01:43:19 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 28 Mar 2011 18:43:19 -0500 Subject: [Tutor] finding directory of self Message-ID: I had been doing this under windows: import os import sys osname = os.name pathtocfg = os.path.dirname(sys.argv[0]) configfileloc = os.path.abspath(pathtocfg) os.chdir(configfileloc) to set the directory of all subsequent file lookups in a script. It worked underwindows because the shortcuts have a "Start In" directory listing. I need something for Linux use that does not care about a symlink that would be used to start the script. The above code finds the directory the symlink is in. I'm actually not suprised by this, it is what I expected, I just don't understand how to fix it. How can I do something similar to this, but find the "real" dir? Perhaps one of the other sys.argv arguments? Thanks for your help Rance From waynejwerner at gmail.com Tue Mar 29 02:16:41 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 28 Mar 2011 19:16:41 -0500 Subject: [Tutor] finding directory of self In-Reply-To: References: Message-ID: On Mon, Mar 28, 2011 at 6:43 PM, Rance Hall wrote: > I had been doing this under windows: > > import os > import sys > > osname = os.name > pathtocfg = os.path.dirname(sys.argv[0]) > configfileloc = os.path.abspath(pathtocfg) > os.chdir(configfileloc) > > to set the directory of all subsequent file lookups in a script. > > It worked underwindows because the shortcuts have a "Start In" > directory listing. > > I need something for Linux use that does not care about a symlink that > would be used to start the script. > > The above code finds the directory the symlink is in. > > I'm actually not suprised by this, it is what I expected, I just don't > understand how to fix it. > > How can I do something similar to this, but find the "real" dir? > Perhaps one of the other sys.argv arguments? > print(os.path.realpath(__file__)) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjameshunter at gmail.com Tue Mar 29 05:12:50 2011 From: bjameshunter at gmail.com (Ben Hunter) Date: Mon, 28 Mar 2011 20:12:50 -0700 Subject: [Tutor] Problem recognizing '{' character? Message-ID: Hi, I'm completing the Python lessons on YouTube that Google posted. At the end of section 2 of day 2, there is a task to identify files then put them in a zip file in any directory. The code is from the 'solution' folder, so it's not something I wrote. I suspect I have a problem with PATHS or environment variables. I'm new to programming in something as advanced as Python, but I do okay with VBA - so I just feel like there's a setting up issue somewhere. I'm on Windows 7, tried running this in Idle and from the command line. These two work perfectly. def get_special_paths(dirname): result = [] paths = os.listdir(dirname) # list of paths in that dir for fname in paths: match = re.search(r'__(\w+)__', fname) if match: result.append(os.path.abspath(os.path.join(dirname, fname))) return result def copy_to(paths, to_dir): if not os.path.exists(to_dir): os.mkdir(to_dir) for path in paths: fname = os.path.basename(path) shutil.copy(path, os.path.join(to_dir, fname)) This third one does not. def zip_to(paths, zipfile): """Zip up all of the given files into a new zip file with the given name.""" cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths) print "Command I'm going to do:" + cmd (status, output) = commands.getstatusoutput(cmd) # If command had a problem (status is non-zero), # print its output to stderr and exit. if status: sys.stderr.write(output) sys.exit(1) My command is this: >>> copyspecial.zip_to(paths, 'zippy') But something goes wrong and it spits this out: '{' is not recognized as an internal or external command, operable program or batch file. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Mar 29 09:37:25 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Mar 2011 08:37:25 +0100 Subject: [Tutor] Replying In-Reply-To: <4D9108E0.9040004@pearwood.info> References: <1301331899.32219005@192.168.4.58> <4D90C2FF.5010801@aim.com> <4D9108E0.9040004@pearwood.info> Message-ID: <4D918C35.9060205@timgolden.me.uk> On 28/03/2011 23:17, Steven D'Aprano wrote: > Corey Richardson wrote: > >> Thunderbird has a "reply list" button that I use. > > It does? What version are you using? Also, if you're a keyboard person, Ctrl-Shift-L (Win7, TB 3.1.9) TJG From km_wawa at vp.pl Tue Mar 29 09:49:33 2011 From: km_wawa at vp.pl (Mateusz K) Date: Tue, 29 Mar 2011 09:49:33 +0200 Subject: [Tutor] how to join two text files ? In-Reply-To: <146626.57899.qm@web110714.mail.gq1.yahoo.com> References: <4D8E55DB.60604@vp.pl> <146626.57899.qm@web110714.mail.gq1.yahoo.com> Message-ID: <4D918F0D.5010800@vp.pl> Well...it looks like I do not know how to use it. Could You help me Example file_1: ==================================================================== 20 53 2.66196 21 53 2.67512 20 52 2.63444 21 52 2.94148 ==================================================================== Example file_2: ==================================================================== 20 53 1.75904 21 53 2.92742 20 52 2.79653 21 52 2.12499 ==================================================================== and so on.... my script: ==================================================================== import glob {some code here} ####here is loop which change folder_daty, zmienna and folder_serw:########## plik2=folder_daty+zmienna+"XYZ.txt" zbiorcze = folder_serw + zmienna + ".txt" if not os.path.isfile(zbiorcze): shutil.copy(plik2, zbiorcze) else: with open(zbiorcze, "wb") as w: writer = csv.writer(w) for f in glob.glob(plik2): rows = open(f, "rb").readlines() writer.writerows(rows) ==================================================================== and result looks like: ==================================================================== 2,0, ,5,3, ,2,.,4,4,8,2," " 2,1, ,5,3, ,3,.,0,4,9,9,6," " 2,0, ,5,2, ,3,.,1,8,4,9,5," " 2,1, ,5,2, ,3,.,3,2,2,6,5," " ==================================================================== > Hello, > > If the files are not too big, you could do something like: > with open("/home/me/Desktop/test.csv", "wb") as w: > writer = csv.writer(w) > for f in glob.glob("/home/me/Desktop/files/*.txt"): > rows = open(f, "rb").readlines() > writer.writerows(rows) > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > All right, but apart from the sanitation, the medicine, education, > wine, public order, irrigation, roads, a fresh water system, and > public health, what have the Romans ever done for us? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > ------------------------------------------------------------------------ > *From:* Mateusz K > *To:* tutor at python.org > *Sent:* Sat, March 26, 2011 10:08:43 PM > *Subject:* [Tutor] how to join two text files ? > > Hello, > > I have many text files, where data is delimited by space. > Each file contain three colums: coordinate x, coordinate y and value > for this location. > > I would like to join this data to get one big file which will > contain columns: > coordinate x, coordinate y, value1,value2,..., value_n and save it to > another text file. > > I wrote script, but there's some stupid error (like "\n" character > although > I have added .rstrip() command). > > Coul You tell me what is most convenient way to join this data > (maybe by using csv module?)? > > ========= > Best regards, > Mateusz > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- ------------------------------------------------------------------------ *Pozdrawiam / Best regards, * Mateusz Ke;dzior | environmental engineer Uz.ywam "otwartych" format?w plik?w biurowych environmental protection: please consider the environment before printing my email -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 29 10:16:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2011 09:16:32 +0100 Subject: [Tutor] finding directory of self References: Message-ID: "Rance Hall" wrote > osname = os.name > pathtocfg = os.path.dirname(sys.argv[0]) > configfileloc = os.path.abspath(pathtocfg) > os.chdir(configfileloc) > > to set the directory of all subsequent file lookups in a script. This is not the most user friendly thing to do. Some sys admins require config files (and indeed all data) to be located separately from programs. It would be more friendly to provide the option of defining the config file location, perhaps via an environment variable. Of course if the env variable is not defined you probably still need this code for the default location, in which case Wayne's suggestion should work. (Alternatively throw an error insisting the EV be set up) And if you are not deploying this to more than one operating envioronment where you know the policy then its a moot point anyway. Alan G. Back from his vacation :-) From alan.gauld at btinternet.com Tue Mar 29 10:21:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2011 09:21:18 +0100 Subject: [Tutor] server used in python References: Message-ID: "ema francis" wrote >I am learnning python for 3 months from now. I wanted to know how >and what > *server* is used in python web development?Looking for your help > .... Python is "blessed" with very many web development frameworks. For basic CGI programming you can use the basic weeb server that comes with Python. For deployment Apache or any other deployment scale server will do. If you are using the more complex frameworks they will have their own development/deployment recomendations, so it all depends on what framework you want to use. Everything from CherryPy to Zope or Plone... Your choice really. There is a good set of documents in the Python webn site that discuss the various web frameworks and options. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 29 10:26:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2011 09:26:44 +0100 Subject: [Tutor] How to read remote text file? References: Message-ID: "Ratna Banjara" wrote > I need to read text file from remote server and generate excel file > from > local computer using python. Is it possible? If so how? Which bit is hard? The reading the file remotely? Or the generating Excel? If the file system is mounted on your local computer you can read it like any other file via the mount. If not you will need to fetch a copy for which the server will need to provide some form of access mechanism - ftp, http, ssh or whatever. To convert the file to Excel will depend on what the original format is and how complex the output is. There are various support modules to help starting with the CSV module and ranging up to more Excel specific variants. Finally you can create/edit Excel documents directly via COM if you are on a Windows box with Excel installed... But that is not for the faint hearted! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Tue Mar 29 10:41:36 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Mar 2011 10:41:36 +0200 Subject: [Tutor] Problem recognizing '{' character? References: Message-ID: Ben Hunter wrote: > Hi, > > I'm completing the Python lessons on YouTube that Google posted. At the > end of section 2 of day 2, there is a task to identify files then put them > in a zip file in any directory. The code is from the 'solution' folder, so > it's not something I wrote. I suspect I have a problem with PATHS or > environment variables. I'm new to programming in something as advanced as > Python, but I do okay with VBA - so I just feel like there's a setting up > issue somewhere. I'm on Windows 7, tried running this in Idle and from the > command line. The commands module used by zip_to() is an unfortunate choice for a tutorial because it is supposed to work with unix shells only. > def zip_to(paths, zipfile): > """Zip up all of the given files into a new zip file with the given > name.""" > cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths) > print "Command I'm going to do:" + cmd > (status, output) = commands.getstatusoutput(cmd) > # If command had a problem (status is non-zero), > # print its output to stderr and exit. > if status: > sys.stderr.write(output) > sys.exit(1) You can either try to install Cygwin to run your script unchanged or rewrite the above function to work with subprocess import sys from subprocess import Popen, PIPE def zip_to(paths, zipfile): command = ["zip", "-j", zipfile] command.extend(paths) process = Popen(command, stdout=PIPE, stderr=PIPE) stdoutdata, stderrdata = process.communicate() if process.returncode: sys.stdout.write(stdoutdata) sys.stderr.write(stderrdata) sys.exit(1) You'll still need a zip.exe on your system. If you're ambitious, have a look at http://docs.python.org/library/zipfile.html a library that allows you to create zipfiles in python without the help of an external program. From __peter__ at web.de Tue Mar 29 10:45:21 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Mar 2011 10:45:21 +0200 Subject: [Tutor] how to join two text files ? References: <4D8E55DB.60604@vp.pl> Message-ID: Mateusz K wrote: > I have many text files, where data is delimited by space. > Each file contain three colums: coordinate x, coordinate y and value for > this location. > > I would like to join this data to get one big file which will > contain columns: > coordinate x, coordinate y, value1,value2,..., value_n and save it to > another text file. > > I wrote script, but there's some stupid error (like "\n" character > although I have added .rstrip() command). > > Coul You tell me what is most convenient way to join this data > (maybe by using csv module?)? Please show us the code that you have. This proves that you've put some effort into the matter and allows us to focus on the missing parts. From mail at timgolden.me.uk Tue Mar 29 10:49:29 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 29 Mar 2011 09:49:29 +0100 Subject: [Tutor] Problem recognizing '{' character? In-Reply-To: References: Message-ID: <4D919D19.30000@timgolden.me.uk> On 29/03/2011 09:41, Peter Otten wrote: > Ben Hunter wrote: > >> Hi, >> >> I'm completing the Python lessons on YouTube that Google posted. At the >> end of section 2 of day 2, there is a task to identify files then put them >> in a zip file in any directory. The code is from the 'solution' folder, so >> it's not something I wrote. I suspect I have a problem with PATHS or >> environment variables. I'm new to programming in something as advanced as >> Python, but I do okay with VBA - so I just feel like there's a setting up >> issue somewhere. I'm on Windows 7, tried running this in Idle and from the >> command line. > > The commands module used by zip_to() is an unfortunate choice for a tutorial > because it is supposed to work with unix shells only. It's also unfortunate that an issue has been outstanding here for a while: http://bugs.python.org/issue10197 It's one of those which seems simple to fix but which spawns a thousand discussions... TJG From ldl08 at gmx.net Tue Mar 29 11:02:50 2011 From: ldl08 at gmx.net (David) Date: Tue, 29 Mar 2011 11:02:50 +0200 Subject: [Tutor] What's the logic behind parameters and arguments? Message-ID: <4D91A03A.4010109@gmx.net> Dear list readers, the command find() takes two parameters, start and end, e.g.: find(substring[, start[, end]]). Here, a substring is located UP TO BUT NOT INCLUDING the optional parameter 'end'. Compare this to replace(). replace() comes with the count argument, e.g.: replace(old, new[, count]) But here the substring is replaced UP TO AND INCLUDING to the optional argument count. My question is how I am best to make sense of this discrepancy. Is there any logic behind this that might make my life easier once I become aware of it? I know of the indexing rules, but this here is obviously not the same. I am curious... Thanks, David From rafadurancastaneda at gmail.com Tue Mar 29 11:09:42 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Tue, 29 Mar 2011 11:09:42 +0200 Subject: [Tutor] how to join two text files ? In-Reply-To: References: <4D8E55DB.60604@vp.pl> Message-ID: If you need read files like Example file_1 and file_2 you could use csv reader, look this code and think how you could use it: import csv f1 = csv.reader(open('file1', newline=''),delimiter=' ') for a, b, c in f1: print('%s %s %s' % (a, b, c)) 2011/3/29 Peter Otten <__peter__ at web.de> > Mateusz K wrote: > > > I have many text files, where data is delimited by space. > > Each file contain three colums: coordinate x, coordinate y and value for > > this location. > > > > I would like to join this data to get one big file which will > > contain columns: > > coordinate x, coordinate y, value1,value2,..., value_n and save it to > > another text file. > > > > I wrote script, but there's some stupid error (like "\n" character > > although I have added .rstrip() command). > > > > Coul You tell me what is most convenient way to join this data > > (maybe by using csv module?)? > > Please show us the code that you have. This proves that you've put some > effort into the matter and allows us to focus on the missing parts. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Tue Mar 29 11:24:58 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Tue, 29 Mar 2011 11:24:58 +0200 Subject: [Tutor] What's the logic behind parameters and arguments? In-Reply-To: <4D91A03A.4010109@gmx.net> References: <4D91A03A.4010109@gmx.net> Message-ID: I don't see discrepancy, end and count are two arguments than mean very different things. End is the position where find ends, it could be included or excluded, in this case is excluded. Count is the maximun number of substrings you want to replace, it wouldn't make sense count=6 if you want to replace 5. 2011/3/29 David > Dear list readers, > > the command find() takes two parameters, start and end, e.g.: > > find(substring[, start[, end]]). > > Here, a substring is located UP TO BUT NOT INCLUDING the optional > parameter 'end'. > > Compare this to replace(). replace() comes with the count argument, e.g.: > > replace(old, new[, count]) > > But here the substring is replaced UP TO AND INCLUDING to the optional > argument count. > > My question is how I am best to make sense of this discrepancy. Is there > any logic behind this that might make my life easier once I become aware > of it? I know of the indexing rules, but this here is obviously not the > same. I am curious... > > Thanks, > > David > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 29 11:35:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2011 10:35:19 +0100 Subject: [Tutor] What's the logic behind parameters and arguments? References: <4D91A03A.4010109@gmx.net> Message-ID: "Rafael Dur?n Casta?eda" wrote >I don't see discrepancy, end and count are two arguments than mean >very > different things. End is the position where find ends, it could be > included > or excluded, in this case is excluded. Count is the maximun number > of > substrings you want to replace, it wouldn't make sense count=6 if > you want > to replace 5. And in general Python uses the convention for *positional* values that it goes up to but not including the last position. Compare slicing, range() etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Mar 29 11:55:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 20:55:56 +1100 Subject: [Tutor] What's the logic behind parameters and arguments? In-Reply-To: <4D91A03A.4010109@gmx.net> References: <4D91A03A.4010109@gmx.net> Message-ID: <4D91ACAC.7080405@pearwood.info> David wrote: > Dear list readers, > > the command find() takes two parameters, start and end, e.g.: > > find(substring[, start[, end]]). > > Here, a substring is located UP TO BUT NOT INCLUDING the optional > parameter 'end'. > > Compare this to replace(). replace() comes with the count argument, e.g.: > > replace(old, new[, count]) > > But here the substring is replaced UP TO AND INCLUDING to the optional > argument count. > > My question is how I am best to make sense of this discrepancy. Is there > any logic behind this that might make my life easier once I become aware > of it? I know of the indexing rules, but this here is obviously not the > same. I am curious... The two functions do different things, they work differently, they take different arguments. replace takes an inclusive `count` parameter because that's the most sensible and obvious way to implement a count parameter. "I want to replace the first five words" suggests a count parameter of 5, not 6. A count of 1 should replace 1 time, not 0 times. The start and end parameters of find work like slices, where the arguments act to slice *between* items: 0.1.2.3.4.5.6 |a|b|c|d|e|f| So, completely different, and there's no discrepancy. As for the question why replace doesn't take a start and end argument like find, *shrug* perhaps it should. But it already has three parameters, another two will start overloading it. -- Steven From steve at pearwood.info Tue Mar 29 11:57:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Mar 2011 20:57:59 +1100 Subject: [Tutor] Replying In-Reply-To: <4D910C4D.7020806@aim.com> References: <1301331899.32219005@192.168.4.58> <4D90C2FF.5010801@aim.com> <4D9108E0.9040004@pearwood.info> <4D910C4D.7020806@aim.com> Message-ID: <4D91AD27.4090904@pearwood.info> Corey Richardson wrote: > After inspecting the headers of emails from a few different lists, it > appears: List-Id, Lust-Unsubscribe, List-Archive, List-Post, List-Help, Oh to be young again... I could have done with a Lust-Unsubscribe command quite a few times... -- Steven From beachkidken at gmail.com Tue Mar 29 15:06:00 2011 From: beachkidken at gmail.com (Ken G.) Date: Tue, 29 Mar 2011 09:06:00 -0400 Subject: [Tutor] Replying In-Reply-To: <4D9108E0.9040004@pearwood.info> References: <1301331899.32219005@192.168.4.58> <4D90C2FF.5010801@aim.com> <4D9108E0.9040004@pearwood.info> Message-ID: <4D91D938.6030307@gmail.com> I am using v3.1.8 for Mozilla Thunderbird. Ken On 03/28/2011 06:17 PM, Steven D'Aprano wrote: > Corey Richardson wrote: > >> Thunderbird has a "reply list" button that I use. > > It does? What version are you using? > > From bjameshunter at gmail.com Tue Mar 29 18:13:28 2011 From: bjameshunter at gmail.com (Ben Hunter) Date: Tue, 29 Mar 2011 09:13:28 -0700 Subject: [Tutor] Problem recognizing '{' character? In-Reply-To: References: Message-ID: Thanks a ton. For the record I did read the 'command' module help page, but must have skipped over the 'Platforms: Unix' and 'Deprecated' parts. I successfully got it to work with the subprocess module, but I really appreciate you filling out the rest with the sys.stderr.write(stderrdata). I certainly would have stumbled over that. -BJH On Mon, Mar 28, 2011 at 8:12 PM, Ben Hunter wrote: > Hi, > > I'm completing the Python lessons on YouTube that Google posted. At the end > of section 2 of day 2, there is a task to identify files then put them in a > zip file in any directory. The code is from the 'solution' folder, so it's > not something I wrote. I suspect I have a problem with PATHS or environment > variables. I'm new to programming in something as advanced as Python, but I > do okay with VBA - so I just feel like there's a setting up issue somewhere. > I'm on Windows 7, tried running this in Idle and from the command line. > > These two work perfectly. > > def get_special_paths(dirname): > result = [] > paths = os.listdir(dirname) # list of paths in that dir > for fname in paths: > match = re.search(r'__(\w+)__', fname) > if match: > result.append(os.path.abspath(os.path.join(dirname, fname))) > return result > > > def copy_to(paths, to_dir): > if not os.path.exists(to_dir): > os.mkdir(to_dir) > for path in paths: > fname = os.path.basename(path) > shutil.copy(path, os.path.join(to_dir, fname)) > > This third one does not. > > def zip_to(paths, zipfile): > """Zip up all of the given files into a new zip file with the given > name.""" > cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths) > print "Command I'm going to do:" + cmd > (status, output) = commands.getstatusoutput(cmd) > # If command had a problem (status is non-zero), > # print its output to stderr and exit. > if status: > sys.stderr.write(output) > sys.exit(1) > > My command is this: >>> copyspecial.zip_to(paths, 'zippy') > > But something goes wrong and it spits this out: > '{' is not recognized as an internal or external command, > operable program or batch file. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From markrivet at gsoftcon.com Tue Mar 29 19:55:14 2011 From: markrivet at gsoftcon.com (markrivet at gsoftcon.com) Date: Tue, 29 Mar 2011 13:55:14 -0400 (EDT) Subject: [Tutor] Replying In-Reply-To: <4D910860.3050504@pearwood.info> References: <1301331899.32219005@192.168.4.58> <4D910860.3050504@pearwood.info> Message-ID: <1301421314.023127389@192.168.4.58> Ok, thanks. I didn't think we should be replying to individuals unless on special case's. I also will have edit my header, but that's fine. -----Original Message----- From: "Steven D'Aprano" Sent: Monday, March 28, 2011 6:14pm To: tutor at python.org Subject: Re: [Tutor] Replying markrivet at gsoftcon.com wrote: > When replying to the mailing list, does everyone just hit the reply button in your email program. Because that sends the email directly to your email. Also everyone is cc'ng the mailing list; is that the exceptable way to reply so everyone in the list gets the replies? Depends on the mail client I am using to reply. In mutt or kmail, I hit "Reply to list", and the reply just goes to the list. In Thunderbird, I use "Reply All", and edit the recipients by hand so that it just goes to the list, and curse the Thunderbird developers. You should not reply to the individual unless you have something private to tell them. Keep replies on the list, for the benefit of anyone else reading. Personally, I get annoyed when people CC me on replies that I'm also getting from the list, but I've long since stopped trying to hold the tide back :) Thank you for asking, and welcome! -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Mark R Rivet, Genesis Software Consulting ASCT(Computer Technologies), BSIT/SE(Software Engineering) Electrical Engineering Technician Member IEEE, Computer Society Do or do not; there is no try. From ramit.prasad at jpmchase.com Tue Mar 29 21:41:40 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Tue, 29 Mar 2011 15:41:40 -0400 Subject: [Tutor] String formatting question. Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Is there a difference (or preference) between using the following? "%s %d" % (var,num) VERSUS "{0} {1}".format(var,num) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From ranjand2005 at gmail.com Tue Mar 29 22:03:45 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Wed, 30 Mar 2011 01:33:45 +0530 Subject: [Tutor] Grouping based on attributes of elements in a List Message-ID: I have the following list List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] now I want to group this elements of List first by index [1] that is (CFS and LOOSEFREIGHT ) together and for those elements which are grouped together for LOOSEFREIGHT, i want to further divide them into different groups based on index[2] that is (LCL or MIXEDLCL) So essentially i want them grouped into different lists and my solution should be of the form New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ), ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')] ] How do I do it? I managed to do divide them into different lists based on index [1] however I was not able to further divide them based on index [2] Any help is appreciated -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Tue Mar 29 22:21:19 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 29 Mar 2011 16:21:19 -0400 Subject: [Tutor] String formatting question. In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D923F3F.3030904@aim.com> On 03/29/2011 03:41 PM, Prasad, Ramit wrote: > Is there a difference (or preference) between using the following? > "%s %d" % (var,num) > VERSUS > "{0} {1}".format(var,num) > > > Ramit If you're using Python 3, use the second one. If you're using Python 2, you have no option but to use the first, as far as I know. Maybe Python 2.7 has that formatting, I'm not sure. -- Corey Richardson From eli.nazarova at gmail.com Tue Mar 29 22:28:04 2011 From: eli.nazarova at gmail.com (Eli Nazarova) Date: Tue, 29 Mar 2011 16:28:04 -0400 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: <4D9240D4.8070101@gmail.com> On 3/29/2011 4:03 PM, ranjan das wrote: > I have the following list > > List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', > 'R4' ), ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', > 'R5') ] > > > now I want to group this elements of List first by index [1] that is > (CFS and LOOSEFREIGHT ) together and for those elements which are > grouped together for LOOSEFREIGHT, i want to further divide them into > different groups based on index[2] that is (LCL or MIXEDLCL) > > > So essentially i want them grouped into different lists and my > solution should be of the form > > New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' > ), ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2', 'LOOSEFREIGHT', 'LCL', > 'R4' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', > 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')] ] > > How do I do it? > > I managed to do divide them into different lists based on index [1] > however I was not able to further divide them based on index [2] > > Any help is appreciated > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can you list comprehension (three times) checking for membership of the relevant items, or you can use for loop to go over all available tuples and sort them into different lists using if. In any case, after that you create a list of the three required lists. Eli -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Mar 29 22:28:21 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 29 Mar 2011 16:28:21 -0400 Subject: [Tutor] String formatting question. In-Reply-To: <4D923F3F.3030904@aim.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> <4D923F3F.3030904@aim.com> Message-ID: On Tue, Mar 29, 2011 at 4:21 PM, Corey Richardson wrote: > On 03/29/2011 03:41 PM, Prasad, Ramit wrote: > > Is there a difference (or preference) between using the following? > > "%s %d" % (var,num) > > VERSUS > > "{0} {1}".format(var,num) > > > > > > Ramit > > If you're using Python 3, use the second one. If you're using Python 2, > you have no option but to use the first, as far as I know. Maybe Python > 2.7 has that formatting, I'm not sure. > > -- > Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > you can use string{0}.format(var) in python 2.6. I use it all the time. I never use the other % method. -------------- next part -------------- An HTML attachment was scrubbed... URL: From susana.delgado_s at utzmg.edu.mx Tue Mar 29 22:38:42 2011 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Tue, 29 Mar 2011 14:38:42 -0600 Subject: [Tutor] Run application from MS-DOS with sys.argv Message-ID: Hello List: I developed a script to walk through a specific directory in my PC and look for files with the same extension (.shp). I want the user to enter from MS-DOS and write the the directory, file extension and csv filename. My script reads the arguments from Windows console, but when I opened the txt file and csv file I noticed that isn't walking through all the root I wrote in MS-DOS. This is my module: import os, csv, time, socket, sys from osgeo import ogr,gdal,osr #This should be the order for the arguments('csv_args.py [root] [file_extension] [csv filename]') #The user is typing python csv_args.py C:\ .shp csv.csv directorio = sys.argv[1] extension = sys.argv[2] csv_salida = sys.argv[3] if len(sys.argv) == 4: print 'Iniciando...' gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk(directorio): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(extension)) f = open(csv_salida, 'wb') log = open ('errores.txt','w') writer = csv.writer(f) ruta = 'Ruta' archivo = 'archivo' x_min = 'x_min' x_max = 'x_max' y_min = 'y_min' y_max = 'y_max' geometria = 'geometria' num_elem = 'num_elem' prj = '.prj' proyeccion = 'proyeccion' fecha = 'fecha_modificacion' maq = 'maquina_host' usu = 'usuario' campos = [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,fecha,maq,usu] writer.writerow(campos) for row, filepath in enumerate(file_list, start=1): (ruta, filename) = os.path.split(filepath) shapeData = ogr.Open(filepath) shp = 'Error al abrir el archivo' +filepath if shapeData is None: print shp log.write(shp+"\n") else: layer = shapeData.GetLayer() feature = layer.GetNextFeature() x_y = layer.GetExtent() x1 = x_y[0] x2 = x_y[1] y1 = x_y[2] y2 = x_y[3] defn = layer.GetLayerDefn() geo = defn.GetGeomType() cuenta = layer.GetFeatureCount() proy = layer.GetSpatialRef() prjtext = ''+str(proy)+'' n = os.path.splitext(filepath) p = n[0]+'.prj' shx = n[0]+'.shx' dbf = n[0]+'.dbf' filepath = ''+filepath+'' filename = ''+filename+'' t = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(filepath))) modificacion = ''+t+'' usuario = os.environ.get("USERNAME") user = ''+usuario+'' host = socket.gethostname() maquina = ''+host+'' if os.path.exists(shx): print 'El archivo ' +shx +' existe' else: og.write('No existe el archivo ' +shx+"\n") if os.path.exists(dbf): print 'El archivo ' +dbf +' existe' else: log.write('No existe el archivo ' +dbf+"\n") if os.path.exists(p): aRow= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 1, prjtext, modificacion, maquina, user] writer.writerow(aRow) else: aRow1= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 0, prjtext, modificacion, maquina, user] writer.writerow(aRow1) log.close() f.close() print "El archivo esta listo" else: print "Tus argumentos no son correctos" -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue Mar 29 23:52:03 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 29 Mar 2011 23:52:03 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: On 29 March 2011 22:03, ranjan das wrote: > List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), > ('G4', 'CFS', 'FCL', 'R10' ), ('G2',? 'LOOSEFREIGHT', 'LCL', 'R4' ), ('G1', > 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5')? ] > > > now I want to group this elements of List? first by index [1] that is (CFS > and LOOSEFREIGHT ) together and for those elements which are grouped > together for LOOSEFREIGHT, i want to further divide them into different > groups based on index[2] that is (LCL or MIXEDLCL) > > > So essentially i want them grouped into different lists and my solution > should be? of the form > > New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ), > ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2',? 'LOOSEFREIGHT', 'LCL', 'R4' ), > ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9')] ] > > How do I do it? You can use itemgetter from the operator module. The below should do what you want. I am using sorted to return a new list but you can also sort the list in place with list.sort(). >>> import operator >>> l =[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] >>> sorted(l, key=operator.itemgetter(1,2)) [('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1', 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')] Greets Sander From rafadurancastaneda at gmail.com Tue Mar 29 23:57:41 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Tue, 29 Mar 2011 23:57:41 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: This would work nice too: list_=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] >>> sorted(list_,key=lambda l: l[1:3]) [('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1', 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')] >>> And more pythonic, I think 2011/3/29 Sander Sweers > On 29 March 2011 22:03, ranjan das wrote: > > List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9'), > > ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), > ('G1', > > 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] > > > > > > now I want to group this elements of List first by index [1] that is > (CFS > > and LOOSEFREIGHT ) together and for those elements which are grouped > > together for LOOSEFREIGHT, i want to further divide them into different > > groups based on index[2] that is (LCL or MIXEDLCL) > > > > > > So essentially i want them grouped into different lists and my solution > > should be of the form > > > > New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ), > > ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), > > ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT', > 'MIXEDLCL', > > 'R9')] ] > > > > How do I do it? > > You can use itemgetter from the operator module. The below should do > what you want. I am using sorted to return a new list but you can also > sort the list in place with list.sort(). > > >>> import operator > >>> l =[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), > ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] > >>> sorted(l, key=operator.itemgetter(1,2)) > [('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1', > 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', > 'LOOSEFREIGHT', 'LCL', 'R5'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9')] > > Greets > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Mar 30 00:08:38 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 30 Mar 2011 00:08:38 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: On 29 March 2011 23:52, Sander Sweers wrote: > On 29 March 2011 22:03, ranjan das wrote: >> New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ), >> ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2',? 'LOOSEFREIGHT', 'LCL', 'R4' ), >> ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', >> 'R9')] ] Hmm, looking at your New_list you actually want to sort on 3 "indexes", on 1 then 0 then 2. So change the key= part from before to key=operator.itemgetter(1,0,2) and it will match your New_list perfectly. Greets Sander From sander.sweers at gmail.com Wed Mar 30 00:14:34 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 30 Mar 2011 00:14:34 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: 2011/3/29 Rafael Dur?n Casta?eda : > And more pythonic, I think I don't agree :-). I think itemgetter from the operator module is more flexible, readable and elegant than using a lamda. How would you sort on the first and last item with lambda? Greets Sander From japhy at pearachute.com Tue Mar 29 15:44:46 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Tue, 29 Mar 2011 09:44:46 -0400 Subject: [Tutor] server used in python In-Reply-To: References: Message-ID: I think tornado (http://tornadoweb.org) is one of the easiest server / frameworks to learn and work with. On Tue, Mar 29, 2011 at 4:21 AM, Alan Gauld wrote: > > "ema francis" wrote > >> I am learnning python for ?3 months from now. I wanted to know how and >> what >> *server* is used in python web development?Looking for your help .... > > Python is "blessed" with very many web development frameworks. > For basic CGI programming you can use the basic weeb server > that comes with Python. For deployment Apache or any other > deployment scale server will do. > > If you are using the more complex frameworks they will have their own > development/deployment recomendations, so it all depends on what > framework you want to use. Everything from CherryPy to Zope or Plone... > Your choice really. > > There is a good set of documents in the Python webn site that > discuss the various web frameworks and options. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rafadurancastaneda at gmail.com Wed Mar 30 00:25:12 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Wed, 30 Mar 2011 00:25:12 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: >From python docs: For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2. Example: >>> list_[1][1:3] ('LOOSEFREIGHT', 'MIXEDLCL') >>> As I said i think my approach is more pythonic, but I'm not absolutely sure. With such approach I don't need importing, I use slicing and you are right, your approach is more flexible and would work on more cases, but in this particular case I still think unnecessary. Maybe someone else could tell us which is the best option. El 30 de marzo de 2011 00:14, Sander Sweers escribi?: > 2011/3/29 Rafael Dur?n Casta?eda : > > And more pythonic, I think > > I don't agree :-). I think itemgetter from the operator module is more > flexible, readable and elegant than using a lamda. How would you sort > on the first and last item with lambda? > > Greets > Sander > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 30 00:30:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Mar 2011 23:30:45 +0100 Subject: [Tutor] Grouping based on attributes of elements in a List References: Message-ID: "Sander Sweers" wrote > flexible, readable and elegant than using a lamda. How would you > sort > on the first and last item with lambda? Wouldn't you just return a tuple of the two elements? Or am I missing something having jumped into the middle of the thread... Alan G. From breamoreboy at yahoo.co.uk Wed Mar 30 00:38:21 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Tue, 29 Mar 2011 23:38:21 +0100 Subject: [Tutor] String formatting question. In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 29/03/2011 20:41, Prasad, Ramit wrote: > Is there a difference (or preference) between using the following? > "%s %d" % (var,num) > VERSUS > "{0} {1}".format(var,num) > > > Ramit > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From Python 2.7.1 docs at http://docs.python.org/tutorial/inputoutput.html "Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.". From sander.sweers at gmail.com Wed Mar 30 00:52:54 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 30 Mar 2011 00:52:54 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: On 30 March 2011 00:30, Alan Gauld wrote: > Wouldn't you just return a tuple of the two elements? > > Or am I missing something having jumped into the middle of the thread... Ah yes, you are correct. But imo reading "key=lambda l: (l[1], l[0], l[2])" (which would be needed to sort how the OP wanted) hurts my eyes ;-). Anyway, both options will work fine for the OP. Greets Sander From modulok at gmail.com Wed Mar 30 02:09:09 2011 From: modulok at gmail.com (Modulok) Date: Tue, 29 Mar 2011 18:09:09 -0600 Subject: [Tutor] String formatting question. In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Message-ID: For simple strings I use the "%s" % foo version, for more complex stuff I use the .format() method. I find it easier to control spacing and alignments with the .format() method, but that's just me. -Modulok- On 3/29/11, Blockheads Oi Oi wrote: > On 29/03/2011 20:41, Prasad, Ramit wrote: >> Is there a difference (or preference) between using the following? >> "%s %d" % (var,num) >> VERSUS >> "{0} {1}".format(var,num) >> >> >> Ramit >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > From Python 2.7.1 docs at > http://docs.python.org/tutorial/inputoutput.html "Since str.format() is > quite new, a lot of Python code still uses the % operator. However, > because this old style of formatting will eventually be removed from the > language, str.format() should generally be used.". > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From andres at chandia.net Wed Mar 30 02:21:31 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 30 Mar 2011 02:21:31 +0200 Subject: [Tutor] (no subject) Message-ID: I'm new to this list, so hello everybody!. The stuff: I'm working with regexps and this is my line: contents = re.sub("l<\/u>", "le" ,contents) in perl there is a way to reference previous registers, i.e. $text =~ s/(l|L|n|N)<\/u>/$1e/g; So I'm looking for the way to do it in python, obviously this does not works: contents = re.sub("(l|L|n|N)<\/u>", "$1e", contents) Thanks _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From waynejwerner at gmail.com Wed Mar 30 04:25:14 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Mar 2011 21:25:14 -0500 Subject: [Tutor] String formatting question. In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Mar 29, 2011 at 2:41 PM, Prasad, Ramit wrote: > Is there a difference (or preference) between using the following? > "%s %d" % (var,num) > VERSUS > "{0} {1}".format(var,num) > Practically there's no difference. In reality (and under the hood) there are more differences, some of which are subtle. For instance, in the first example, var = 3, num = 'hi' will error, while with .format, it won't. If you are writing code that should be backwards compatible, pre-2.6, then you should use the % formatting. My personal preference is to use .format() as it (usually) feels more elegant: ("{0} "*8+"{1}").format("na", "batman") vs: "%s %s" % ("na" * 8, "batman") And named arguments: "Name: {name}\nAddress: {address}".format(name="Bob", address="123 Castle Auuurrggh") vs "Name: %(name)\nAddress: %(address)" % {"name": "Bob", "address", "123 Castle Auurgh") But when I'm dealing with floating point, especially if it's a simple output value, I will usually use % formatting: "Money left: %8.2f" % (money,) vs. "Money Left: {0:8.2f)".format(money) Of course, it's best to pick a style and stick to it - having something like this: print "Name: %s" % (name) print "Address: {address}".format(address=street) is bad enough, but... print "This is %s {0}".format("horrible") % ("just") My recommendation would be to use what feels most natural to you. I think I read somewhere that % formatting is so ingrained that even though the .format() method is intended to replace it, it's probably going to stick around for a while. But if you want to be on the safe side, you can always just use .format() - it certainly won't hurt anything, and the fact that it says "format" is more explicit. If you didn't know Python, you would know that "{0} {1} {2}".format(3,2,1) is doing some type of formatting, and since "Explicit is better than implicit."*, that should be a good thing. HTH, Wayne * see: import this this.s.encode('rot13').split('\n')[3] -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 30 08:55:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Mar 2011 07:55:45 +0100 Subject: [Tutor] Regex question References: Message-ID: ""Andr?s Chand?a"" wrote > I'm new to this list, so hello everybody!. Hi, welcome to the list. Please do not use reply to start a new thread it confuses threaded readers and may mean you message will not be seen. Also please supply a meaningful subject (as above) so we can decide if it looks like something we can answer! These will help you maximise the replies. Also, although not relevant here, please include the full text of any error messages and the Python version and OS you are using (2 or 3 etc). Basically anything that helps us understand the context. > in perl there is a way to reference previous registers, > $text =~ s/(l|L|n|N)<\/u>/$1e/g; > I'm looking for the way to do it in python It is possible but I'll let some of the more regex literate users tell you how :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rafadurancastaneda at gmail.com Wed Mar 30 09:13:59 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Wed, 30 Mar 2011 09:13:59 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List In-Reply-To: References: Message-ID: You are right, lambda lis: lis[1:3] would be more readable 2011/3/30 Sander Sweers > On 30 March 2011 00:30, Alan Gauld wrote: > > Wouldn't you just return a tuple of the two elements? > > > > Or am I missing something having jumped into the middle of the thread... > > Ah yes, you are correct. But imo reading "key=lambda l: (l[1], l[0], > l[2])" (which would be needed to sort how the OP wanted) hurts my eyes > ;-). Anyway, both options will work fine for the OP. > > Greets > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Mar 30 09:35:43 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Mar 2011 09:35:43 +0200 Subject: [Tutor] Grouping based on attributes of elements in a List References: Message-ID: ranjan das wrote: > I have the following list > > List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL', > 'R9'), > ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), > ('G1', > 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] > > > now I want to group this elements of List first by index [1] that is (CFS > and LOOSEFREIGHT ) together and for those elements which are grouped > together for LOOSEFREIGHT, i want to further divide them into different > groups based on index[2] that is (LCL or MIXEDLCL) > > > So essentially i want them grouped into different lists and my solution > should be of the form > > New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ), > ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ), > ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT', > 'MIXEDLCL', 'R9')] ] > > How do I do it? > > I managed to do divide them into different lists based on index [1] > however > I was not able to further divide them based on index [2] > > Any help is appreciated Assuming you have a function def group_list(items, key): # ... that takes a list and a function to extract the key you can apply that recursively first on the initial list, then on all partial lists def group_recursive(items, keys): if not keys: return items firstkey = keys[0] rest = keys[1:] items = group_list(items, firstkey) if rest: return [group_recursive(item, rest) for item in items] return items if __name__ == "__main__": from operator import itemgetter import json items = [ ('G1', 'CFS', 'FCL', 'R1'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), ('G4', 'CFS', 'FCL', 'R10'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ] groups = group_recursive(items, [itemgetter(1), itemgetter(2)]) print json.dumps(groups, indent=2) One way to implement group_list() is to sort the items and then use itertools.groupby() to create the sublists. Another is to put the items into a dictionary with key(item) as the dict key and a list of items as the value. From steve at alchemy.com Wed Mar 30 09:16:29 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 30 Mar 2011 00:16:29 -0700 Subject: [Tutor] Regex question In-Reply-To: References: Message-ID: <4D92D8CD.8040509@alchemy.com> On 29-Mar-11 23:55, Alan Gauld wrote: > ""Andr?s Chand?a"" wrote >> in perl there is a way to reference previous registers, >> $text =~ s/(l|L|n|N)<\/u>/$1e/g; > >> I'm looking for the way to do it in python If you're using just a straight call to re.sub(), it works like this: text = re.sub(r'(l|L|n|N)', '\1e', text) You use \1, \2, etc. for backreferences just like all the other regex-based editors do (Perl's more of an exception than the rule there). Alternatively, you can pre-compile the regular expression into an object: pattern = re.compile(r'(l|L|n|N)') and then substitute by calling its sub() method: text = pattern.sub('\1e', text) -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From kushal.kumaran+python at gmail.com Wed Mar 30 09:46:21 2011 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Wed, 30 Mar 2011 13:16:21 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: 2011/3/30 "Andr?s Chand?a" : > > > I'm new to this list, so hello everybody!. > Hello Andr?s > The stuff: > > I'm working with > regexps and this is my line: > > contents = re.sub("l<\/u>", > "le" ,contents) > > in perl there is a way to reference previous registers, > i.e. > > $text =~ s/(l|L|n|N)<\/u>/$1e/g; > > So I'm looking for > the way to do it in python, obviously this does not works: > > contents = > re.sub("(l|L|n|N)<\/u>", "$1e", contents) > You will use \1 for the backreference. The documentation of the re module (http://docs.python.org/library/re.html#re.sub) has an example. Also note the use of raw strings (r'...') to avoid having to escape the backslash with another backslash. -- regards, kushal From carlarjenkins at yahoo.com Wed Mar 30 16:26:22 2011 From: carlarjenkins at yahoo.com (Carla Jenkins) Date: Wed, 30 Mar 2011 07:26:22 -0700 (PDT) Subject: [Tutor] Trajectory Syntax Error Message-ID: <140415.12722.qm@web31506.mail.mud.yahoo.com> I am new to Python learnig for a class. When I try using trajectory I receive an error. Here is the code: def logistic(x): return 4*x*(1-x) ds_logistic11=trajectory(logistic,0.11) SyntaxError: invalid syntax Sincerely, Carla Jenkins From emile at fenx.com Wed Mar 30 17:05:56 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 30 Mar 2011 08:05:56 -0700 Subject: [Tutor] Trajectory Syntax Error In-Reply-To: <140415.12722.qm@web31506.mail.mud.yahoo.com> References: <140415.12722.qm@web31506.mail.mud.yahoo.com> Message-ID: On 3/30/2011 7:26 AM Carla Jenkins said... > I am new to Python learnig for a class. When I try using trajectory I receive an error. Here is the code: > > def logistic(x): > return 4*x*(1-x) > ds_logistic11=trajectory(logistic,0.11) > SyntaxError: invalid syntax > Hi Carla, Be sure to copy and paste in exactly the code that results in the error. As you can see below when I use your example there is no error. This makes it hard as we now have to guess what you may have done. I do see one issue -- when you intend to execute your function you need to enclose the parameters in parens. eg, use logistic(0.11) Emile ActivePython 2.6.1.1 (ActiveState Software Inc.) based on Python 2.6.1 (r261:67515, Dec 5 2008, 13:58:38) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def logistic(x): ... return 4*x*(1-x) ... >>> def trajectory(a,b):pass ... >>> ds_logistic11=trajectory(logistic,0.11) >>> From andres at chandia.net Wed Mar 30 17:21:02 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 30 Mar 2011 17:21:02 +0200 Subject: [Tutor] Regex question In-Reply-To: References: Message-ID: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> Thanks Kushal and Steve. I think it works,a I say "I think" because at the results I got a strange character instead of the letter that should appear this is my regexp: contents = re.sub(r'(|)(l|L|n|N|t|T)(|)', '\2\'' ,contents) this is my input file content: lomo? nomo? tomo? Lomo? Nomo? Tomo? nomo? tomo this is my output file content 'omo? 'omo? 'omo? 'omo? 'omo? 'omo? 'omo? 'omo? at to head of the file I got: #!/usr/bin/env python # -*- coding: utf-8 -*- I tried changing the coding to iso-8859-15, but nothing, for sure you know the reason for this, can you share it with this poor newbee" Thanks a lot!! On Wed, March 30, 2011 09:46, Kushal Kumaran wrote: 2011/3/30 "Andr??s Chand??a" : > > > I'm new to this list, so hello everybody!. > Hello Andr??s > The stuff: > > I'm working with > regexps and this is my line: > > contents = re.sub("l<\/u>", > "le" ,contents) > > in perl there is a way to reference previous registers, > i.e. > > $text =~ s/(l|L|n|N)<\/u>/$1e/g; > > So I'm looking for > the way to do it in python, obviously this does not works: > > contents = > re.sub("(l|L|n|N)<\/u>", "$1e", contents) > You will use \1 for the backreference. The documentation of the re module (http://docs.python.org/library/re.html#re.sub) has an example. Also note the use of raw strings (r'...') to avoid having to escape the backslash with another backslash. _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From steve at alchemy.com Wed Mar 30 17:27:25 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 30 Mar 2011 08:27:25 -0700 Subject: [Tutor] Regex question In-Reply-To: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> References: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> Message-ID: <4D934BDD.6020404@alchemy.com> On 30-Mar-11 08:21, "Andr?s Chand?a" wrote: > > > Thanks Kushal and Steve. > I think it works,a I say "I think" because at the > results I got a strange character instead of the letter that should appear > > this is > my regexp: > > contents = re.sub(r'(|)(l|L|n|N|t|T)(|)', '\2\'' ,contents) Remember that \2 in a string means the ASCII character with the code 002. You need to escape this with an extra backslash: '\\2\'' Although it would be more convenient to switch to double quotes to make the inclusion of the literal single quote easier: "\\2'" How does that work? As the string is being "built", the \\ is interpreted as a literal backslash, so the actual characters in the string's value end up being: \2' THAT is what is then passed into the sub() function, where \2 means to replace the second match. This can be yet simpler by using raw strings: r"\2'" Since in raw strings, backslashes do almost nothing special at all, so you don't need to double them. I should have thought of that when sending my original answer to your question. Sorry I overlooked it. --steve -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From andres at chandia.net Wed Mar 30 18:49:39 2011 From: andres at chandia.net (=?iso-8859-1?Q?=22Andr=E9s_Chand=EDa=22?=) Date: Wed, 30 Mar 2011 18:49:39 +0200 Subject: [Tutor] Regex question In-Reply-To: <4D934BDD.6020404@alchemy.com> References: <9f91f88168c63ea117a66e3717b9f734.squirrel@mail.chandia.net> <4D934BDD.6020404@alchemy.com> Message-ID: <0ff941bcdca92c74cb761361229dc99c.squirrel@mail.chandia.net> Thanks Steve, your are, from now on, my guru.... this is the final version, the good one! contents = re.sub(r'(|)(l|L|n|N|t|T)(|)', r"\2'" ,contents) On Wed, March 30, 2011 17:27, Steve Willoughby wrote: On 30-Mar-11 08:21, "Andr?s Chand?a" wrote: > > > Thanks Kushal and Steve. > I think it works,a I say "I think" because at the > results I got a strange character instead of the letter that should appear > > this is > my regexp: > > contents = re.sub(r'(|)(l|L|n|N|t|T)(|)', '\2\'' ,contents) Remember that \2 in a string means the ASCII character with the code 002. You need to escape this with an extra backslash: '\\2\'' Although it would be more convenient to switch to double quotes to make the inclusion of the literal single quote easier: "\\2'" How does that work? As the string is being "built", the \\ is interpreted as a literal backslash, so the actual characters in the string's value end up being: \2' THAT is what is then passed into the sub() function, where \2 means to replace the second match. This can be yet simpler by using raw strings: r"\2'" Since in raw strings, backslashes do almost nothing special at all, so you don't need to double them. I should have thought of that when sending my original answer to your question. Sorry I overlooked it. --steve _______________________ ????????????andr?s chand?a P No imprima innecesariamente. ?Cuide el medio ambiente! From alan.gauld at btinternet.com Wed Mar 30 19:07:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Mar 2011 18:07:45 +0100 Subject: [Tutor] Trajectory Syntax Error References: <140415.12722.qm@web31506.mail.mud.yahoo.com> Message-ID: "Carla Jenkins" wrote > When I try using trajectory I receive an error. What is trajectory? Its not a standard Python function so we can't be too helpful in fixing errors unless we know more about it. > Here is the code: > > def logistic(x): > return 4*x*(1-x) This is OK so far... > ds_logistic11=trajectory(logistic,0.11) Now this passes your function and a value to trajectory. That could be right if trajectory looks like: def trajectory(f,v): return f(v) but if trajectory looks like: def trajectory(v): return v Then your code needs some extra parens adding. > SyntaxError: invalid syntax But even then the error would be different so can you paste the complete error message so that we can see exactly what it says? But well done for trying to do the code yourself first, we do appreciate you taking that effort. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From david.crisp at gmail.com Thu Mar 31 05:41:38 2011 From: david.crisp at gmail.com (David Crisp) Date: Thu, 31 Mar 2011 14:41:38 +1100 Subject: [Tutor] Converting a numpy matrix to a numpy array Message-ID: Hello, I have a very simple question / problem I need answered.? The problem is imnot entirely sure of the correct terminology and langauge to use to describe it.? (One of the reasons im using this miling list) I have a 2d matrix representing the X the Y and the Z value of a point.? I wish to convert that matrix to an array.??? What is a good way of doing so? Eg: Matrix ?012345 0xooooo 1xooooo 2oxxxxx 3oooooo 4ooooox 5ooooox I want to convert that to a 2d array which looks like: 0,0,x 0,1,o 0,2,o 0,3,o 0,4,o 0,5,o ....... 5,4,o 5,5,o I am pretty sure it is simple.? I'm just having a brain fade. Regards, David From bjameshunter at gmail.com Thu Mar 31 10:38:11 2011 From: bjameshunter at gmail.com (Ben Hunter) Date: Thu, 31 Mar 2011 01:38:11 -0700 Subject: [Tutor] Data frame packages Message-ID: Is anybody out there familiar with data frame modules for python that will allow me to read a CSV in a similar way that R does? pydataframe and DataFrame have both befuddled me. One requires a special stripe of R that I don't think is available on windows and the other is either very buggy or I've put it in the wrong directory / installed incorrectly. Sorry for the vague question - just taking the pulse. I haven't seen any chatter about this on this mailing list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 31 16:25:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 01:25:19 +1100 Subject: [Tutor] Converting a numpy matrix to a numpy array In-Reply-To: References: Message-ID: <4D948ECF.9000900@pearwood.info> David Crisp wrote: > I have a 2d matrix representing the X the Y and the Z value of a > point. I wish to convert that matrix to an array. What is a good > way of doing so? > > Eg: > Matrix > 012345 > 0xooooo > 1xooooo > 2oxxxxx > 3oooooo > 4ooooox > 5ooooox It's not clear what this matrix actually is. Is this from a text file? What are the X's and O's (letter o)? Are they meant to be place-holders for something else, or literally letter X and letter O? If placeholders, what are they placeholders for? And if literally X and O, what are you expecting to do with them in numpy, which expects numeric data? > I want to convert that to a 2d array which looks like: > 0,0,x > 0,1,o > 0,2,o > 0,3,o > 0,4,o > 0,5,o > ....... > 5,4,o > 5,5,o What you are describing is not a two dimensional array. It is a one-dimensional list, each item of which includes 2D coordinates as explicit data. You almost certainly do not want that! Working with numpy, you want to use a numpy two dimensional array that looks something like this: [ [ x o o o o o ] [ x o o o o o ] [ o x x x x x ] [ o o o o o o ] [ o o o o o x ] [ o o o o o x ] ] where the coordinates are implied. I have borrowed Python list syntax [] for the array. Each row is a [...] and the columns are read down the rows. Unfortunately, I'm not using my usual computer, so I don't have access to numpy at the moment. More detail will have to follow later. Regards, -- Steven From steve at pearwood.info Thu Mar 31 16:27:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 01:27:36 +1100 Subject: [Tutor] Data frame packages In-Reply-To: References: Message-ID: <4D948F58.9080701@pearwood.info> Ben Hunter wrote: > Is anybody out there familiar with data frame modules for python that will > allow me to read a CSV in a similar way that R does? pydataframe and > DataFrame have both befuddled me. One requires a special stripe of R that I > don't think is available on windows and the other is either very buggy or > I've put it in the wrong directory / installed incorrectly. Sorry for the > vague question - just taking the pulse. I haven't seen any chatter about > this on this mailing list. Perhaps if you give an example of what R does with CSV files, and explain what "data frame" means in this context, we may be able to help. Otherwise, have you tried googling "Python data frame"? -- Steven From __peter__ at web.de Thu Mar 31 17:04:50 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Mar 2011 17:04:50 +0200 Subject: [Tutor] Converting a numpy matrix to a numpy array References: Message-ID: David Crisp wrote: > Hello, > > I have a very simple question / problem I need answered. The problem > is imnot entirely sure of the correct terminology and langauge to use > to describe it. (One of the reasons im using this miling list) > > I have a 2d matrix representing the X the Y and the Z value of a > point. I wish to convert that matrix to an array. What is a good > way of doing so? > > Eg: > Matrix > 012345 > 0xooooo > 1xooooo > 2oxxxxx > 3oooooo > 4ooooox > 5ooooox > > > I want to convert that to a 2d array which looks like: > 0,0,x > 0,1,o > 0,2,o > 0,3,o > 0,4,o > 0,5,o > ....... > 5,4,o > 5,5,o > > I am pretty sure it is simple. I'm just having a brain fade. Using basic numpy: >>> import numpy as np >>> a = np.array(list("xoo" ... "oxx" ... "oxo")).reshape(3,3) >>> a array([['x', 'o', 'o'], ['o', 'x', 'x'], ['o', 'x', 'o']], dtype='|S1') >>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()]).transpose() array([['0', '0', 'x'], ['0', '1', 'o'], ['0', '2', 'o'], ['1', '0', 'o'], ['1', '1', 'x'], ['1', '2', 'x'], ['2', '0', 'o'], ['2', '1', 'x'], ['2', '2', 'o']], dtype='|S8') >>> np.array([np.arange(9)//3, np.arange(9)%3, (a=="x").flatten()]).transpose() array([[0, 0, 1], [0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 1, 1], [1, 2, 1], [2, 0, 0], [2, 1, 1], [2, 2, 0]]) >>> np.array([np.arange(9)//3, np.arange(9)%3, a.flatten()], dtype=object).transpose() array([[0, 0, x], [0, 1, o], [0, 2, o], [1, 0, o], [1, 1, x], [1, 2, x], [2, 0, o], [2, 1, x], [2, 2, o]], dtype=object) If that's not good enough you may also ask on the numpy mailing list. From breamoreboy at yahoo.co.uk Thu Mar 31 17:10:03 2011 From: breamoreboy at yahoo.co.uk (Blockheads Oi Oi) Date: Thu, 31 Mar 2011 16:10:03 +0100 Subject: [Tutor] Data frame packages In-Reply-To: References: Message-ID: On 31/03/2011 09:38, Ben Hunter wrote: > Is anybody out there familiar with data frame modules for python that > will allow me to read a CSV in a similar way that R does? pydataframe > and DataFrame have both befuddled me. One requires a special stripe of R > that I don't think is available on windows and the other is either very > buggy or I've put it in the wrong directory / installed incorrectly. > Sorry for the vague question - just taking the pulse. I haven't seen any > chatter about this on this mailing list. > > What are you trying to achieve? Can you simply read the data with the standard library csv module and manipulate it to your needs? What makes you say that the code is buggy, have you examples of what you tried and where it was wrong? Did you install with easy_install or run setup.py? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Regards. Mark L. From eire1130 at gmail.com Thu Mar 31 17:17:19 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 31 Mar 2011 11:17:19 -0400 Subject: [Tutor] Data frame packages In-Reply-To: References: Message-ID: On Thu, Mar 31, 2011 at 11:10 AM, Blockheads Oi Oi wrote: > On 31/03/2011 09:38, Ben Hunter wrote: > >> Is anybody out there familiar with data frame modules for python that >> will allow me to read a CSV in a similar way that R does? pydataframe >> and DataFrame have both befuddled me. One requires a special stripe of R >> that I don't think is available on windows and the other is either very >> buggy or I've put it in the wrong directory / installed incorrectly. >> Sorry for the vague question - just taking the pulse. I haven't seen any >> chatter about this on this mailing list. >> >> >> > What are you trying to achieve? Can you simply read the data with the > standard library csv module and manipulate it to your needs? What makes > you say that the code is buggy, have you examples of what you tried and > where it was wrong? Did you install with easy_install or run setup.py? > > > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Regards. > > Mark L. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'm not familiar with it, but what about http://rpy.sourceforge.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Mar 31 17:23:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 01 Apr 2011 02:23:18 +1100 Subject: [Tutor] String formatting question. In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4D949C66.9010209@pearwood.info> Wayne Werner wrote: > On Tue, Mar 29, 2011 at 2:41 PM, Prasad, Ramit wrote: > >> Is there a difference (or preference) between using the following? >> "%s %d" % (var,num) >> VERSUS >> "{0} {1}".format(var,num) >> > > Practically there's no difference. In reality (and under the hood) there are > more differences, some of which are subtle. On the contrary, the two code snippets *explicitly* do different things, about as different as: str(var) + str(int(num)) vs. str(var) + str(num) The first example expects an arbitrary object and a number on the right hand side of the % operator. The second example expects two arbitrary objects. Now, I see from your next comment that you realise this: > For instance, in the first example, var = 3, num = 'hi' will error, while > with .format, it won't. but you don't make it clear that that's because the two pieces of code ask for two different things, not because of a difference between % and format(). To be consistent, you would compare: "%s %s" % (var,num) vs. "{0} {1}".format(var,num) or possibly: "%s %d" % (var,num) "{0} {1:d}".format(var,num) # I think, I'm stuck here with Python 2.4 # and can't check it. Any other differences? Yes, plenty. % formatting and .format() don't just have different syntax, they have different capabilities. format() has more power, but that power comes at the cost of being slightly slower and being more verbose to write. > My personal preference is to use .format() as it (usually) feels more > elegant: > > ("{0} "*8+"{1}").format("na", "batman") > > vs: > > "%s %s" % ("na" * 8, "batman") They do different things. The first repeats "na" separated by spaces; the second has "nanana....na" without spaces. In any case, we differ in our opinion of elegant, because I feel the two solutions are equally elegant. > And named arguments: > > "Name: {name}\nAddress: {address}".format(name="Bob", address="123 Castle > Auuurrggh") > > vs > > "Name: %(name)\nAddress: %(address)" % {"name": "Bob", "address", "123 > Castle Auurgh") The second example will not work, because you have forgotten the type code. That's an advantage of % formatting: if you forget the type code, you get an error instead of a default, likely incorrect, type. > My recommendation would be to use what feels most natural to you. I think I > read somewhere that % formatting is so ingrained that even though the > .format() method is intended to replace it, it's probably going to stick > around for a while. I should think so... there are plenty of ex-C programmers whose attitude is "You can have my % format strings when you pry them from my cold, dead fingers." I'm not a C programmer, and I agree with them. -- Steven From bgailer at gmail.com Thu Mar 31 18:46:04 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 31 Mar 2011 11:46:04 -0500 Subject: [Tutor] String formatting question. In-Reply-To: <4D949C66.9010209@pearwood.info> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> <4D949C66.9010209@pearwood.info> Message-ID: <4D94AFCC.3000909@gmail.com> IMHO % formatting is the easiest to use and understand. I am sorry that it has been slated for removal. -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at alchemy.com Thu Mar 31 18:51:59 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 31 Mar 2011 09:51:59 -0700 Subject: [Tutor] String formatting question. In-Reply-To: <4D94AFCC.3000909@gmail.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9460947C@EMARC112VS01.exchad.jpmchase.net> <4D949C66.9010209@pearwood.info> <4D94AFCC.3000909@gmail.com> Message-ID: <4D94B12F.1010301@alchemy.com> On 31-Mar-11 09:46, bob gailer wrote: > IMHO % formatting is the easiest to use and understand. > I am sorry that it has been slated for removal. I had the same reaction, but I think it was mostly because of my long background as a C programmer, since it's essentially the equivalent of printf() formatting. Just heavily ingrained in my brain. However, since the more recent Python 2 versions have supported str.format(), and anticipating their removal from Python 3, I have started gravitating more to them, and I have to admit they're more powerful and probably a good evolutionary step to take. Especially so if your formats are configurable or generated by code which may want to reorder the values. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From bjameshunter at gmail.com Thu Mar 31 20:26:39 2011 From: bjameshunter at gmail.com (Ben Hunter) Date: Thu, 31 Mar 2011 11:26:39 -0700 Subject: [Tutor] Data frame packages In-Reply-To: References: Message-ID: I appreciate all the responses and apologize for not being more detailed. An R data frame is a tightly grouped array of vectors of the same length. Each vector is all the same datatype, I believe, but you can read all types of data into the same variable. The benefit is being able to quickly subset, stack and such (or 'melt' and 'cast' in R vernacular) according to any of your qualitative variables (or 'factors'). As someone pretty familiar with R and quite a newbie to python, I'm wary of insulting anybody's intelligence by describing what to me is effectively the default data format my most familiar language. The following is some brief R code if you're curious about how it works. d <- read.csv(filename, header = TRUE, sep = ',') #this reads the table. '<-' is the assignment operator d[ , 'column.name'] # this references a column name. This same syntax can be used to reference all rows (index is put left of the comma) and columns in any order. The data frame then allows you to quickly declare new fields as functions of other fields. newVar <- d[ ,'column.name'] + d[ ,'another.column'] d$newVar <- newVar # attaches newVar to the rightmost column of 'd' At any rate, I finally got pydataframe to work, but had to go from Python 2.6 to 2.5. pydataframe has a bug for Windows that the author points out. Line 127 in 'parsers.py' should be changed from: columns = list(itertools.izip_longest(*split_lines ,fillvalue = na_text)) to: columns = list(itertools.izip_longest(list(*split_lines),fillvalue = na_text)) I don't know exactly what I did, but the module would not load until I did that. I know itertools.izip_longest requires 2 arguments before fillvalue, so I guess that did it. It's a handy way to handle alpha-numeric data. My problem with the csv module was that it interpreted all numbers as strings. Thanks again. On Thu, Mar 31, 2011 at 8:17 AM, James Reynolds wrote: > > > On Thu, Mar 31, 2011 at 11:10 AM, Blockheads Oi Oi < > breamoreboy at yahoo.co.uk> wrote: > >> On 31/03/2011 09:38, Ben Hunter wrote: >> >>> Is anybody out there familiar with data frame modules for python that >>> will allow me to read a CSV in a similar way that R does? pydataframe >>> and DataFrame have both befuddled me. One requires a special stripe of R >>> that I don't think is available on windows and the other is either very >>> buggy or I've put it in the wrong directory / installed incorrectly. >>> Sorry for the vague question - just taking the pulse. I haven't seen any >>> chatter about this on this mailing list. >>> >>> >>> >> What are you trying to achieve? Can you simply read the data with the >> standard library csv module and manipulate it to your needs? What makes >> you say that the code is buggy, have you examples of what you tried and >> where it was wrong? Did you install with easy_install or run setup.py? >> >> >> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> Regards. >> >> Mark L. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > > > > > > > > > > > > I'm not familiar with it, but what about http://rpy.sourceforge.net/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmchase.com Thu Mar 31 20:07:25 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 31 Mar 2011 14:07:25 -0400 Subject: [Tutor] Importing sub modules Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> Hi everyone, I was wondering if there is a difference in >>>import os >>>os.path.join(string1,string2) AND >>>import os.path >>>os.path.join(string1,string2) The only difference that I could think of is if the os module does not get loaded on the second example. I am not sure if it does. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From emile at fenx.com Thu Mar 31 22:17:08 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 31 Mar 2011 13:17:08 -0700 Subject: [Tutor] Importing sub modules In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> Message-ID: On 3/31/2011 11:07 AM Prasad, Ramit said... > Hi everyone, > I was wondering if there is a difference in > >>>> import os >>>> os.path.join(string1,string2) > AND >>>> import os.path >>>> os.path.join(string1,string2) > > A quick test shows they're the same: ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os as os1 >>> import os.path >>> os1.path is os.path True >>> Although I'm not sure what to make of the joins What are you trying to do? Emile From easywebs4u at gmail.com Thu Mar 31 22:44:53 2011 From: easywebs4u at gmail.com (Greg Richards) Date: Thu, 31 Mar 2011 15:44:53 -0500 Subject: [Tutor] (no subject) Message-ID: http%3A%2F%2Fwww%2Eeasy%2Dsofa%2Epl%2F%2Fimages%2Ffriends%2Ehtml From ramit.prasad at jpmchase.com Thu Mar 31 23:11:50 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 31 Mar 2011 17:11:50 -0400 Subject: [Tutor] Importing sub modules In-Reply-To: References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> The joins are really just random calls. I was just curious if importing os.path could avoid any reading/overhead that might occur by importing os. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Emile van Sebille Sent: Thursday, March 31, 2011 3:17 PM To: tutor at python.org Subject: Re: [Tutor] Importing sub modules On 3/31/2011 11:07 AM Prasad, Ramit said... > Hi everyone, > I was wondering if there is a difference in > >>>> import os >>>> os.path.join(string1,string2) > AND >>>> import os.path >>>> os.path.join(string1,string2) > > A quick test shows they're the same: ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os as os1 >>> import os.path >>> os1.path is os.path True >>> Although I'm not sure what to make of the joins What are you trying to do? Emile _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. From eire1130 at gmail.com Thu Mar 31 23:53:24 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Thu, 31 Mar 2011 21:53:24 +0000 Subject: [Tutor] Importing sub modules In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net><0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> Message-ID: <1515192433-1301608406-cardhu_decombobulator_blackberry.rim.net-909595448-@bda346.bisx.prod.on.blackberry> You could just use from os import path and use it like path.xxx I don't know know if it saves on overhead or not. In any event, you shouldn't be worrying about something like overhead until after your base prorgram is written. Generally if all I use is path, for example, I use from import. If not I just import the enchilada Sent from my Verizon Wireless BlackBerry -----Original Message----- From: "Prasad, Ramit" Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Thu, 31 Mar 2011 17:11:50 To: 'Emile van Sebille'; 'tutor at python.org' Subject: Re: [Tutor] Importing sub modules The joins are really just random calls. I was just curious if importing os.path could avoid any reading/overhead that might occur by importing os. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -----Original Message----- From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Emile van Sebille Sent: Thursday, March 31, 2011 3:17 PM To: tutor at python.org Subject: Re: [Tutor] Importing sub modules On 3/31/2011 11:07 AM Prasad, Ramit said... > Hi everyone, > I was wondering if there is a difference in > >>>> import os >>>> os.path.join(string1,string2) > AND >>>> import os.path >>>> os.path.join(string1,string2) > > A quick test shows they're the same: ActivePython 2.6.6.15 (ActiveState Software Inc.) based on Python 2.6.6 (r266:84292, Aug 24 2010, 16:01:11) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os as os1 >>> import os.path >>> os1.path is os.path True >>> Although I'm not sure what to make of the joins What are you trying to do? Emile _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmchase.com Thu Mar 31 23:59:51 2011 From: ramit.prasad at jpmchase.com (Prasad, Ramit) Date: Thu, 31 Mar 2011 17:59:51 -0400 Subject: [Tutor] Importing sub modules In-Reply-To: <1515192433-1301608406-cardhu_decombobulator_blackberry.rim.net-909595448-@bda346.bisx.prod.on.blackberry> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D9482150E@EMARC112VS01.exchad.jpmchase.net><0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821A9A@EMARC112VS01.exchad.jpmchase.net> <1515192433-1301608406-cardhu_decombobulator_blackberry.rim.net-909595448-@bda346.bisx.prod.on.blackberry> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2D94821B9F@EMARC112VS01.exchad.jpmchase.net> >> In any event, you shouldn't be worrying about something like overhead until after your base prorgram is written. Base programs are written. I was just looking into insight about the mechanics behind importing :) For instance, do these libraries normally lazy load? If you have mod1.mod2 and mod1.mod3 and import mod1 does it usually also internally load mod2/3? import mod1.mod2 (or do from mod1 import mod2) does it avoid any loading of mod3 or does it do that as part of loading mod1? I suppose this mailing list may not be the correct place to be asking this question since it is geared towards beginner questions. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities.