Re: [Tutor] continuous running of a method
On Wed, Aug 25, 2010 at 12:56 AM, Greg Bair wrote: > > It's not that the value doesn't lie between the mentioned range. > > What I'm doing is randomly fetching an item from a list of dicts > (multi-dimensional ones from a JSON response) and accessing a value from it, > but not every item has the key I'm looking for (can't change that). I > suppose what I could do to not randomize every time is to iterate through > the list and create a new list that only contains dicts that have that key, > then get a random one from that. I suppose that would be more efficient. > > Any thoughts? > this sounds like a good idea. Either the filter() function or a list comprehension can filter out the dicts you want easily. My guess is the list comprehension is somewhat faster, but I could be wrong. And it doesn't sound like performance is a very big deal here anyway, so take your pick. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retriving previous user inputs in a gui
"Karim" wrote Is there any equivalent to JAVACC in python (or lex yacc) to create grammary for config or format file? Thats kind of what ConfiogParser does - it gives you tools to read/write a config file. If you don't mind the data not being human readable you could also use the shelve module which simulates a dictionary in a file. There are lots of options. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such fileor directory
"Carter Danforth" wrote Anyhow, I can't seem to be executing any files in terminal for some reason, in this case the file ex1.py: C:\Users\Carter Danforth\python ex1.py python: can't open file 'ex1.py': [Errno 2] No such file or directory ex1.py is located in "pythonpractice" on my desktop and I've updated the modules, here's the output from sys.path: sys.path (and PYTHONPATH) only affect how imports work within Python, they have no effect on Windows ability to find scripts. To run a script you must do one of the following: 1) CD to the script folder and run Python from there as: > Python myscript.py 2) From anywhere execute Python as > python full\path\to\myscript.py 3) From anywhere execute myscript as > myscript.py For 1,2 PATH must include the Python executable folder For 3 the .py extension must be associated with the Python executable and the folder containing myscript must be in PATH. I'm not sure why I keep getting this error message and why I'm not able to execute any .py files. Any help would be great appreciated. Windows needs to know where the file lives. You could have many files called myscript.py in your file system. PYTHONPATH is used only by Python and only for imports. PATH is used only for executables. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] os.access unreliable?
Hi, Hi I'm using os.access to do a preliminary check to see if I have RW access, but it seems to be unreliable. In a dir for which I have only read access, os.access also says I have write access. This is under Windows 2000. I could of course use a try-except and catch the IOError, but I'd like to know why the code below isn;t working. def isAcccessible(self): if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK): return True else: return False 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@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.access unreliable?
On 25/08/2010 09:28, Albert-Jan Roskam wrote: Hi, Hi I'm using os.access to do a preliminary check to see if I have RW access, but it seems to be unreliable. In a dir for which I have only read access, os.access also says I have write access. This is under Windows 2000. I could of course use a try-except and catch the IOError, but I'd like to know why the code below isn;t working. def isAcccessible(self): if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK): return True else: return False os.access is effectively meaningless under Windows, especially against directories. It only checks the read-only flag (which doesn't mean anything for directories anyway). There is a long-open issue here: http://bugs.python.org/issue2528 which I am half-minded to close although I could be persuaded to pursue it if anyone were interested enough. On the other hand, os.access checks are open to race-conditions in any case, so you might simply be better off with a try-except block as you suggest. If you want more information I can explain further but unless you want to dive into the Windows API and use AccessCheck -- which is what that patch is doing -- then I suggest you use try-except TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] why does this fail
Hello, I have this programm : def remove_letter(letter, strng): """ >>> remove_letter('a', 'apple') 'pple' >>> remove_letter('a', 'banana') 'bnn' >>> remove_letter('z', 'banana') 'banana' >>> remove_letter('i', 'Mississippi') 'Mpp' """ antwoord="" for letter in strng: print letter, strng if letter in strng: print "false" else: print "true" return antwoord x=remove_letter('a', 'apple') print x But now everything is false even a in apple. What is here wrong ? Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.access unreliable?
On Wed, 25 Aug 2010 06:28:47 pm Albert-Jan Roskam wrote: > Hi, > > Hi I'm using os.access to do a preliminary check to see if I have RW > access, but it seems to be unreliable. In a dir for which I have only > read access, os.access also says I have write access. This is under > Windows 2000. I could of course use a try-except and catch the > IOError, but I'd like to know why the code below isn;t working. As a general rule you need to use a try...except block anyway, otherwise your code is vulnerable to race conditions. In a multi-tasking operating system (like just about all OSes these days, including Windows) there is no guarantee that just because you had permission to read the file now you will still have it in a millisecond when you try to open it. Or even that the file will still exist. If you're writing a quick script for dealing with files, you can get away with taking the risk. But for more serious applications, there is no getting away from try...except. In this case, the Fine Manual specifically warns that relying on os.access opens a potential security vulnerability: http://docs.python.org/library/os.html#os.access It also warns that os.access doesn't take into account network file sharing permissions. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
On 25/08/2010 12:00, Roelof Wobben wrote: Hello, I have this programm : def remove_letter(letter, strng): """ >>> remove_letter('a', 'apple') 'pple' >>> remove_letter('a', 'banana') 'bnn' >>> remove_letter('z', 'banana') 'banana' >>> remove_letter('i', 'Mississippi') 'Mpp' """ antwoord="" for letter in strng: print letter, strng if letter in strng: print "false" else: print "true" return antwoord x=remove_letter('a', 'apple') print x But now everything is false even a in apple. What is here wrong ? Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You're rebinding the variable `letter`. It is an input variable for your function but then you use it as the character store while iterating through your string variable `strng`. What your control should look like would be more like for character in strng: if letter == character: print 'false' # this should be true, it is a match just like in your example else: print 'true' I'm assuming this function is just for learning purposes because there's a built-in string function you can use called replace and you'd use it as such `'apple'.replace('a', '')`. PS: Once you've gotten it to work convert it to a list comprehension, they are incredibly useful and a great tool. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.access unreliable?
On 25/08/2010 11:15, Steven D'Aprano wrote: It also warns that os.access doesn't take into account network file sharing permissions. Heh. On Windows it doesn't take into account *any* file sharing permissions :) TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] continuous running of a method
On Wed, 25 Aug 2010 03:25:12 pm Nitin Das wrote: > The problem with this while loop is if your random value doesn't lie > between the mentioned range then ur 100% cpu would be utilized. The > one thing u can do is to sleep for some time lets say 0.5 sec after > every while loop iteration , in this case ur cpu utilization will go > down. Pausing for half a second after each loop is WAY over-kill. Half a millisecond would be more appropriate, and even that is over-cautious. Any modern multi-tasking operating system will ensure than a while loop doesn't kill your computer's responsiveness. A decent operating system will still remain responsive even at 100% CPU usage. Even Windows does that! As I type this, I have about a dozen browser windows open, a music player playing, various text editors, a bittorrent client, and a Python interactive session running this: >>> while 1: ... pass ... (plus a whole heap more). Here are the top 4 entries according to top: % CPUProcess name 96 python2.6 12 Xorg 7 epiphany 1 gtk-gnutella Obviously this adds up to more that 100%. The load average is just 1.31. That's nothing -- a load less than 2 isn't even worth mentioning for a single CPU desktop machine. I don't start to worry until the load exceeds 3 or 4. I don't panic until it gets to 10 :) This is perfectly normal, and nothing to be concerned about. I can barely notice any performance degradation despite the while loop. And of course Python itself remains responsive: type Ctrl-C kills it instantaneously. You might need to worry this if you're writing in a low-level language like C, but in Python? Not unless you do something out of the ordinary, like setting the check interval to a ridiculously high value. You can force Python to give even more time to threads by calling time.sleep(0). Other than that, you're not likely to need to care about this. Just write your code in the most straightforward way and leave the rest to Python and the OS. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
> Date: Wed, 25 Aug 2010 12:27:39 +0200 > From: cwi...@compuscan.co.za > To: tutor@python.org > Subject: Re: [Tutor] why does this fail > > On 25/08/2010 12:00, Roelof Wobben wrote: > > Hello, > > > > I have this programm : > > > > def remove_letter(letter, strng): > > """ > > >>> remove_letter('a', 'apple') > > 'pple' > > >>> remove_letter('a', 'banana') > > 'bnn' > > >>> remove_letter('z', 'banana') > > 'banana' > > >>> remove_letter('i', 'Mississippi') > > 'Mpp' > > """ > > antwoord="" > > for letter in strng: > > print letter, strng > > if letter in strng: > > print "false" > > else: > > print "true" > > return antwoord > > > > x=remove_letter('a', 'apple') > > print x > > > > But now everything is false even a in apple. > > > > What is here wrong ? > > > > Roelof > > > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > You're rebinding the variable `letter`. > It is an input variable for your function but then you use it as the > character store while iterating through your string variable `strng`. > > What your control should look like would be more like > > for character in strng: > if letter == character: > print 'false' # this should be true, it is a match just like in > your example > else: > print 'true' > > I'm assuming this function is just for learning purposes because there's > a built-in string function you can use called replace and you'd use it > as such `'apple'.replace('a', '')`. > > PS: Once you've gotten it to work convert it to a list comprehension, > they are incredibly useful and a great tool. > > -- > Kind Regards, > Christian Witts > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hello Christian. It's for learning purposed but I forget that de module string has built in functions. Thank you for remainding it to me. list comprehistion is q few chapters later in the book so I don't try yet. Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.access unreliable?
Hi Tim and Steven, Thanks a lot for your very useful replies! 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: Tim Golden Cc: tutor@python.org Sent: Wed, August 25, 2010 12:25:13 PM Subject: Re: [Tutor] os.access unreliable? On 25/08/2010 11:15, Steven D'Aprano wrote: > It also warns that os.access doesn't take into account network file > sharing permissions. Heh. On Windows it doesn't take into account *any* file sharing permissions :) TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Function object
Hello again, seems like in my journey to learn Python I have stumbled into another problem regarding understanding a concept- function object. As I said, I do not understand what a function object is, what it does, and what can I do with it? I'm currently reading Think python, but the book is not clear for me. Python is my first programming language. Please, can you give me some examples and if it is possible can you explain in a more beginner orientated way? also if someone has a minute I'm available on google chat, if it's more convenient to explain this way. Thanks so much and I hope I didn't disturb anyone with my questions. I know you probably get this question and others a lot. But please understand, my goal with this email is not to make you angry or something like that, I really like programming and what to learn it but as a beginner I find some concepts hard to understand just by reading. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function object
On 8/25/2010 9:56 AM Daniel said... Hello again, seems like in my journey to learn Python I have stumbled into another problem regarding understanding a concept- function object. As I said, I do not understand what a function object is, what it does, and what can I do with it? I'm currently reading Think python, but the book is not clear for me. Python is my first programming language. Please, can you give me some examples and if it is possible can you explain in a more beginner orientated way? Generally speaking, everything in python is an object. As such, objects have methods and attributes. At a certain level for certain projects, manipulating code objects helps solve problems. Here's a simple example. 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 test(ii): print "my name is %s" % ii.func_name ... >>> def test1(ii): print "my name is %s" % ii.func_name ... >>> def test2(ii): print "double ii is %s-%s" % (ii,ii) ... >>> for funcobj in (test1,test2): funcobj('spam') ... single ii is spam double ii is spam-spam >>>for funcobj in (test1,test2): test(funcobj) ... my name is test1 my name is test2 Once defined, code is an object. try dir(test) on the above. HTH, Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function object
On 8/25/2010 10:56 AM Emile van Sebille said... >>> def test1(ii): print "my name is %s" % ii.func_name ... Oops -- my bad editing s/b or once was: def test1(ii): print "single ii is %s" % ii ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
On 08/25/2010 06:00 AM, Roelof Wobben wrote: > > Hello, > > > > I have this programm : > > > > def remove_letter(letter, strng): > """ > >>> remove_letter('a', 'apple') > 'pple' > >>> remove_letter('a', 'banana') > 'bnn' > >>> remove_letter('z', 'banana') > 'banana' > >>> remove_letter('i', 'Mississippi') > 'Mpp' > """ > antwoord="" > for letter in strng: > print letter, strng > if letter in strng: > print "false" > else: > print "true" > return antwoord > > > > x=remove_letter('a', 'apple') > print x > > > > But now everything is false even a in apple. > > > > What is here wrong ? > I'm assuming what you really want is : if letter in strng: print "true" else: print "false" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
"Roelof Wobben" wrote ## def remove_letter(letter, strng): antwoord="" for letter in strng: print letter, strng if letter in strng: print "false" else: print "true" return antwoord ## Several issues: 1) You never use antwoord so it alweays returns "" 2) you print false when the letter IS in the string 3) You use letter as an input parameter but then overwrite it in the for loop. 4) your if test would be better written as print (letter in string) (The parens aren't necessary but I think make it clearer that we are printing the evaluation of an expression not just a string with missing quotes...) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
"Roelof Wobben" wrote It's for learning purposed but I forget that de module string has built in functions.Thank you for remainding it to me. Its not the string module that Christian is referring to, its the methods of string objects - different things: You can do: import string string.replace(aString, aChr, another) # use string module But its better to do aString.replace(aChr, another) # use string method HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Function object
"Daniel" wrote another problem regarding understanding a concept- function object. As I said, I do not understand what a function object is, what it does, and what can I do with it? You are actually using them all the time. Every function in Python is a function object. You can execute the function by putting parenthesesc after its name(filled with any required arguments) def foo(): return None defines a function object called foo that does nothing but return None. We can rewrite that using the lambda operator which returns function objects with no name: foo = lambda : None This assigns an anonymous function object to a variable foo - thus giving it a name, just like any other variable. In both cases we can now call the function with: foo() The advantage of treating functions as objects is that we can store them and then call them later. This is the basis of event driven programming and GUIs. It also allows us to easily build reconfigurable dynamic logic into applications - just by changing the order in which functions are called. It also allows us to create functions which return functions as their output, but this is getting into deeper water, so I'll ignore that for now! :-) You will find a slightly different explanation in the Functional Programming topic of my tutorial HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need URGENT support ... PL
Hi all, I have been getting support on this from the list, but unfortunately now it has become URGENT that i get some solution to this problem i need to resolve. What i have done is create FileA.CSV whose structure is as follows :- (no blank spaces, this is just for representation) /home/nitin/path/To/PRl1/File1.csv , /home/nitin/path/To/PR3/File1.csv , /home/nitin/path/To/PR2/File1.csv /home/nitin/path/To/PRl1/File2.csv , /home/nitin/path/To/PR3/File2.csv , /home/nitin/path/To/PR2/File2.csv /home/nitin/path/To/PRl1/File3.csv , /home/nitin/path/To/PR3/File3.csv , /home/nitin/path/To/PR2/File3.csv /home/nitin/path/To/PRl1/File4.csv , /home/nitin/path/To/PR3/File4.csv , /home/nitin/path/To/PR2/File4.csv ... ... (96) rows The first column is INPUT Protocol-1 File1 Second Column is INPUT Protocol-3 File1 Third Column is OUTPUT Protocol-2 File1 Each File (eg. PR1/File1 , PR3/File1 ) have approx. 600 rows of 39 column, numeric data. These data files end in a blank new line / blank line. Through the following code I am trying to read the TWO input files, extract columns, Add , Divide (take mean of the values) and write to THEIR respective OUTPUT files. My script reads the first file and displays all the rows (print) from PR1/File1 and then program terminates. IT does not read the Second file (PR3/File1) and therefore i am unable to write the result out to the OUTPUT file (PR2/File1). Earlier I was able to create ONE file ... like the loop would run ONCE and would not do the same process to the NEXT set of files (PR1/File2 , PR3/File2 , PR2/File2) and do the same till it has done processing all the 96 set of files. here is the code PL ... PL I REALLY need this solution. * import sys, os, fileinput FileA = raw_input('Enter CSV file with List of Files :') try: fp1 = open(FileA,'r') #print fp1 except IOError: sys.exit('Could not open File : %s' % FileA) for rows in fp1: #print rows row11 = rows.split(",") #print row1 row1 = row11[0] row2 = row11[1] row3 = row11[2] #print row1 #print row2 #print row3 try: fp2 = open(row1,'r') #print fp2 except IOError: sys.exit('Could not open File %s.' % fp2) try: fp3 = open(row2,'r') #print fp3 except IOError: sys.exit('Could not open File %s.' % fp3) try: fp4 = open(row3,'w') #print fp4 except IOError: sys.exit('Could not open File %s to write.' % fp4) row21 = fp2.readline().split(",") row31 = fp3.readline().split(",") #print row21 row22 = row21[0] row23 = row21[1] row24 = row21[2] row25 = row21[3] row26 = row21[21] row27 = row21[22] row28 = row21[23] row32 = row31[1] row33 = row31[2] row34 = row31[3] row35 = row31[21] row36 = row31[22] row37 = row31[23] print "PR1", row22, row23, row24, row25, row26, row27, row28, "PR3", row32, row33, row34, row35, row36, row37 ## Doing the Addition is also not the problem. I am not able to put this ## whole process in a loop. ## do the calculation and write to file. ## and do the same thing with the next set of files. Till 96 sets ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need URGENT support ... PL
sorry missed; with current code IT is reading / prints ONLY first lines for each 96 set of files are displayed. DOES NOT go the Next row or the Next Set of Files. PL PL ... give me the solution. Thanks Nitin * PR1 0.00 0.153436 0.016740 1.362566 -0.031154 1.132133 0.266704 PR3 -0.047642 0.059674 0.271700 0.047802 -0.085366 0.016262 PR1 0.005000 0.137681 0.063328 1.396118 0.015738 1.374378 0.313304 PR3 -0.008209 0.059674 0.339661 -0.046058 0.087159 0.008836 PR1 0.01 0.200700 0.008988 1.431611 0.007935 1.478203 0.285076 PR3 -0.047827 0.075154 0.201622 -0.022574 0.087495 0.027239 PR1 0.015000 0.145697 0.016801 1.431463 -0.023277 1.651546 0.333441 PR3 -0.023871 0.082955 0.547534 0.040449 0.053501 -0.059713 PR1 0.00 -3.404975 -0.965380 26.688482 -0.538069 7.530815 -0.076355 PR3 1.736750 0.261636 7.920164 0.579122 2.579521 -0.468668 PR1 0.005000 -3.381482 -1.012078 26.964482 -0.546172 7.566007 -0.104835 PR3 1.784014 0.315952 7.989384 0.634342 2.439866 -0.584216 PR1 0.01 -3.358453 -1.004423 26.654238 -0.530866 7.150382 -0.085785 PR3 1.807878 0.362540 7.748612 0.595252 2.581121 -0.335703 PR1 0.015000 -3.327500 -0.880397 26.480582 -0.593364 7.323216 -0.056011 PR3 1.736750 0.347047 7.886282 0.429967 2.304293 -0.275297 PR1 0.00 -0.004793 0.030768 0.356952 -0.036841 0.332747 -0.087458 PR3 -1.433546 -0.237249 7.929407 -0.446087 2.454336 0.326635 PR1 0.005000 -0.020455 -0.008018 0.461187 -0.036616 0.367250 -0.077974 PR3 -1.401758 -0.229472 7.722859 -0.548049 2.662068 0.290733 PR1 0.01 -0.067348 -0.046731 0.218824 -0.036541 0.263715 -0.087470 PR3 -1.457039 -0.237212 7.618937 -0.485251 2.350271 0.318161 PR1 0.015000 -0.043669 -0.039003 0.322279 -0.052372 0.506002 -0.096786 PR3 -1.449300 -0.229472 7.687630 -0.563655 2.593573 0.233980 PR1 0.00 1.641553 0.391073 13.009227 0.214600 1.953616 0.015595 PR3 0.146105 0.032141 0.840999 0.006657 0.178160 -0.130106 PR1 0.005000 1.681172 0.391073 13.008975 0.222178 2.196009 0.025139 PR3 0.114503 0.024401 0.946306 0.124525 -0.235777 0.057199 PR1 0.01 1.649384 0.391061 13.042360 0.238084 2.334502 0.005910 PR3 0.082993 0.032141 0.876697 0.156186 0.283311 -0.066508 PR1 0.015000 1.673248 0.429835 12.801305 0.214450 2.231176 0.091931 PR3 0.106672 0.016600 1.049760 0.054149 -0.858067 0.058464 PR1 0.00 -0.130893 -0.171140 0.332583 -0.030145 1.476301 -0.362464 PR3 0.051427 -0.025635 0.600788 0.118771 0.509802 -0.041242 PR1 0.005000 -0.115045 -0.171091 0.470262 -0.014539 1.685376 -0.458278 PR3 0.020196 -0.048916 0.290571 0.001202 0.129074 -0.048434 PR1 0.01 -0.099198 -0.194348 0.297432 0.001141 1.442160 -0.391747 PR3 -0.027253 -0.025610 0.532962 -0.006900 -0.147851 -0.029492 PR1 0.015000 -0.130522 -0.186620 0.712175 0.008944 1.339193 -0.401560 PR3 0.059166 -0.010105 0.188483 0.024012 0.302548 -0.001217 On Thu, Aug 26, 2010 at 1:10 AM, nitin chandra wrote: > Hi all, > > I have been getting support on this from the list, but unfortunately > now it has become URGENT that i get some solution to this problem i > need to resolve. > > What i have done is create FileA.CSV whose structure is as follows :- > (no blank spaces, this is just for representation) > /home/nitin/path/To/PRl1/File1.csv , /home/nitin/path/To/PR3/File1.csv > , /home/nitin/path/To/PR2/File1.csv > /home/nitin/path/To/PRl1/File2.csv , /home/nitin/path/To/PR3/File2.csv > , /home/nitin/path/To/PR2/File2.csv > /home/nitin/path/To/PRl1/File3.csv , /home/nitin/path/To/PR3/File3.csv > , /home/nitin/path/To/PR2/File3.csv > /home/nitin/path/To/PRl1/File4.csv , /home/nitin/path/To/PR3/File4.csv > , /home/nitin/path/To/PR2/File4.csv > ... > ... > (96) rows > > The first column is INPUT Protocol-1 File1 > Second Column is INPUT Protocol-3 File1 > Third Column is OUTPUT Protocol-2 File1 > > Each File (eg. PR1/File1 , PR3/File1 ) have approx. 600 rows of 39 > column, numeric data. These data files end in a blank new line / blank > line. > > Through the following code I am trying to read the TWO input files, > extract columns, Add , Divide (take mean of the values) and write to > THEIR respective OUTPUT files. > > My script reads the first file and displays all the rows (print) from > PR1/File1 and then program terminates. IT does not read the Second > file (PR3/File1) and therefore i am unable to write the result out to > the OUTPUT file (PR2/File1). > > Earlier I was able to create ONE file ... like the loop would run ONCE > and would not do the same process to the NEXT set of files (PR1/File2 > , PR3/File2 , PR2/File2) and do the same till it has done > processing all the 96 set of files. > > here is the code > PL ... PL I REALLY need this solution. > > * > import sys, os, fileinput > > > FileA = raw_input('Enter CSV file with List of Files :') > try: > fp1 = open(FileA,'r') > #print fp1 > except IOError: > sys.exit('Could not open File : %s' % FileA) > > for rows in fp1: > #print rows > row11 = rows.split(",") >
Re: [Tutor] why does this fail
On Thu, 26 Aug 2010 04:18:28 am Greg Bair wrote: > I'm assuming what you really want is : > > if letter in strng: > print "true" > else: > print "false" Oh I hope not... the above is better written as: print letter in strng (assuming you don't care about the difference between "True" and "true"). -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need URGENT support ... PL
On Thu, 26 Aug 2010 05:40:33 am nitin chandra wrote: > Hi all, > > I have been getting support on this from the list, but unfortunately > now it has become URGENT that i get some solution to this problem i > need to resolve. Is it "URGENT" enough that you would consider paid support? Or are you asking for free support *and* immediate responsiveness as well? If so, why is *your* urgency important to us? > Through the following code I am trying to read the TWO input files, > extract columns, Add , Divide (take mean of the values) and write to > THEIR respective OUTPUT files. > > My script reads the first file and displays all the rows (print) from > PR1/File1 and then program terminates. IT does not read the Second > file (PR3/File1) and therefore i am unable to write the result out to > the OUTPUT file (PR2/File1). "Divide and conquer" is the most important programming principle. When a task is too complicated, break it into little pieces and solve each little piece alone. That's why functions exist! Instead of one great big script that tries to do everything, break the problem into functions. You have a file that has the format: filename1,filename3,filename2 repeated for many lines. Write a function that takes a *single* line and splits it into three filenames. That's easy: def get_names(input_line): return input_line.strip().split(',') Now write a function that does that to each and every line in a file: def process_input_file(filename): for line in open(filename): f1, f3, f2 = input_line.strip().split(',') process(f1, f3, f2) Now write the process function: def process(infile1, infile2, outfile): """Read files infile1 and infile2, do something to their content line-by-line, and write the output to outfile. """ # whatever... And then write your calculate function that operates on one row at a time: def calculate(line1, line2): # whatever... Just make sure it returns a string ending with a newline "\n". And finally, put it all together: if __name__ == '__main__': filename = raw_input("Enter the name of the file: ") process_input_file(filename.strip()) And that should be it. If there are any problems, they will be easy to diagnose because you can isolate them to one small function instead of one big, confusing script. Do not use try...except and sys.exit to disguise where exceptions occur. If there is a bug or an error, you want to see the full traceback, not just a generic, useless error message. I can't remember how much the company I work for charges for a monthly four-hour service level agreement, but we charge AUD$300 for ad-hoc priority service plus $150 an hour for consulting. Since I'm doing this in my own time, I'll do it for half that. You get the above for free because I'm a nice guy. (Or maybe a sucker.) If you still need "URGENT" support, contact me and we'll make arrangements. Either that, or just wait until somebody feels like answering. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
Steven D'Aprano wrote: > Other than using numpy, probably the simplest solution is to just > subclass tuple and give it named properties and whatever other methods > you want. Here's a simple version: > > class Point(tuple): > [snip] > > What it doesn't give you (yet!) is: > > * distance between Points with different dimensions could easily be > defined just by removing the len() comparison. zip() will > automatically terminate at the shortest input, thus projecting the > higher-dimension point down to the lower-dimension point; > * other distance methods, such as Manhattan distance; > * a nice exception when you as for (say) pt.z from a 2-D point, instead > of raising IndexError; > * point arithmetic (say, adding two points to get a third). I hope you'll suffer me one more question on this thread. In thinking about creating other distance methods (as you suggest), how best to create a generic enough interface, so that ANY distance metric could be used. It seems like coding the Point class with multiple distance methods is not very flexible, especially if you wanted to iterate over those methods for any two points, e.g. class Point(tuple): def euclidean_distance(self, other): ... def manhattan_distance(self, other): ... def any_other_distance(self, other): ... Would this be a place for a generic get_distance with a DistanceMetric subclass as a parameter, e.g. class DistanceMetric(object): def distance(self, p1, p2): assert 0, 'Must be defined in subclasses' class EuclideanDistMetric(DistanceMetric): def distance(self, p1, p2): ... class Point(tuple): def get_distance(self, other, metric): distance = metric.distance(self, other) return distance I'm sure I don't have all my syntax correct. Thanks for continued help. matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Trouble with exercise regarding classes
I just starting programming and am trying to learn some python (ver 2.6). I am reading Python Programming: An Introduction to Computer Science by John Zelle. In chapter ten, the first programming exercise asks the reader to modify code from the chapter (below) . The code I added is highlighted. However, when I did so I got this error: "TypeError: unbound method getY() must be called with Projectile instance as first argument (got nothing instead) " Can someone help me out with what I am doing wrong? Please be as straitforward as you can. I am still struggling with classes Thanks a lot # cball4.py > # Simulation of the flight of a cannon ball (or other projectile) > # This version uses a separate projectile module file > > from projectile import Projectile > > def getInputs(): > a = input("Enter the launch angle (in degrees): ") > v = input("Enter the initial velocity (in meters/sec): ") > h = input("Enter the initial height (in meters): ") > t = input("Enter the time interval between position calculations: ") > return a,v,h,t > > def main(): > angle, vel, h0, time = getInputs() > cball = Projectile(angle, vel, h0) > zenith = 0.0 > while cball.getY() >= 0: > cball.update(time) > if Projectile.getY > zenith: > zenith = Projectile.getY() > print "\nDistance traveled: %0.1f meters." % (cball.getX()) > print "The heighest the cannon ball reached was %0.1f meters." % > (zenith) > > if __name__ == "__main__": main() > > > # projectile.py > > """projectile.py > Provides a simple class for modeling the flight of projectiles.""" > > from math import pi, sin, cos > > class Projectile: > > """Simulates the flight of simple projectiles near the earth's > surface, ignoring wind resistance. Tracking is done in two > dimensions, height (y) and distance (x).""" > > def __init__(self, angle, velocity, height): > """Create a projectile with given launch angle, initial > velocity and height.""" > self.xpos = 0.0 > self.ypos = height > theta = pi * angle / 180.0 > self.xvel = velocity * cos(theta) > self.yvel = velocity * sin(theta) > > def update(self, time): > """Update the state of this projectile to move it time seconds > farther into its flight""" > self.xpos = self.xpos + time * self.xvel > yvel1 = self.yvel - 9.8 * time > self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0 > self.yvel = yvel1 > > def getY(self): > "Returns the y position (height) of this projectile." > return self.ypos > > def getX(self): > "Returns the x position (distance) of this projectile." > return self.xpos > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] args to functions in a dictionary?
Hi all, If I wanted to have a dictionary containing functions, could I pass args to those functions? For example: menu={ "option 1":f1, "option 2":f2 } How would I pass args to f1 or f2 in this case? TIA. -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] args to functions in a dictionary?
On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall wrote: > Hi all, > If I wanted to have a dictionary containing functions, could I pass > args to those functions? For example: > menu={ > "option 1":f1, > "option 2":f2 > } > How would I pass args to f1 or f2 in this case? TIA. You sure could, because functions are first order citizens in python, meaning you can pass them around like any other data type. menu['option 1']() is how you would call the functions, and you'd just put an args/kwargs in the parenthesis. Conceptually you can replace menu['option 1'] with f1, so anywhere you see this: menu['option 1'](arg1) you can replace it with f1(arg1) I don't know if Python does that exact thing on the back end, but the end result is certainly the same. HTH, Wayne (p.s. Gmail's undo sending feature is terribly nice when I forget to reply-all) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] args to functions in a dictionary?
On 8/25/10, Wayne Werner wrote: > On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall wrote: > >> Hi all, >> If I wanted to have a dictionary containing functions, could I pass >> args to those functions? For example: >> menu={ >> "option 1":f1, >> "option 2":f2 >> } >> How would I pass args to f1 or f2 in this case? TIA. > > > You sure could, because functions are first order citizens in python, > meaning you can pass them around like any other data type. > > menu['option 1']() is how you would call the functions, and you'd just put > an args/kwargs in the parenthesis. Of course! So simple, yet somehow I did not see it. Thanks! > > Conceptually you can replace menu['option 1'] with f1, so anywhere you see > this: > > menu['option 1'](arg1) > > you can replace it with > > f1(arg1) > > I don't know if Python does that exact thing on the back end, but the end > result is certainly the same. > > HTH, > Wayne > > (p.s. Gmail's undo sending feature is terribly nice when I forget to > reply-all) > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
"Gregory, Matthew" wrote . It seems like coding the Point class with multiple distance methods is not very flexible, especially if you wanted to iterate over those methods for any two points Its flexible enough provided you keep the interface to points. In other words if the distance is expressed as the difference between two points that can be worked out regardless of representation. The trick is to always keep the interface as free of internal representation detail as possible. However, you may not be able to provide concrete implementations of those methods at the level of Point - which means Point turns into an abstract class. Alternatively you may implement the methods in such way that they call still other methods to perform data conversions (polar-cartesian say) or generate default values where none exist - generating an X,Y from a list of dimensions maybe. And the Point class implementation of those conversions may be trivial. There are seveal ways to do this and none of them are perfect and none of them are "right" - although a few of them might be considered "wrong"!. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with exercise regarding classes
"Andrew Martin" wrote However, when I did so I got this error: "TypeError: unbound method getY() must be called with Projectile instance as first argument (got nothing instead) " def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) cball is a Projectile instance zenith = 0.0 while cball.getY() >= 0: So this is fine cball.update(time) if Projectile.getY > zenith: zenith = Projectile.getY() But what are you doing here? You are trying to compare the getY method of the class with a floating point number? Then you call getY using the class rather than the instance? I'm confused - and so is Python... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such file or directory
in a gui > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; >reply-type=original > > > "Karim" wrote > > > Is there any equivalent to JAVACC in python (or lex yacc) to create > > grammary > > for config or format file? > > Thats kind of what ConfiogParser does - it gives you tools to > read/write > a config file. > > If you don't mind the data not being human readable you could also > use the shelve module which simulates a dictionary in a file. > > There are lots of options. > > Alan G. > > > > > -- > > Message: 4 > Date: Wed, 25 Aug 2010 08:30:59 +0100 > From: "Alan Gauld" > To: tutor@python.org > Subject: Re: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No >suchfileor directory > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; >reply-type=original > > > "Carter Danforth" wrote > > > Anyhow, I can't seem to be executing any files in terminal for some > > reason, in this case the file ex1.py: > > > > C:\Users\Carter Danforth\python ex1.py > > python: can't open file 'ex1.py': [Errno 2] No such file or > > directory > > > > ex1.py is located in "pythonpractice" on my desktop and I've updated > > the > > modules, here's the output from sys.path: > > sys.path (and PYTHONPATH) only affect how imports work within > Python, they have no effect on Windows ability to find scripts. > To run a script you must do one of the following: > > 1) CD to the script folder and run Python from there as: > > Python myscript.py > > 2) From anywhere execute Python as >> python full\path\to\myscript.py > > 3) From anywhere execute myscript as > > myscript.py > > For 1,2 PATH must include the Python executable folder > For 3 the .py extension must be associated with the Python > executable and the folder containing myscript must be in PATH. > > > I'm not sure why I keep getting this error message and why I'm not > > able to > > execute any .py files. Any help would be great appreciated. > > Windows needs to know where the file lives. You could have many > files called myscript.py in your file system. PYTHONPATH is used > only by Python and only for imports. PATH is used only for > executables. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > -- > > Message: 5 > Date: Wed, 25 Aug 2010 01:28:47 -0700 (PDT) > From: Albert-Jan Roskam > To: Python Mailing List > Subject: [Tutor] os.access unreliable? > Message-ID: <502129.63760...@web110716.mail.gq1.yahoo.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi, > > Hi I'm using os.access to do a preliminary check to see if I have RW > access, but > it seems to be unreliable. In a dir for which I have only read access, > os.access > also says I have write access. This is under Windows 2000. I could of > course use > a try-except and catch the IOError, but I'd like to know why the code below > isn;t working. > > ??? def isAcccessible(self): > ??? if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK): > ??? return True > ??? else: > ??? return False > ?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: < > http://mail.python.org/pipermail/tutor/attachments/20100825/3a660844/attachment-0001.html > > > > -- > > Message: 6 > Date: Wed, 25 Aug 2010 09:53:08 +0100 > From: Tim Golden > Cc: Python Mailing List > Subject: Re: [Tutor] os.access unreliable? > Message-ID: <4c74d9f4.3030...@timgolden.me.uk> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 25/08/2010 09:28, Albert-Jan Roskam wrote: > > Hi, > > > > Hi I'm using os.access to do a preliminary check to see if I have RW > access, but > > it seems to be unreliable. In a dir for which I have only read access, > os.access > > also says I have write
Re: [Tutor] Function object
Daniel, Considering that Python is your first programming language, let's start from the absolute beginning. Before you think about what a function object is, try to understand what a function is. A function is a series of python commands put together under a common heading or name in order to achieve a specific task. A function can receive parameters from the main program, perform some operations using the parameters and return value(s) to the main program. In the following example, add is a function and it, like all other functions is defined using the def statement: def add(x,y): sum=x+y# python commands here return sum The x and y are parameters or arguments that you pass to the function add. x and y can be anything depending on what you want your function to do. In our particular example x and y will be numbers (assuming, integers) because the add function will take the parameters, adds them together and temporarily save the result in a variable called sum. The return statement will then take the result of the addition and send it back to the main program. When this happens the sum variable you created inside the function will go out of scope (i.e. you will not be able to refer to it any more). To use the function above say you have the following snippet in a file called foo.py: foo.py def add(x,y): sum=x+y return sum if __name__=="__main__":# Execution of code starts here when you type ">>> python foo.py". Python knows you defined add above. Think of this as the main program. result=add(1,1)# You are calling add and storing the value returned into a variable called result print result# Assuming you are using Python2.X Type >>> python foo.py Run it and see what happens. You should get the answer 2. From the main program, you are calling the function add and storing the value that it returns into a variable called result. Then you are printing that value to screen. Once you get to learning about classes you will get a better understanding of why a function in python is an object but I think you should try to get the mechanics down first. Experiment! Good luck. Denis On Wed, Aug 25, 2010 at 2:44 PM, Alan Gauld wrote: > > "Daniel" wrote > > > another problem regarding understanding a concept- function object. As I >> said, I do not understand what a function object is, what it does, and >> what >> can I do with it? >> > > You are actually using them all the time. > Every function in Python is a function object. > You can execute the function by putting parenthesesc after its name(filled > with any required arguments) > > def foo(): return None > > defines a function object called foo that does nothing but return None. > > We can rewrite that using the lambda operator which returns function > objects with no name: > > foo = lambda : None > > This assigns an anonymous function object to a variable foo - thus giving > it a name, just like any other variable. > > In both cases we can now call the function with: > > foo() > > The advantage of treating functions as objects is that we can store them > and then call them later. This is the basis of event driven programming > and GUIs. It also allows us to easily build reconfigurable dynamic logic > into applications - just by changing the order in which functions are > called. > > It also allows us to create functions which return functions as their > output, > but this is getting into deeper water, so I'll ignore that for now! :-) > > You will find a slightly different explanation in the Functional > Programming > topic of my tutorial > > > HTH > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with exercise regarding classes
All I want to do is add a line that displays that maximum height the cannonball reaches. I created a variable zenith to store the highest y value. I then wanted to compare the current y value of the cannonball to zenith while the cannonballs y value is greater than zero. If the cannonballs current y value is greater than zenith, I want to have the current value replace zenith. Finally, once the cannonball has reaches y = 0, I wanted the program to write out the value for zenith. I want to compare zenith, a floating point number, with the current y value? I thought the current y value could be retrieved by Projectile.getY. And how do I call the getY using the instance? On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote: > > "Andrew Martin" wrote > > > However, when I did so I got this error: "TypeError: unbound method getY() >> must be called with Projectile instance as first argument (got nothing >> instead) " >> > > def main(): >>>angle, vel, h0, time = getInputs() >>>cball = Projectile(angle, vel, h0) >>> >> > cball is a Projectile instance > > > zenith = 0.0 >>>while cball.getY() >= 0: >>> >> > So this is fine > > > cball.update(time) >>> >> > > if Projectile.getY > zenith: >>>zenith = Projectile.getY() >>> >> > But what are you doing here? > You are trying to compare the getY method of the class with a floating > point number? > Then you call getY using the class rather than the instance? > I'm confused - and so is Python... > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] continuous running of a method
> Any modern multi-tasking operating system will ensure than a while loop > doesn't kill your computer's responsiveness. A decent operating system > will still remain responsive even at 100% CPU usage. Even Windows does > that! Opinions vary. If you try this on a laptop, the end user will be quite annoyed to see their battery drop to zero, their cooling fans go into overdrive, and to receive first degree burns on their hands and/or lap. Busywaiting my cpu makes your program an instant candidate for immediate deletion. Maybe that's just me :) Alan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with exercise regarding classes
On 8/25/10, Andrew Martin wrote: > All I want to do is add a line that displays that maximum height the > cannonball reaches. I created a variable zenith to store the highest y > value. I then wanted to compare the current y value of the cannonball to > zenith while the cannonballs y value is greater than zero. If the > cannonballs current y value is greater than zenith, I want to have the > current value replace zenith. Finally, once the cannonball has reaches y = > 0, I wanted the program to write out the value for zenith. > > I want to compare zenith, a floating point number, with the current y value? > I thought the current y value could be retrieved by Projectile.getY. And how It can, but you need parentheses after the function call. > do I call the getY using the instance? I think the problem may be where you say ball.getY instead of ball.getY() When you hear "instance", do not panic. An instance is just a variable of type class. For example, "ball" is an instance of the Projectile class. As an example, if I had a "pet" class, I might make a "dog" variable of type pet: dog=Pet() After I have my dog set up, since it is an instance of the Pet class, it has all the methods available in the Pet class. I might say dog.speak() which would just look at my Pet class for a "speak" method, and call it. In the same way, you have a "ball" variable which is a Projectile, so you have all the methods and variables from the Projectile class available in the "ball" variable. Note that, if a variable is of type class, it is also called an object, so I could have as easily called the "ball" a Projectile object. > > > > On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld > wrote: > >> >> "Andrew Martin" wrote >> >> >> However, when I did so I got this error: "TypeError: unbound method >> getY() >>> must be called with Projectile instance as first argument (got nothing >>> instead) " >>> >> >> def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) >>> >> cball is a Projectile instance >> >> >> zenith = 0.0 while cball.getY() >= 0: >>> >> So this is fine >> >> >> cball.update(time) >>> >> >> if Projectile.getY > zenith: zenith = Projectile.getY() >>> >> But what are you doing here? >> You are trying to compare the getY method of the class with a floating >> point number? >> Then you call getY using the class rather than the instance? >> I'm confused - and so is Python... >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> ___ >> Tutor maillist - Tutor@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) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with exercise regarding classes
There are 2 ways to get the ypos value one is cball.ypos and another is call.getY() both will give u the current ypos. --nitin On Thu, Aug 26, 2010 at 7:26 AM, Andrew Martin wrote: > All I want to do is add a line that displays that maximum height the > cannonball reaches. I created a variable zenith to store the highest y > value. I then wanted to compare the current y value of the cannonball to > zenith while the cannonballs y value is greater than zero. If the > cannonballs current y value is greater than zenith, I want to have the > current value replace zenith. Finally, once the cannonball has reaches y = > 0, I wanted the program to write out the value for zenith. > > I want to compare zenith, a floating point number, with the current y > value? I thought the current y value could be retrieved by Projectile.getY. > And how do I call the getY using the instance? > > > > > On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote: > >> >> "Andrew Martin" wrote >> >> >> However, when I did so I got this error: "TypeError: unbound method >>> getY() >>> must be called with Projectile instance as first argument (got nothing >>> instead) " >>> >> >> def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) >>> >> cball is a Projectile instance >> >> >> zenith = 0.0 while cball.getY() >= 0: >>> >> So this is fine >> >> >> cball.update(time) >>> >> >> if Projectile.getY > zenith: zenith = Projectile.getY() >>> >> But what are you doing here? >> You are trying to compare the getY method of the class with a floating >> point number? >> Then you call getY using the class rather than the instance? >> I'm confused - and so is Python... >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trouble with exercise regarding classes
Andrew, For starters you have some errors in the way you are trying to access methods from within a class instances. For example in your code in line 7 and 8, def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) zenith = 0.0 while cball.getY() >= 0: cball.update(time) if Projectile.getY > zenith: # This should be -- if cball.getY()>zenith: zenith = Projectile.getY() # This should be -- zenith = cball.getY() print "\nDistance traveled: %0.1f meters." % (cball.getX()) print "The heighest the cannon ball reached was %0.1f meters." % (zenith) You access the method of an instance using the instance name that you created on line 3, not the class name. Secondly, you have to change the time variable so that the value of cball.getY() changes or else nothing will happen. Assuming that the time you are entering is a delta_t value, you can create another variable say actual_time which starts at 0 and add delta_t to it at the end of the while loop each time through. actual_time=actual_time+delta_t This will update your Y position because you will be calling cball.update(actual_time). You will converge to a solution. Good luck, Denis On Wed, Aug 25, 2010 at 9:56 PM, Andrew Martin wrote: > All I want to do is add a line that displays that maximum height the > cannonball reaches. I created a variable zenith to store the highest y > value. I then wanted to compare the current y value of the cannonball to > zenith while the cannonballs y value is greater than zero. If the > cannonballs current y value is greater than zenith, I want to have the > current value replace zenith. Finally, once the cannonball has reaches y = > 0, I wanted the program to write out the value for zenith. > > I want to compare zenith, a floating point number, with the current y > value? I thought the current y value could be retrieved by Projectile.getY. > And how do I call the getY using the instance? > > > > > On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote: > >> >> "Andrew Martin" wrote >> >> >> However, when I did so I got this error: "TypeError: unbound method >>> getY() >>> must be called with Projectile instance as first argument (got nothing >>> instead) " >>> >> >> def main(): angle, vel, h0, time = getInputs() cball = Projectile(angle, vel, h0) >>> >> cball is a Projectile instance >> >> >> zenith = 0.0 while cball.getY() >= 0: >>> >> So this is fine >> >> >> cball.update(time) >>> >> >> if Projectile.getY > zenith: zenith = Projectile.getY() >>> >> But what are you doing here? >> You are trying to compare the getY method of the class with a floating >> point number? >> Then you call getY using the class rather than the instance? >> I'm confused - and so is Python... >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
Hello Alan, Oops, then I have a problem. Im following this book : http://openbookproject.net/thinkcs/python/english2e/ which is the first link in the beginners tutorial page. And it's talking about the string modules. Roelof Date: Wed, 25 Aug 2010 15:49:14 -0700 From: alan.ga...@btinternet.com Subject: Re: [Tutor] why does this fail To: rwob...@hotmail.com Thats OK, I only replied because what you said could genuinely have been a mistake because some old tutorials still refer to the string module amnd its functions. Because other begineers may read the post too it was important to make the distinction. Regards, Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From: Roelof Wobben To: alan.ga...@btinternet.com Sent: Wednesday, 25 August, 2010 19:38:03 Subject: RE: [Tutor] why does this fail Oke, That's what I ment. Apolize for the bad English. It's not the language I often use. Roelof > To: tutor@python.org > From: alan.ga...@btinternet.com > Date: Wed, 25 Aug 2010 19:32:59 +0100 > Subject: Re: [Tutor] why does this fail > > > "Roelof Wobben" wrote > > > It's for learning purposed but I forget that de module string > > has built in functions.Thank you for remainding it to me. > > Its not the string module that Christian is referring to, > its the methods of string objects - different things: > > > You can do: > > import string > string.replace(aString, aChr, another) # use string module > > But its better to do > > aString.replace(aChr, another) # use string method > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (no subject)
Hello, I have this exercise : Try each of the following formatted string operations in a Python shell and record the results: “%s %d %f” % (5, 5, 5) “%-.2f” % 3 “%-10.2f%-10.2f” % (7, 1.0/2) print ” $%5.2fn $%5.2fn $%5.2f” % (3, 4.5, 11.2) But if I try in a python 2.7 IDLE enviroment I get this : >>> %s %d %f % (5, 5, 5) SyntaxError: invalid syntax >>> print “%s %d %f” % (5, 5, 5) SyntaxError: invalid syntax Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] What Design Pattern for Document class (NOT URGENT)
Hello All, I want to build some classes by optimizing their design. But I want to keep quite 'simples'. I have a XML document which represents let's say some rules (id, description, value). My first idea is to create an *docrules* class which holds my document. This class will use 2 other instances from 2 respectives classes reader and writer. The main method of reader is get(). The main method of writer is write(). To resume I have: -- --- - docrules --- reader - -- --- - filename - - file - - --- - - - get() - - ------ -- - - - ---writer- - file - - write() - The *docrules* will do the parsing (*xml.etree* very effective) and create the reader and the writer instance. I want to create 2 others classes (or more) more specific which have more the knowledge about the XML documents structures. *SpecificRuleReader*, *SpecificRuleWriter* which are deriving resp. from Reader and Writer which hold resp. *getSpecificRules*() (use of get('/tag1/tag2/tag3/specificTagRules') and a* writeSpecificRules*(): - - reader writer - - ^ ^ || --- --- *SpecificRuleReader* *SpecificRulesWriter* --- --- *getSpecificRules*() *writeSpecificRules()* -- My purpose is to separate as far as possible XML representation from core classes. I will have certainly more SpecificrulesReader/Writer classes becauses the document is huge and several discipline rules will be adressed. I don't want necessarily have 2 big classes which know everything about XML document because I will have too many methods. So, for if anybody has this kind of experience or any design pattern idea, I will be enchanté. Regards Karim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor